#!/usr/bin/env node
const __OPENSWARM_IMPORT_META_URL__ = require("url").pathToFileURL(__filename).href;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esm = (fn, res, err) => function __init() {
  if (err) throw err[0];
  try {
    return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
  } catch (e2) {
    throw err = [e2], e2;
  }
};
var __commonJS = (cb, mod) => function __require() {
  try {
    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  } catch (e2) {
    throw mod = 0, e2;
  }
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// node_modules/bson/lib/bson.cjs
var require_bson = __commonJS({
  "node_modules/bson/lib/bson.cjs"(exports2) {
    "use strict";
    var TypedArrayPrototypeGetSymbolToStringTag = (() => {
      const g = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
      return (value) => g.call(value);
    })();
    function isUint8Array(value) {
      return TypedArrayPrototypeGetSymbolToStringTag(value) === "Uint8Array";
    }
    function isAnyArrayBuffer(value) {
      return typeof value === "object" && value != null && Symbol.toStringTag in value && (value[Symbol.toStringTag] === "ArrayBuffer" || value[Symbol.toStringTag] === "SharedArrayBuffer");
    }
    function isRegExp(regexp2) {
      return regexp2 instanceof RegExp || Object.prototype.toString.call(regexp2) === "[object RegExp]";
    }
    function isMap(value) {
      return typeof value === "object" && value != null && Symbol.toStringTag in value && value[Symbol.toStringTag] === "Map";
    }
    function isDate(date5) {
      return date5 instanceof Date || Object.prototype.toString.call(date5) === "[object Date]";
    }
    function defaultInspect(x2, _options) {
      return JSON.stringify(x2, (k, v) => {
        if (typeof v === "bigint") {
          return { $numberLong: `${v}` };
        } else if (isMap(v)) {
          return Object.fromEntries(v);
        }
        return v;
      });
    }
    function getStylizeFunction(options) {
      const stylizeExists = options != null && typeof options === "object" && "stylize" in options && typeof options.stylize === "function";
      if (stylizeExists) {
        return options.stylize;
      }
    }
    var BSON_MAJOR_VERSION = 7;
    var BSON_VERSION_SYMBOL = /* @__PURE__ */ Symbol.for("@@mdb.bson.version");
    var BSON_INT32_MAX = 2147483647;
    var BSON_INT32_MIN = -2147483648;
    var BSON_INT64_MAX = Math.pow(2, 63) - 1;
    var BSON_INT64_MIN = -Math.pow(2, 63);
    var JS_INT_MAX = Math.pow(2, 53);
    var JS_INT_MIN = -Math.pow(2, 53);
    var BSON_DATA_NUMBER = 1;
    var BSON_DATA_STRING = 2;
    var BSON_DATA_OBJECT = 3;
    var BSON_DATA_ARRAY = 4;
    var BSON_DATA_BINARY = 5;
    var BSON_DATA_UNDEFINED = 6;
    var BSON_DATA_OID = 7;
    var BSON_DATA_BOOLEAN = 8;
    var BSON_DATA_DATE = 9;
    var BSON_DATA_NULL = 10;
    var BSON_DATA_REGEXP = 11;
    var BSON_DATA_DBPOINTER = 12;
    var BSON_DATA_CODE = 13;
    var BSON_DATA_SYMBOL = 14;
    var BSON_DATA_CODE_W_SCOPE = 15;
    var BSON_DATA_INT = 16;
    var BSON_DATA_TIMESTAMP = 17;
    var BSON_DATA_LONG = 18;
    var BSON_DATA_DECIMAL128 = 19;
    var BSON_DATA_MIN_KEY = 255;
    var BSON_DATA_MAX_KEY = 127;
    var BSON_BINARY_SUBTYPE_DEFAULT = 0;
    var BSON_BINARY_SUBTYPE_UUID_NEW = 4;
    var BSONType = Object.freeze({
      double: 1,
      string: 2,
      object: 3,
      array: 4,
      binData: 5,
      undefined: 6,
      objectId: 7,
      bool: 8,
      date: 9,
      null: 10,
      regex: 11,
      dbPointer: 12,
      javascript: 13,
      symbol: 14,
      javascriptWithScope: 15,
      int: 16,
      timestamp: 17,
      long: 18,
      decimal: 19,
      minKey: -1,
      maxKey: 127
    });
    var BSONError = class extends Error {
      get bsonError() {
        return true;
      }
      get name() {
        return "BSONError";
      }
      constructor(message, options) {
        super(message, options);
      }
      static isBSONError(value) {
        return value != null && typeof value === "object" && "bsonError" in value && value.bsonError === true && "name" in value && "message" in value && "stack" in value;
      }
    };
    var BSONVersionError = class extends BSONError {
      get name() {
        return "BSONVersionError";
      }
      constructor() {
        super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`);
      }
    };
    var BSONRuntimeError = class extends BSONError {
      get name() {
        return "BSONRuntimeError";
      }
      constructor(message) {
        super(message);
      }
    };
    var BSONOffsetError = class extends BSONError {
      get name() {
        return "BSONOffsetError";
      }
      offset;
      constructor(message, offset, options) {
        super(`${message}. offset: ${offset}`, options);
        this.offset = offset;
      }
    };
    var TextDecoderFatal;
    var TextDecoderNonFatal;
    function parseUtf8(buffer2, start, end, fatal) {
      if (fatal) {
        TextDecoderFatal ??= new TextDecoder("utf8", { fatal: true });
        try {
          return TextDecoderFatal.decode(buffer2.subarray(start, end));
        } catch (cause) {
          throw new BSONError("Invalid UTF-8 string in BSON document", { cause });
        }
      }
      TextDecoderNonFatal ??= new TextDecoder("utf8", { fatal: false });
      return TextDecoderNonFatal.decode(buffer2.subarray(start, end));
    }
    function tryReadBasicLatin(uint8array, start, end) {
      if (uint8array.length === 0) {
        return "";
      }
      const stringByteLength = end - start;
      if (stringByteLength === 0) {
        return "";
      }
      if (stringByteLength > 20) {
        return null;
      }
      if (stringByteLength === 1 && uint8array[start] < 128) {
        return String.fromCharCode(uint8array[start]);
      }
      if (stringByteLength === 2 && uint8array[start] < 128 && uint8array[start + 1] < 128) {
        return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]);
      }
      if (stringByteLength === 3 && uint8array[start] < 128 && uint8array[start + 1] < 128 && uint8array[start + 2] < 128) {
        return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]) + String.fromCharCode(uint8array[start + 2]);
      }
      const latinBytes = [];
      for (let i2 = start; i2 < end; i2++) {
        const byte = uint8array[i2];
        if (byte > 127) {
          return null;
        }
        latinBytes.push(byte);
      }
      return String.fromCharCode(...latinBytes);
    }
    function tryWriteBasicLatin(destination, source, offset) {
      if (source.length === 0)
        return 0;
      if (source.length > 25)
        return null;
      if (destination.length - offset < source.length)
        return null;
      for (let charOffset = 0, destinationOffset = offset; charOffset < source.length; charOffset++, destinationOffset++) {
        const char = source.charCodeAt(charOffset);
        if (char > 127)
          return null;
        destination[destinationOffset] = char;
      }
      return source.length;
    }
    function nodejsMathRandomBytes(byteLength) {
      return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
    }
    function nodejsSecureRandomBytes(byteLength) {
      return crypto.getRandomValues(nodeJsByteUtils.allocate(byteLength));
    }
    var nodejsRandomBytes = (() => {
      const { crypto: crypto2 } = globalThis;
      if (crypto2 != null && typeof crypto2.getRandomValues === "function") {
        return nodejsSecureRandomBytes;
      } else {
        return nodejsMathRandomBytes;
      }
    })();
    var nodeJsByteUtils = {
      isUint8Array,
      toLocalBufferType(potentialBuffer) {
        if (Buffer.isBuffer(potentialBuffer)) {
          return potentialBuffer;
        }
        if (ArrayBuffer.isView(potentialBuffer)) {
          return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength);
        }
        const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer);
        if (stringTag === "ArrayBuffer" || stringTag === "SharedArrayBuffer" || stringTag === "[object ArrayBuffer]" || stringTag === "[object SharedArrayBuffer]") {
          return Buffer.from(potentialBuffer);
        }
        throw new BSONError(`Cannot create Buffer from the passed potentialBuffer.`);
      },
      allocate(size) {
        return Buffer.alloc(size);
      },
      allocateUnsafe(size) {
        return Buffer.allocUnsafe(size);
      },
      compare(a, b) {
        return nodeJsByteUtils.toLocalBufferType(a).compare(b);
      },
      concat(list) {
        return Buffer.concat(list);
      },
      copy(source, target, targetStart, sourceStart, sourceEnd) {
        return nodeJsByteUtils.toLocalBufferType(source).copy(target, targetStart ?? 0, sourceStart ?? 0, sourceEnd ?? source.length);
      },
      equals(a, b) {
        return nodeJsByteUtils.toLocalBufferType(a).equals(b);
      },
      fromNumberArray(array2) {
        return Buffer.from(array2);
      },
      fromBase64(base643) {
        return Buffer.from(base643, "base64");
      },
      fromUTF8(utf8) {
        return Buffer.from(utf8, "utf8");
      },
      toBase64(buffer2) {
        return nodeJsByteUtils.toLocalBufferType(buffer2).toString("base64");
      },
      fromISO88591(codePoints) {
        return Buffer.from(codePoints, "binary");
      },
      toISO88591(buffer2) {
        return nodeJsByteUtils.toLocalBufferType(buffer2).toString("binary");
      },
      fromHex(hex3) {
        return Buffer.from(hex3, "hex");
      },
      toHex(buffer2) {
        return nodeJsByteUtils.toLocalBufferType(buffer2).toString("hex");
      },
      toUTF8(buffer2, start, end, fatal) {
        const basicLatin = end - start <= 20 ? tryReadBasicLatin(buffer2, start, end) : null;
        if (basicLatin != null) {
          return basicLatin;
        }
        const string4 = nodeJsByteUtils.toLocalBufferType(buffer2).toString("utf8", start, end);
        if (fatal) {
          for (let i2 = 0; i2 < string4.length; i2++) {
            if (string4.charCodeAt(i2) === 65533) {
              parseUtf8(buffer2, start, end, true);
              break;
            }
          }
        }
        return string4;
      },
      utf8ByteLength(input) {
        return Buffer.byteLength(input, "utf8");
      },
      encodeUTF8Into(buffer2, source, byteOffset) {
        const latinBytesWritten = tryWriteBasicLatin(buffer2, source, byteOffset);
        if (latinBytesWritten != null) {
          return latinBytesWritten;
        }
        return nodeJsByteUtils.toLocalBufferType(buffer2).write(source, byteOffset, void 0, "utf8");
      },
      randomBytes: nodejsRandomBytes,
      swap32(buffer2) {
        return nodeJsByteUtils.toLocalBufferType(buffer2).swap32();
      }
    };
    function isReactNative() {
      const { navigator: navigator2 } = globalThis;
      return typeof navigator2 === "object" && navigator2.product === "ReactNative";
    }
    function webMathRandomBytes(byteLength) {
      if (byteLength < 0) {
        throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`);
      }
      return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
    }
    var webRandomBytes = (() => {
      const { crypto: crypto2 } = globalThis;
      if (crypto2 != null && typeof crypto2.getRandomValues === "function") {
        return (byteLength) => {
          return crypto2.getRandomValues(webByteUtils.allocate(byteLength));
        };
      } else {
        if (isReactNative()) {
          const { console: console2 } = globalThis;
          console2?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.");
        }
        return webMathRandomBytes;
      }
    })();
    var HEX_DIGIT = /(\d|[a-f])/i;
    var webByteUtils = {
      isUint8Array,
      toLocalBufferType(potentialUint8array) {
        const stringTag = potentialUint8array?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialUint8array);
        if (stringTag === "Uint8Array") {
          return potentialUint8array;
        }
        if (ArrayBuffer.isView(potentialUint8array)) {
          return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength));
        }
        if (stringTag === "ArrayBuffer" || stringTag === "SharedArrayBuffer" || stringTag === "[object ArrayBuffer]" || stringTag === "[object SharedArrayBuffer]") {
          return new Uint8Array(potentialUint8array);
        }
        throw new BSONError(`Cannot make a Uint8Array from passed potentialBuffer.`);
      },
      allocate(size) {
        if (typeof size !== "number") {
          throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`);
        }
        return new Uint8Array(size);
      },
      allocateUnsafe(size) {
        return webByteUtils.allocate(size);
      },
      compare(uint8Array, otherUint8Array) {
        if (uint8Array === otherUint8Array)
          return 0;
        const len = Math.min(uint8Array.length, otherUint8Array.length);
        for (let i2 = 0; i2 < len; i2++) {
          if (uint8Array[i2] < otherUint8Array[i2])
            return -1;
          if (uint8Array[i2] > otherUint8Array[i2])
            return 1;
        }
        if (uint8Array.length < otherUint8Array.length)
          return -1;
        if (uint8Array.length > otherUint8Array.length)
          return 1;
        return 0;
      },
      concat(uint8Arrays) {
        if (uint8Arrays.length === 0)
          return webByteUtils.allocate(0);
        let totalLength = 0;
        for (const uint8Array of uint8Arrays) {
          totalLength += uint8Array.length;
        }
        const result = webByteUtils.allocate(totalLength);
        let offset = 0;
        for (const uint8Array of uint8Arrays) {
          result.set(uint8Array, offset);
          offset += uint8Array.length;
        }
        return result;
      },
      copy(source, target, targetStart, sourceStart, sourceEnd) {
        if (sourceEnd !== void 0 && sourceEnd < 0) {
          throw new RangeError(`The value of "sourceEnd" is out of range. It must be >= 0. Received ${sourceEnd}`);
        }
        sourceEnd = sourceEnd ?? source.length;
        if (sourceStart !== void 0 && (sourceStart < 0 || sourceStart > sourceEnd)) {
          throw new RangeError(`The value of "sourceStart" is out of range. It must be >= 0 and <= ${sourceEnd}. Received ${sourceStart}`);
        }
        sourceStart = sourceStart ?? 0;
        if (targetStart !== void 0 && targetStart < 0) {
          throw new RangeError(`The value of "targetStart" is out of range. It must be >= 0. Received ${targetStart}`);
        }
        targetStart = targetStart ?? 0;
        const srcSlice = source.subarray(sourceStart, sourceEnd);
        const maxLen = Math.min(srcSlice.length, target.length - targetStart);
        if (maxLen <= 0) {
          return 0;
        }
        target.set(srcSlice.subarray(0, maxLen), targetStart);
        return maxLen;
      },
      equals(uint8Array, otherUint8Array) {
        if (uint8Array.byteLength !== otherUint8Array.byteLength) {
          return false;
        }
        for (let i2 = 0; i2 < uint8Array.byteLength; i2++) {
          if (uint8Array[i2] !== otherUint8Array[i2]) {
            return false;
          }
        }
        return true;
      },
      fromNumberArray(array2) {
        return Uint8Array.from(array2);
      },
      fromBase64(base643) {
        return Uint8Array.from(atob(base643), (c) => c.charCodeAt(0));
      },
      fromUTF8(utf8) {
        return new TextEncoder().encode(utf8);
      },
      toBase64(uint8array) {
        return btoa(webByteUtils.toISO88591(uint8array));
      },
      fromISO88591(codePoints) {
        return Uint8Array.from(codePoints, (c) => c.charCodeAt(0) & 255);
      },
      toISO88591(uint8array) {
        return Array.from(Uint16Array.from(uint8array), (b) => String.fromCharCode(b)).join("");
      },
      fromHex(hex3) {
        const evenLengthHex = hex3.length % 2 === 0 ? hex3 : hex3.slice(0, hex3.length - 1);
        const buffer2 = [];
        for (let i2 = 0; i2 < evenLengthHex.length; i2 += 2) {
          const firstDigit = evenLengthHex[i2];
          const secondDigit = evenLengthHex[i2 + 1];
          if (!HEX_DIGIT.test(firstDigit)) {
            break;
          }
          if (!HEX_DIGIT.test(secondDigit)) {
            break;
          }
          const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16);
          buffer2.push(hexDigit);
        }
        return Uint8Array.from(buffer2);
      },
      toHex(uint8array) {
        return Array.from(uint8array, (byte) => byte.toString(16).padStart(2, "0")).join("");
      },
      toUTF8(uint8array, start, end, fatal) {
        const basicLatin = end - start <= 20 ? tryReadBasicLatin(uint8array, start, end) : null;
        if (basicLatin != null) {
          return basicLatin;
        }
        return parseUtf8(uint8array, start, end, fatal);
      },
      utf8ByteLength(input) {
        return new TextEncoder().encode(input).byteLength;
      },
      encodeUTF8Into(uint8array, source, byteOffset) {
        const bytes = new TextEncoder().encode(source);
        uint8array.set(bytes, byteOffset);
        return bytes.byteLength;
      },
      randomBytes: webRandomBytes,
      swap32(buffer2) {
        if (buffer2.length % 4 !== 0) {
          throw new RangeError("Buffer size must be a multiple of 32-bits");
        }
        for (let i2 = 0; i2 < buffer2.length; i2 += 4) {
          const byte0 = buffer2[i2];
          const byte1 = buffer2[i2 + 1];
          const byte2 = buffer2[i2 + 2];
          const byte3 = buffer2[i2 + 3];
          buffer2[i2] = byte3;
          buffer2[i2 + 1] = byte2;
          buffer2[i2 + 2] = byte1;
          buffer2[i2 + 3] = byte0;
        }
        return buffer2;
      }
    };
    var hasGlobalBuffer = typeof Buffer === "function" && Buffer.prototype?._isBuffer !== true;
    var ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils;
    var bsonType = /* @__PURE__ */ Symbol.for("@@mdb.bson.type");
    var BSONValue = class {
      get [bsonType]() {
        return this._bsontype;
      }
      get [BSON_VERSION_SYMBOL]() {
        return BSON_MAJOR_VERSION;
      }
      [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")](depth, options, inspect) {
        return this.inspect(depth, options, inspect);
      }
    };
    var FLOAT = new Float64Array(1);
    var FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8);
    FLOAT[0] = -1;
    var isBigEndian = FLOAT_BYTES[7] === 0;
    var NumberUtils = {
      isBigEndian,
      getNonnegativeInt32LE(source, offset) {
        if (source[offset + 3] > 127) {
          throw new RangeError(`Size cannot be negative at offset: ${offset}`);
        }
        return source[offset] | source[offset + 1] << 8 | source[offset + 2] << 16 | source[offset + 3] << 24;
      },
      getInt32LE(source, offset) {
        return source[offset] | source[offset + 1] << 8 | source[offset + 2] << 16 | source[offset + 3] << 24;
      },
      getUint32LE(source, offset) {
        return source[offset] + source[offset + 1] * 256 + source[offset + 2] * 65536 + source[offset + 3] * 16777216;
      },
      getUint32BE(source, offset) {
        return source[offset + 3] + source[offset + 2] * 256 + source[offset + 1] * 65536 + source[offset] * 16777216;
      },
      getBigInt64LE(source, offset) {
        const hi = BigInt(source[offset + 4] + source[offset + 5] * 256 + source[offset + 6] * 65536 + (source[offset + 7] << 24));
        const lo = BigInt(source[offset] + source[offset + 1] * 256 + source[offset + 2] * 65536 + source[offset + 3] * 16777216);
        return (hi << 32n) + lo;
      },
      getFloat64LE: isBigEndian ? (source, offset) => {
        FLOAT_BYTES[7] = source[offset];
        FLOAT_BYTES[6] = source[offset + 1];
        FLOAT_BYTES[5] = source[offset + 2];
        FLOAT_BYTES[4] = source[offset + 3];
        FLOAT_BYTES[3] = source[offset + 4];
        FLOAT_BYTES[2] = source[offset + 5];
        FLOAT_BYTES[1] = source[offset + 6];
        FLOAT_BYTES[0] = source[offset + 7];
        return FLOAT[0];
      } : (source, offset) => {
        FLOAT_BYTES[0] = source[offset];
        FLOAT_BYTES[1] = source[offset + 1];
        FLOAT_BYTES[2] = source[offset + 2];
        FLOAT_BYTES[3] = source[offset + 3];
        FLOAT_BYTES[4] = source[offset + 4];
        FLOAT_BYTES[5] = source[offset + 5];
        FLOAT_BYTES[6] = source[offset + 6];
        FLOAT_BYTES[7] = source[offset + 7];
        return FLOAT[0];
      },
      setInt32BE(destination, offset, value) {
        destination[offset + 3] = value;
        value >>>= 8;
        destination[offset + 2] = value;
        value >>>= 8;
        destination[offset + 1] = value;
        value >>>= 8;
        destination[offset] = value;
        return 4;
      },
      setInt32LE(destination, offset, value) {
        destination[offset] = value;
        value >>>= 8;
        destination[offset + 1] = value;
        value >>>= 8;
        destination[offset + 2] = value;
        value >>>= 8;
        destination[offset + 3] = value;
        return 4;
      },
      setBigInt64LE(destination, offset, value) {
        const mask32bits = 0xffffffffn;
        let lo = Number(value & mask32bits);
        destination[offset] = lo;
        lo >>= 8;
        destination[offset + 1] = lo;
        lo >>= 8;
        destination[offset + 2] = lo;
        lo >>= 8;
        destination[offset + 3] = lo;
        let hi = Number(value >> 32n & mask32bits);
        destination[offset + 4] = hi;
        hi >>= 8;
        destination[offset + 5] = hi;
        hi >>= 8;
        destination[offset + 6] = hi;
        hi >>= 8;
        destination[offset + 7] = hi;
        return 8;
      },
      setFloat64LE: isBigEndian ? (destination, offset, value) => {
        FLOAT[0] = value;
        destination[offset] = FLOAT_BYTES[7];
        destination[offset + 1] = FLOAT_BYTES[6];
        destination[offset + 2] = FLOAT_BYTES[5];
        destination[offset + 3] = FLOAT_BYTES[4];
        destination[offset + 4] = FLOAT_BYTES[3];
        destination[offset + 5] = FLOAT_BYTES[2];
        destination[offset + 6] = FLOAT_BYTES[1];
        destination[offset + 7] = FLOAT_BYTES[0];
        return 8;
      } : (destination, offset, value) => {
        FLOAT[0] = value;
        destination[offset] = FLOAT_BYTES[0];
        destination[offset + 1] = FLOAT_BYTES[1];
        destination[offset + 2] = FLOAT_BYTES[2];
        destination[offset + 3] = FLOAT_BYTES[3];
        destination[offset + 4] = FLOAT_BYTES[4];
        destination[offset + 5] = FLOAT_BYTES[5];
        destination[offset + 6] = FLOAT_BYTES[6];
        destination[offset + 7] = FLOAT_BYTES[7];
        return 8;
      }
    };
    var Binary = class _Binary extends BSONValue {
      get _bsontype() {
        return "Binary";
      }
      static BSON_BINARY_SUBTYPE_DEFAULT = 0;
      static BUFFER_SIZE = 256;
      static SUBTYPE_DEFAULT = 0;
      static SUBTYPE_FUNCTION = 1;
      static SUBTYPE_BYTE_ARRAY = 2;
      static SUBTYPE_UUID_OLD = 3;
      static SUBTYPE_UUID = 4;
      static SUBTYPE_MD5 = 5;
      static SUBTYPE_ENCRYPTED = 6;
      static SUBTYPE_COLUMN = 7;
      static SUBTYPE_SENSITIVE = 8;
      static SUBTYPE_VECTOR = 9;
      static SUBTYPE_USER_DEFINED = 128;
      static VECTOR_TYPE = Object.freeze({
        Int8: 3,
        Float32: 39,
        PackedBit: 16
      });
      buffer;
      sub_type;
      position;
      constructor(buffer2, subType) {
        super();
        if (!(buffer2 == null) && typeof buffer2 === "string" && !ArrayBuffer.isView(buffer2) && !isAnyArrayBuffer(buffer2) && !Array.isArray(buffer2)) {
          throw new BSONError("Binary can only be constructed from Uint8Array or number[]");
        }
        this.sub_type = (subType ?? _Binary.BSON_BINARY_SUBTYPE_DEFAULT) & 255;
        if (buffer2 == null) {
          this.buffer = ByteUtils.allocate(_Binary.BUFFER_SIZE);
          this.position = 0;
        } else {
          this.buffer = Array.isArray(buffer2) ? ByteUtils.fromNumberArray(buffer2) : ByteUtils.toLocalBufferType(buffer2);
          this.position = this.buffer.byteLength;
        }
      }
      put(byteValue) {
        if (typeof byteValue === "string" && byteValue.length !== 1) {
          throw new BSONError("only accepts single character String");
        } else if (typeof byteValue !== "number" && byteValue.length !== 1)
          throw new BSONError("only accepts single character Uint8Array or Array");
        let decodedByte;
        if (typeof byteValue === "string") {
          decodedByte = byteValue.charCodeAt(0);
        } else if (typeof byteValue === "number") {
          decodedByte = byteValue;
        } else {
          decodedByte = byteValue[0];
        }
        if (decodedByte < 0 || decodedByte > 255) {
          throw new BSONError("only accepts number in a valid unsigned byte range 0-255");
        }
        if (this.buffer.byteLength > this.position) {
          this.buffer[this.position++] = decodedByte;
        } else {
          const newSpace = ByteUtils.allocate(_Binary.BUFFER_SIZE + this.buffer.length);
          newSpace.set(this.buffer, 0);
          this.buffer = newSpace;
          this.buffer[this.position++] = decodedByte;
        }
      }
      write(sequence, offset) {
        offset = typeof offset === "number" ? offset : this.position;
        if (this.buffer.byteLength < offset + sequence.length) {
          const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length);
          newSpace.set(this.buffer, 0);
          this.buffer = newSpace;
        }
        if (ArrayBuffer.isView(sequence)) {
          this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset);
          this.position = offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
        } else if (typeof sequence === "string") {
          throw new BSONError("input cannot be string");
        }
      }
      read(position, length) {
        length = length && length > 0 ? length : this.position;
        const end = position + length;
        return this.buffer.subarray(position, end > this.position ? this.position : end);
      }
      value() {
        return this.buffer.length === this.position ? this.buffer : this.buffer.subarray(0, this.position);
      }
      length() {
        return this.position;
      }
      toJSON() {
        return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
      }
      toString(encoding) {
        if (encoding === "hex")
          return ByteUtils.toHex(this.buffer.subarray(0, this.position));
        if (encoding === "base64")
          return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
        if (encoding === "utf8" || encoding === "utf-8")
          return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
        return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
      }
      toExtendedJSON(options) {
        options = options || {};
        if (this.sub_type === _Binary.SUBTYPE_VECTOR) {
          validateBinaryVector(this);
        }
        const base64String = ByteUtils.toBase64(this.buffer);
        const subType = Number(this.sub_type).toString(16);
        if (options.legacy) {
          return {
            $binary: base64String,
            $type: subType.length === 1 ? "0" + subType : subType
          };
        }
        return {
          $binary: {
            base64: base64String,
            subType: subType.length === 1 ? "0" + subType : subType
          }
        };
      }
      toUUID() {
        if (this.sub_type === _Binary.SUBTYPE_UUID) {
          return new UUID(this.buffer.subarray(0, this.position));
        }
        throw new BSONError(`Binary sub_type "${this.sub_type}" (${typeof this.sub_type}) is not supported for converting to UUID. Only 0x${_Binary.SUBTYPE_UUID.toString(16).padStart(2, "0")} is currently supported.`);
      }
      static createFromHexString(hex3, subType) {
        return new _Binary(ByteUtils.fromHex(hex3), subType);
      }
      static createFromBase64(base643, subType) {
        return new _Binary(ByteUtils.fromBase64(base643), subType);
      }
      static fromExtendedJSON(doc, options) {
        options = options || {};
        let data;
        let type;
        if ("$binary" in doc) {
          if (options.legacy && typeof doc.$binary === "string" && "$type" in doc) {
            type = doc.$type ? parseInt(doc.$type, 16) : 0;
            data = ByteUtils.fromBase64(doc.$binary);
          } else {
            if (typeof doc.$binary !== "string") {
              type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
              data = ByteUtils.fromBase64(doc.$binary.base64);
            }
          }
        } else if ("$uuid" in doc) {
          type = 4;
          data = UUID.bytesFromString(doc.$uuid);
        }
        if (!data) {
          throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`);
        }
        return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new _Binary(data, type);
      }
      inspect(depth, options, inspect) {
        inspect ??= defaultInspect;
        const base643 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));
        const base64Arg = inspect(base643, options);
        const subTypeArg = inspect(this.sub_type, options);
        return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`;
      }
      toInt8Array() {
        if (this.sub_type !== _Binary.SUBTYPE_VECTOR) {
          throw new BSONError("Binary sub_type is not Vector");
        }
        if (this.buffer[0] !== _Binary.VECTOR_TYPE.Int8) {
          throw new BSONError("Binary datatype field is not Int8");
        }
        validateBinaryVector(this);
        return new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
      }
      toFloat32Array() {
        if (this.sub_type !== _Binary.SUBTYPE_VECTOR) {
          throw new BSONError("Binary sub_type is not Vector");
        }
        if (this.buffer[0] !== _Binary.VECTOR_TYPE.Float32) {
          throw new BSONError("Binary datatype field is not Float32");
        }
        validateBinaryVector(this);
        const floatBytes = new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
        if (NumberUtils.isBigEndian)
          ByteUtils.swap32(floatBytes);
        return new Float32Array(floatBytes.buffer);
      }
      toPackedBits() {
        if (this.sub_type !== _Binary.SUBTYPE_VECTOR) {
          throw new BSONError("Binary sub_type is not Vector");
        }
        if (this.buffer[0] !== _Binary.VECTOR_TYPE.PackedBit) {
          throw new BSONError("Binary datatype field is not packed bit");
        }
        validateBinaryVector(this);
        return new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
      }
      toBits() {
        if (this.sub_type !== _Binary.SUBTYPE_VECTOR) {
          throw new BSONError("Binary sub_type is not Vector");
        }
        if (this.buffer[0] !== _Binary.VECTOR_TYPE.PackedBit) {
          throw new BSONError("Binary datatype field is not packed bit");
        }
        validateBinaryVector(this);
        const byteCount = this.length() - 2;
        const bitCount = byteCount * 8 - this.buffer[1];
        const bits = new Int8Array(bitCount);
        for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
          const byteOffset = bitOffset / 8 | 0;
          const byte = this.buffer[byteOffset + 2];
          const shift = 7 - bitOffset % 8;
          const bit = byte >> shift & 1;
          bits[bitOffset] = bit;
        }
        return bits;
      }
      static fromInt8Array(array2) {
        const buffer2 = ByteUtils.allocate(array2.byteLength + 2);
        buffer2[0] = _Binary.VECTOR_TYPE.Int8;
        buffer2[1] = 0;
        const intBytes = new Uint8Array(array2.buffer, array2.byteOffset, array2.byteLength);
        buffer2.set(intBytes, 2);
        const bin = new this(buffer2, this.SUBTYPE_VECTOR);
        validateBinaryVector(bin);
        return bin;
      }
      static fromFloat32Array(array2) {
        const binaryBytes = ByteUtils.allocate(array2.byteLength + 2);
        binaryBytes[0] = _Binary.VECTOR_TYPE.Float32;
        binaryBytes[1] = 0;
        const floatBytes = new Uint8Array(array2.buffer, array2.byteOffset, array2.byteLength);
        binaryBytes.set(floatBytes, 2);
        if (NumberUtils.isBigEndian)
          ByteUtils.swap32(new Uint8Array(binaryBytes.buffer, 2));
        const bin = new this(binaryBytes, this.SUBTYPE_VECTOR);
        validateBinaryVector(bin);
        return bin;
      }
      static fromPackedBits(array2, padding = 0) {
        const buffer2 = ByteUtils.allocate(array2.byteLength + 2);
        buffer2[0] = _Binary.VECTOR_TYPE.PackedBit;
        buffer2[1] = padding;
        buffer2.set(array2, 2);
        const bin = new this(buffer2, this.SUBTYPE_VECTOR);
        validateBinaryVector(bin);
        return bin;
      }
      static fromBits(bits) {
        const byteLength = bits.length + 7 >>> 3;
        const bytes = new Uint8Array(byteLength + 2);
        bytes[0] = _Binary.VECTOR_TYPE.PackedBit;
        const remainder = bits.length % 8;
        bytes[1] = remainder === 0 ? 0 : 8 - remainder;
        for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
          const byteOffset = bitOffset >>> 3;
          const bit = bits[bitOffset];
          if (bit !== 0 && bit !== 1) {
            throw new BSONError(`Invalid bit value at ${bitOffset}: must be 0 or 1, found ${bits[bitOffset]}`);
          }
          if (bit === 0)
            continue;
          const shift = 7 - bitOffset % 8;
          bytes[byteOffset + 2] |= bit << shift;
        }
        return new this(bytes, _Binary.SUBTYPE_VECTOR);
      }
    };
    function validateBinaryVector(vector) {
      if (vector.sub_type !== Binary.SUBTYPE_VECTOR)
        return;
      const size = vector.position;
      const datatype = vector.buffer[0];
      const padding = vector.buffer[1];
      if ((datatype === Binary.VECTOR_TYPE.Float32 || datatype === Binary.VECTOR_TYPE.Int8) && padding !== 0) {
        throw new BSONError("Invalid Vector: padding must be zero for int8 and float32 vectors");
      }
      if (datatype === Binary.VECTOR_TYPE.Float32) {
        if (size !== 0 && size - 2 !== 0 && (size - 2) % 4 !== 0) {
          throw new BSONError("Invalid Vector: Float32 vector must contain a multiple of 4 bytes");
        }
      }
      if (datatype === Binary.VECTOR_TYPE.PackedBit && padding !== 0 && size === 2) {
        throw new BSONError("Invalid Vector: padding must be zero for packed bit vectors that are empty");
      }
      if (datatype === Binary.VECTOR_TYPE.PackedBit && padding > 7) {
        throw new BSONError(`Invalid Vector: padding must be a value between 0 and 7. found: ${padding}`);
      }
    }
    var UUID_BYTE_LENGTH = 16;
    var UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i;
    var UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;
    var UUID = class _UUID extends Binary {
      constructor(input) {
        let bytes;
        if (input == null) {
          bytes = _UUID.generate();
        } else if (input instanceof _UUID) {
          bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));
        } else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) {
          bytes = ByteUtils.toLocalBufferType(input);
        } else if (typeof input === "string") {
          bytes = _UUID.bytesFromString(input);
        } else {
          throw new BSONError("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).");
        }
        super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW);
      }
      get id() {
        return this.buffer;
      }
      set id(value) {
        this.buffer = value;
      }
      toHexString(includeDashes = true) {
        if (includeDashes) {
          return [
            ByteUtils.toHex(this.buffer.subarray(0, 4)),
            ByteUtils.toHex(this.buffer.subarray(4, 6)),
            ByteUtils.toHex(this.buffer.subarray(6, 8)),
            ByteUtils.toHex(this.buffer.subarray(8, 10)),
            ByteUtils.toHex(this.buffer.subarray(10, 16))
          ].join("-");
        }
        return ByteUtils.toHex(this.buffer);
      }
      toString(encoding) {
        if (encoding === "hex")
          return ByteUtils.toHex(this.id);
        if (encoding === "base64")
          return ByteUtils.toBase64(this.id);
        return this.toHexString();
      }
      toJSON() {
        return this.toHexString();
      }
      equals(otherId) {
        if (!otherId) {
          return false;
        }
        if (otherId instanceof _UUID) {
          return ByteUtils.equals(otherId.id, this.id);
        }
        try {
          return ByteUtils.equals(new _UUID(otherId).id, this.id);
        } catch {
          return false;
        }
      }
      toBinary() {
        return new Binary(this.id, Binary.SUBTYPE_UUID);
      }
      static generate() {
        const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH);
        bytes[6] = bytes[6] & 15 | 64;
        bytes[8] = bytes[8] & 63 | 128;
        return bytes;
      }
      static isValid(input) {
        if (!input) {
          return false;
        }
        if (typeof input === "string") {
          return _UUID.isValidUUIDString(input);
        }
        if (isUint8Array(input)) {
          return input.byteLength === UUID_BYTE_LENGTH;
        }
        return input._bsontype === "Binary" && input.sub_type === this.SUBTYPE_UUID && input.buffer.byteLength === 16;
      }
      static createFromHexString(hexString) {
        const buffer2 = _UUID.bytesFromString(hexString);
        return new _UUID(buffer2);
      }
      static createFromBase64(base643) {
        return new _UUID(ByteUtils.fromBase64(base643));
      }
      static bytesFromString(representation) {
        if (!_UUID.isValidUUIDString(representation)) {
          throw new BSONError("UUID string representation must be 32 hex digits or canonical hyphenated representation");
        }
        return ByteUtils.fromHex(representation.replace(/-/g, ""));
      }
      static isValidUUIDString(representation) {
        return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation);
      }
      inspect(depth, options, inspect) {
        inspect ??= defaultInspect;
        return `new UUID(${inspect(this.toHexString(), options)})`;
      }
    };
    var Code = class _Code extends BSONValue {
      get _bsontype() {
        return "Code";
      }
      code;
      scope;
      constructor(code, scope) {
        super();
        this.code = code.toString();
        this.scope = scope ?? null;
      }
      toJSON() {
        if (this.scope != null) {
          return { code: this.code, scope: this.scope };
        }
        return { code: this.code };
      }
      toExtendedJSON() {
        if (this.scope) {
          return { $code: this.code, $scope: this.scope };
        }
        return { $code: this.code };
      }
      static fromExtendedJSON(doc) {
        return new _Code(doc.$code, doc.$scope);
      }
      inspect(depth, options, inspect) {
        inspect ??= defaultInspect;
        let parametersString = inspect(this.code, options);
        const multiLineFn = parametersString.includes("\n");
        if (this.scope != null) {
          parametersString += `,${multiLineFn ? "\n" : " "}${inspect(this.scope, options)}`;
        }
        const endingNewline = multiLineFn && this.scope === null;
        return `new Code(${multiLineFn ? "\n" : ""}${parametersString}${endingNewline ? "\n" : ""})`;
      }
    };
    function isDBRefLike(value) {
      return value != null && typeof value === "object" && "$id" in value && value.$id != null && "$ref" in value && typeof value.$ref === "string" && (!("$db" in value) || "$db" in value && typeof value.$db === "string");
    }
    var DBRef = class _DBRef extends BSONValue {
      get _bsontype() {
        return "DBRef";
      }
      collection;
      oid;
      db;
      fields;
      constructor(collection, oid, db, fields) {
        super();
        const parts = collection.split(".");
        if (parts.length === 2) {
          db = parts.shift();
          collection = parts.shift();
        }
        this.collection = collection;
        this.oid = oid;
        this.db = db;
        this.fields = fields || {};
      }
      get namespace() {
        return this.collection;
      }
      set namespace(value) {
        this.collection = value;
      }
      toJSON() {
        const o = Object.assign({
          $ref: this.collection,
          $id: this.oid
        }, this.fields);
        if (this.db != null)
          o.$db = this.db;
        return o;
      }
      toExtendedJSON(options) {
        options = options || {};
        let o = {
          $ref: this.collection,
          $id: this.oid
        };
        if (options.legacy) {
          return o;
        }
        if (this.db)
          o.$db = this.db;
        o = Object.assign(o, this.fields);
        return o;
      }
      static fromExtendedJSON(doc) {
        const copy = Object.assign({}, doc);
        delete copy.$ref;
        delete copy.$id;
        delete copy.$db;
        return new _DBRef(doc.$ref, doc.$id, doc.$db, copy);
      }
      inspect(depth, options, inspect) {
        inspect ??= defaultInspect;
        const args = [
          inspect(this.namespace, options),
          inspect(this.oid, options),
          ...this.db ? [inspect(this.db, options)] : [],
          ...Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : []
        ];
        args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1];
        return `new DBRef(${args.join(", ")})`;
      }
    };
    function removeLeadingZerosAndExplicitPlus(str) {
      if (str === "") {
        return str;
      }
      let startIndex = 0;
      const isNegative = str[startIndex] === "-";
      const isExplicitlyPositive = str[startIndex] === "+";
      if (isExplicitlyPositive || isNegative) {
        startIndex += 1;
      }
      let foundInsignificantZero = false;
      for (; startIndex < str.length && str[startIndex] === "0"; ++startIndex) {
        foundInsignificantZero = true;
      }
      if (!foundInsignificantZero) {
        return isExplicitlyPositive ? str.slice(1) : str;
      }
      return `${isNegative ? "-" : ""}${str.length === startIndex ? "0" : str.slice(startIndex)}`;
    }
    function validateStringCharacters(str, radix) {
      radix = radix ?? 10;
      const validCharacters = "0123456789abcdefghijklmnopqrstuvwxyz".slice(0, radix);
      const regex = new RegExp(`[^-+${validCharacters}]`, "i");
      return regex.test(str) ? false : str;
    }
    var wasm = void 0;
    try {
      wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports;
    } catch {
    }
    var TWO_PWR_16_DBL = 1 << 16;
    var TWO_PWR_24_DBL = 1 << 24;
    var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
    var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
    var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
    var INT_CACHE = {};
    var UINT_CACHE = {};
    var MAX_INT64_STRING_LENGTH = 20;
    var DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/;
    var Long = class _Long extends BSONValue {
      get _bsontype() {
        return "Long";
      }
      get __isLong__() {
        return true;
      }
      high;
      low;
      unsigned;
      constructor(lowOrValue = 0, highOrUnsigned, unsigned) {
        super();
        const unsignedBool = typeof highOrUnsigned === "boolean" ? highOrUnsigned : Boolean(unsigned);
        const high = typeof highOrUnsigned === "number" ? highOrUnsigned : 0;
        const res = typeof lowOrValue === "string" ? _Long.fromString(lowOrValue, unsignedBool) : typeof lowOrValue === "bigint" ? _Long.fromBigInt(lowOrValue, unsignedBool) : { low: lowOrValue | 0, high: high | 0, unsigned: unsignedBool };
        this.low = res.low;
        this.high = res.high;
        this.unsigned = res.unsigned;
      }
      static TWO_PWR_24 = _Long.fromInt(TWO_PWR_24_DBL);
      static MAX_UNSIGNED_VALUE = _Long.fromBits(4294967295 | 0, 4294967295 | 0, true);
      static ZERO = _Long.fromInt(0);
      static UZERO = _Long.fromInt(0, true);
      static ONE = _Long.fromInt(1);
      static UONE = _Long.fromInt(1, true);
      static NEG_ONE = _Long.fromInt(-1);
      static MAX_VALUE = _Long.fromBits(4294967295 | 0, 2147483647 | 0, false);
      static MIN_VALUE = _Long.fromBits(0, 2147483648 | 0, false);
      static fromBits(lowBits, highBits, unsigned) {
        return new _Long(lowBits, highBits, unsigned);
      }
      static fromInt(value, unsigned) {
        let obj, cachedObj, cache;
        if (unsigned) {
          value >>>= 0;
          if (cache = 0 <= value && value < 256) {
            cachedObj = UINT_CACHE[value];
            if (cachedObj)
              return cachedObj;
          }
          obj = _Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);
          if (cache)
            UINT_CACHE[value] = obj;
          return obj;
        } else {
          value |= 0;
          if (cache = -128 <= value && value < 128) {
            cachedObj = INT_CACHE[value];
            if (cachedObj)
              return cachedObj;
          }
          obj = _Long.fromBits(value, value < 0 ? -1 : 0, false);
          if (cache)
            INT_CACHE[value] = obj;
          return obj;
        }
      }
      static fromNumber(value, unsigned) {
        if (isNaN(value))
          return unsigned ? _Long.UZERO : _Long.ZERO;
        if (unsigned) {
          if (value < 0)
            return _Long.UZERO;
          if (value >= TWO_PWR_64_DBL)
            return _Long.MAX_UNSIGNED_VALUE;
        } else {
          if (value <= -TWO_PWR_63_DBL)
            return _Long.MIN_VALUE;
          if (value + 1 >= TWO_PWR_63_DBL)
            return _Long.MAX_VALUE;
        }
        if (value < 0)
          return _Long.fromNumber(-value, unsigned).neg();
        return _Long.fromBits(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0, unsigned);
      }
      static fromBigInt(value, unsigned) {
        const FROM_BIGINT_BIT_MASK = 0xffffffffn;
        const FROM_BIGINT_BIT_SHIFT = 32n;
        return new _Long(Number(value & FROM_BIGINT_BIT_MASK), Number(value >> FROM_BIGINT_BIT_SHIFT & FROM_BIGINT_BIT_MASK), unsigned);
      }
      static _fromString(str, unsigned, radix) {
        if (str.length === 0)
          throw new BSONError("empty string");
        if (radix < 2 || 36 < radix)
          throw new BSONError("radix");
        let p;
        if ((p = str.indexOf("-")) > 0)
          throw new BSONError("interior hyphen");
        else if (p === 0) {
          return _Long._fromString(str.substring(1), unsigned, radix).neg();
        }
        const radixToPower = _Long.fromNumber(Math.pow(radix, 8));
        let result = _Long.ZERO;
        for (let i2 = 0; i2 < str.length; i2 += 8) {
          const size = Math.min(8, str.length - i2), value = parseInt(str.substring(i2, i2 + size), radix);
          if (size < 8) {
            const power = _Long.fromNumber(Math.pow(radix, size));
            result = result.mul(power).add(_Long.fromNumber(value));
          } else {
            result = result.mul(radixToPower);
            result = result.add(_Long.fromNumber(value));
          }
        }
        result.unsigned = unsigned;
        return result;
      }
      static fromStringStrict(str, unsignedOrRadix, radix) {
        let unsigned = false;
        if (typeof unsignedOrRadix === "number") {
          radix = unsignedOrRadix, unsignedOrRadix = false;
        } else {
          unsigned = !!unsignedOrRadix;
        }
        radix ??= 10;
        if (str.trim() !== str) {
          throw new BSONError(`Input: '${str}' contains leading and/or trailing whitespace`);
        }
        if (!validateStringCharacters(str, radix)) {
          throw new BSONError(`Input: '${str}' contains invalid characters for radix: ${radix}`);
        }
        const cleanedStr = removeLeadingZerosAndExplicitPlus(str);
        const result = _Long._fromString(cleanedStr, unsigned, radix);
        if (result.toString(radix).toLowerCase() !== cleanedStr.toLowerCase()) {
          throw new BSONError(`Input: ${str} is not representable as ${result.unsigned ? "an unsigned" : "a signed"} 64-bit Long ${radix != null ? `with radix: ${radix}` : ""}`);
        }
        return result;
      }
      static fromString(str, unsignedOrRadix, radix) {
        let unsigned = false;
        if (typeof unsignedOrRadix === "number") {
          radix = unsignedOrRadix, unsignedOrRadix = false;
        } else {
          unsigned = !!unsignedOrRadix;
        }
        radix ??= 10;
        if (str === "NaN" && radix < 24) {
          return _Long.ZERO;
        } else if ((str === "Infinity" || str === "+Infinity" || str === "-Infinity") && radix < 35) {
          return _Long.ZERO;
        }
        return _Long._fromString(str, unsigned, radix);
      }
      static fromBytes(bytes, unsigned, le) {
        return le ? _Long.fromBytesLE(bytes, unsigned) : _Long.fromBytesBE(bytes, unsigned);
      }
      static fromBytesLE(bytes, unsigned) {
        return new _Long(bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24, bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24, unsigned);
      }
      static fromBytesBE(bytes, unsigned) {
        return new _Long(bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7], bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], unsigned);
      }
      static isLong(value) {
        return value != null && typeof value === "object" && "__isLong__" in value && value.__isLong__ === true;
      }
      static fromValue(val, unsigned) {
        if (typeof val === "number")
          return _Long.fromNumber(val, unsigned);
        if (typeof val === "string")
          return _Long.fromString(val, unsigned);
        return _Long.fromBits(val.low, val.high, typeof unsigned === "boolean" ? unsigned : val.unsigned);
      }
      add(addend) {
        if (!_Long.isLong(addend))
          addend = _Long.fromValue(addend);
        const a48 = this.high >>> 16;
        const a32 = this.high & 65535;
        const a16 = this.low >>> 16;
        const a00 = this.low & 65535;
        const b48 = addend.high >>> 16;
        const b32 = addend.high & 65535;
        const b16 = addend.low >>> 16;
        const b00 = addend.low & 65535;
        let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
        c00 += a00 + b00;
        c16 += c00 >>> 16;
        c00 &= 65535;
        c16 += a16 + b16;
        c32 += c16 >>> 16;
        c16 &= 65535;
        c32 += a32 + b32;
        c48 += c32 >>> 16;
        c32 &= 65535;
        c48 += a48 + b48;
        c48 &= 65535;
        return _Long.fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
      }
      and(other) {
        if (!_Long.isLong(other))
          other = _Long.fromValue(other);
        return _Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
      }
      compare(other) {
        if (!_Long.isLong(other))
          other = _Long.fromValue(other);
        if (this.eq(other))
          return 0;
        const thisNeg = this.isNegative(), otherNeg = other.isNegative();
        if (thisNeg && !otherNeg)
          return -1;
        if (!thisNeg && otherNeg)
          return 1;
        if (!this.unsigned)
          return this.sub(other).isNegative() ? -1 : 1;
        return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1;
      }
      comp(other) {
        return this.compare(other);
      }
      divide(divisor) {
        if (!_Long.isLong(divisor))
          divisor = _Long.fromValue(divisor);
        if (divisor.isZero())
          throw new BSONError("division by zero");
        if (wasm) {
          if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) {
            return this;
          }
          const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
          return _Long.fromBits(low, wasm.get_high(), this.unsigned);
        }
        if (this.isZero())
          return this.unsigned ? _Long.UZERO : _Long.ZERO;
        let approx, rem, res;
        if (!this.unsigned) {
          if (this.eq(_Long.MIN_VALUE)) {
            if (divisor.eq(_Long.ONE) || divisor.eq(_Long.NEG_ONE))
              return _Long.MIN_VALUE;
            else if (divisor.eq(_Long.MIN_VALUE))
              return _Long.ONE;
            else {
              const halfThis = this.shr(1);
              approx = halfThis.div(divisor).shl(1);
              if (approx.eq(_Long.ZERO)) {
                return divisor.isNegative() ? _Long.ONE : _Long.NEG_ONE;
              } else {
                rem = this.sub(divisor.mul(approx));
                res = approx.add(rem.div(divisor));
                return res;
              }
            }
          } else if (divisor.eq(_Long.MIN_VALUE))
            return this.unsigned ? _Long.UZERO : _Long.ZERO;
          if (this.isNegative()) {
            if (divisor.isNegative())
              return this.neg().div(divisor.neg());
            return this.neg().div(divisor).neg();
          } else if (divisor.isNegative())
            return this.div(divisor.neg()).neg();
          res = _Long.ZERO;
        } else {
          if (!divisor.unsigned)
            divisor = divisor.toUnsigned();
          if (divisor.gt(this))
            return _Long.UZERO;
          if (divisor.gt(this.shru(1)))
            return _Long.UONE;
          res = _Long.UZERO;
        }
        rem = this;
        while (rem.gte(divisor)) {
          approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
          const log2 = Math.ceil(Math.log(approx) / Math.LN2);
          const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
          let approxRes = _Long.fromNumber(approx);
          let approxRem = approxRes.mul(divisor);
          while (approxRem.isNegative() || approxRem.gt(rem)) {
            approx -= delta;
            approxRes = _Long.fromNumber(approx, this.unsigned);
            approxRem = approxRes.mul(divisor);
          }
          if (approxRes.isZero())
            approxRes = _Long.ONE;
          res = res.add(approxRes);
          rem = rem.sub(approxRem);
        }
        return res;
      }
      div(divisor) {
        return this.divide(divisor);
      }
      equals(other) {
        if (!_Long.isLong(other))
          other = _Long.fromValue(other);
        if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
          return false;
        return this.high === other.high && this.low === other.low;
      }
      eq(other) {
        return this.equals(other);
      }
      getHighBits() {
        return this.high;
      }
      getHighBitsUnsigned() {
        return this.high >>> 0;
      }
      getLowBits() {
        return this.low;
      }
      getLowBitsUnsigned() {
        return this.low >>> 0;
      }
      getNumBitsAbs() {
        if (this.isNegative()) {
          return this.eq(_Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
        }
        const val = this.high !== 0 ? this.high : this.low;
        let bit;
        for (bit = 31; bit > 0; bit--)
          if ((val & 1 << bit) !== 0)
            break;
        return this.high !== 0 ? bit + 33 : bit + 1;
      }
      greaterThan(other) {
        return this.comp(other) > 0;
      }
      gt(other) {
        return this.greaterThan(other);
      }
      greaterThanOrEqual(other) {
        return this.comp(other) >= 0;
      }
      gte(other) {
        return this.greaterThanOrEqual(other);
      }
      ge(other) {
        return this.greaterThanOrEqual(other);
      }
      isEven() {
        return (this.low & 1) === 0;
      }
      isNegative() {
        return !this.unsigned && this.high < 0;
      }
      isOdd() {
        return (this.low & 1) === 1;
      }
      isPositive() {
        return this.unsigned || this.high >= 0;
      }
      isZero() {
        return this.high === 0 && this.low === 0;
      }
      lessThan(other) {
        return this.comp(other) < 0;
      }
      lt(other) {
        return this.lessThan(other);
      }
      lessThanOrEqual(other) {
        return this.comp(other) <= 0;
      }
      lte(other) {
        return this.lessThanOrEqual(other);
      }
      modulo(divisor) {
        if (!_Long.isLong(divisor))
          divisor = _Long.fromValue(divisor);
        if (wasm) {
          const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
          return _Long.fromBits(low, wasm.get_high(), this.unsigned);
        }
        return this.sub(this.div(divisor).mul(divisor));
      }
      mod(divisor) {
        return this.modulo(divisor);
      }
      rem(divisor) {
        return this.modulo(divisor);
      }
      multiply(multiplier) {
        if (this.isZero())
          return _Long.ZERO;
        if (!_Long.isLong(multiplier))
          multiplier = _Long.fromValue(multiplier);
        if (wasm) {
          const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
          return _Long.fromBits(low, wasm.get_high(), this.unsigned);
        }
        if (multiplier.isZero())
          return _Long.ZERO;
        if (this.eq(_Long.MIN_VALUE))
          return multiplier.isOdd() ? _Long.MIN_VALUE : _Long.ZERO;
        if (multiplier.eq(_Long.MIN_VALUE))
          return this.isOdd() ? _Long.MIN_VALUE : _Long.ZERO;
        if (this.isNegative()) {
          if (multiplier.isNegative())
            return this.neg().mul(multiplier.neg());
          else
            return this.neg().mul(multiplier).neg();
        } else if (multiplier.isNegative())
          return this.mul(multiplier.neg()).neg();
        if (this.lt(_Long.TWO_PWR_24) && multiplier.lt(_Long.TWO_PWR_24))
          return _Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
        const a48 = this.high >>> 16;
        const a32 = this.high & 65535;
        const a16 = this.low >>> 16;
        const a00 = this.low & 65535;
        const b48 = multiplier.high >>> 16;
        const b32 = multiplier.high & 65535;
        const b16 = multiplier.low >>> 16;
        const b00 = multiplier.low & 65535;
        let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
        c00 += a00 * b00;
        c16 += c00 >>> 16;
        c00 &= 65535;
        c16 += a16 * b00;
        c32 += c16 >>> 16;
        c16 &= 65535;
        c16 += a00 * b16;
        c32 += c16 >>> 16;
        c16 &= 65535;
        c32 += a32 * b00;
        c48 += c32 >>> 16;
        c32 &= 65535;
        c32 += a16 * b16;
        c48 += c32 >>> 16;
        c32 &= 65535;
        c32 += a00 * b32;
        c48 += c32 >>> 16;
        c32 &= 65535;
        c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
        c48 &= 65535;
        return _Long.fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
      }
      mul(multiplier) {
        return this.multiply(multiplier);
      }
      negate() {
        if (!this.unsigned && this.eq(_Long.MIN_VALUE))
          return _Long.MIN_VALUE;
        return this.not().add(_Long.ONE);
      }
      neg() {
        return this.negate();
      }
      not() {
        return _Long.fromBits(~this.low, ~this.high, this.unsigned);
      }
      notEquals(other) {
        return !this.equals(other);
      }
      neq(other) {
        return this.notEquals(other);
      }
      ne(other) {
        return this.notEquals(other);
      }
      or(other) {
        if (!_Long.isLong(other))
          other = _Long.fromValue(other);
        return _Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
      }
      shiftLeft(numBits) {
        if (_Long.isLong(numBits))
          numBits = numBits.toInt();
        if ((numBits &= 63) === 0)
          return this;
        else if (numBits < 32)
          return _Long.fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits, this.unsigned);
        else
          return _Long.fromBits(0, this.low << numBits - 32, this.unsigned);
      }
      shl(numBits) {
        return this.shiftLeft(numBits);
      }
      shiftRight(numBits) {
        if (_Long.isLong(numBits))
          numBits = numBits.toInt();
        if ((numBits &= 63) === 0)
          return this;
        else if (numBits < 32)
          return _Long.fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits, this.unsigned);
        else
          return _Long.fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1, this.unsigned);
      }
      shr(numBits) {
        return this.shiftRight(numBits);
      }
      shiftRightUnsigned(numBits) {
        if (_Long.isLong(numBits))
          numBits = numBits.toInt();
        numBits &= 63;
        if (numBits === 0)
          return this;
        else {
          const high = this.high;
          if (numBits < 32) {
            const low = this.low;
            return _Long.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits, this.unsigned);
          } else if (numBits === 32)
            return _Long.fromBits(high, 0, this.unsigned);
          else
            return _Long.fromBits(high >>> numBits - 32, 0, this.unsigned);
        }
      }
      shr_u(numBits) {
        return this.shiftRightUnsigned(numBits);
      }
      shru(numBits) {
        return this.shiftRightUnsigned(numBits);
      }
      subtract(subtrahend) {
        if (!_Long.isLong(subtrahend))
          subtrahend = _Long.fromValue(subtrahend);
        return this.add(subtrahend.neg());
      }
      sub(subtrahend) {
        return this.subtract(subtrahend);
      }
      toInt() {
        return this.unsigned ? this.low >>> 0 : this.low;
      }
      toNumber() {
        if (this.unsigned)
          return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
        return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
      }
      toBigInt() {
        return BigInt(this.toString());
      }
      toBytes(le) {
        return le ? this.toBytesLE() : this.toBytesBE();
      }
      toBytesLE() {
        const hi = this.high, lo = this.low;
        return [
          lo & 255,
          lo >>> 8 & 255,
          lo >>> 16 & 255,
          lo >>> 24,
          hi & 255,
          hi >>> 8 & 255,
          hi >>> 16 & 255,
          hi >>> 24
        ];
      }
      toBytesBE() {
        const hi = this.high, lo = this.low;
        return [
          hi >>> 24,
          hi >>> 16 & 255,
          hi >>> 8 & 255,
          hi & 255,
          lo >>> 24,
          lo >>> 16 & 255,
          lo >>> 8 & 255,
          lo & 255
        ];
      }
      toSigned() {
        if (!this.unsigned)
          return this;
        return _Long.fromBits(this.low, this.high, false);
      }
      toString(radix) {
        radix = radix || 10;
        if (radix < 2 || 36 < radix)
          throw new BSONError("radix");
        if (this.isZero())
          return "0";
        if (this.isNegative()) {
          if (this.eq(_Long.MIN_VALUE)) {
            const radixLong = _Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
            return div.toString(radix) + rem1.toInt().toString(radix);
          } else
            return "-" + this.neg().toString(radix);
        }
        const radixToPower = _Long.fromNumber(Math.pow(radix, 6), this.unsigned);
        let rem = this;
        let result = "";
        while (true) {
          const remDiv = rem.div(radixToPower);
          const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;
          let digits = intval.toString(radix);
          rem = remDiv;
          if (rem.isZero()) {
            return digits + result;
          } else {
            while (digits.length < 6)
              digits = "0" + digits;
            result = "" + digits + result;
          }
        }
      }
      toUnsigned() {
        if (this.unsigned)
          return this;
        return _Long.fromBits(this.low, this.high, true);
      }
      xor(other) {
        if (!_Long.isLong(other))
          other = _Long.fromValue(other);
        return _Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
      }
      eqz() {
        return this.isZero();
      }
      le(other) {
        return this.lessThanOrEqual(other);
      }
      toExtendedJSON(options) {
        if (options && options.relaxed)
          return this.toNumber();
        return { $numberLong: this.toString() };
      }
      static fromExtendedJSON(doc, options) {
        const { useBigInt64 = false, relaxed = true } = { ...options };
        if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) {
          throw new BSONError("$numberLong string is too long");
        }
        if (!DECIMAL_REG_EX.test(doc.$numberLong)) {
          throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`);
        }
        if (useBigInt64) {
          const bigIntResult = BigInt(doc.$numberLong);
          return BigInt.asIntN(64, bigIntResult);
        }
        const longResult = _Long.fromString(doc.$numberLong);
        if (relaxed) {
          return longResult.toNumber();
        }
        return longResult;
      }
      inspect(depth, options, inspect) {
        inspect ??= defaultInspect;
        const longVal = inspect(this.toString(), options);
        const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : "";
        return `new Long(${longVal}${unsignedVal})`;
      }
    };
    var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
    var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
    var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
    var EXPONENT_MAX = 6111;
    var EXPONENT_MIN = -6176;
    var EXPONENT_BIAS = 6176;
    var MAX_DIGITS = 34;
    var NAN_BUFFER = ByteUtils.fromNumberArray([
      124,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0
    ].reverse());
    var INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([
      248,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0
    ].reverse());
    var INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([
      120,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0
    ].reverse());
    var EXPONENT_REGEX = /^([-+])?(\d+)?$/;
    var COMBINATION_MASK = 31;
    var EXPONENT_MASK = 16383;
    var COMBINATION_INFINITY = 30;
    var COMBINATION_NAN = 31;
    function isDigit(value) {
      return !isNaN(parseInt(value, 10));
    }
    function divideu128(value) {
      const DIVISOR = Long.fromNumber(1e3 * 1e3 * 1e3);
      let _rem = Long.fromNumber(0);
      if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
        return { quotient: value, rem: _rem };
      }
      for (let i2 = 0; i2 <= 3; i2++) {
        _rem = _rem.shiftLeft(32);
        _rem = _rem.add(new Long(value.parts[i2], 0));
        value.parts[i2] = _rem.div(DIVISOR).low;
        _rem = _rem.modulo(DIVISOR);
      }
      return { quotient: value, rem: _rem };
    }
    function multiply64x2(left, right) {
      if (!left && !right) {
        return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
      }
      const leftHigh = left.shiftRightUnsigned(32);
      const leftLow = new Long(left.getLowBits(), 0);
      const rightHigh = right.shiftRightUnsigned(32);
      const rightLow = new Long(right.getLowBits(), 0);
      let productHigh = leftHigh.multiply(rightHigh);
      let productMid = leftHigh.multiply(rightLow);
      const productMid2 = leftLow.multiply(rightHigh);
      let productLow = leftLow.multiply(rightLow);
      productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
      productMid = new Long(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32));
      productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
      productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
      return { high: productHigh, low: productLow };
    }
    function lessThan(left, right) {
      const uhleft = left.high >>> 0;
      const uhright = right.high >>> 0;
      if (uhleft < uhright) {
        return true;
      } else if (uhleft === uhright) {
        const ulleft = left.low >>> 0;
        const ulright = right.low >>> 0;
        if (ulleft < ulright)
          return true;
      }
      return false;
    }
    function invalidErr(string4, message) {
      throw new BSONError(`"${string4}" is not a valid Decimal128 string - ${message}`);
    }
    var Decimal128 = class _Decimal128 extends BSONValue {
      get _bsontype() {
        return "Decimal128";
      }
      bytes;
      constructor(bytes) {
        super();
        if (typeof bytes === "string") {
          this.bytes = _Decimal128.fromString(bytes).bytes;
        } else if (bytes instanceof Uint8Array || isUint8Array(bytes)) {
          if (bytes.byteLength !== 16) {
            throw new BSONError("Decimal128 must take a Buffer of 16 bytes");
          }
          this.bytes = bytes;
        } else {
          throw new BSONError("Decimal128 must take a Buffer or string");
        }
      }
      static fromString(representation) {
        return _Decimal128._fromString(representation, { allowRounding: false });
      }
      static fromStringWithRounding(representation) {
        return _Decimal128._fromString(representation, { allowRounding: true });
      }
      static _fromString(representation, options) {
        let isNegative = false;
        let sawSign = false;
        let sawRadix = false;
        let foundNonZero = false;
        let significantDigits = 0;
        let nDigitsRead = 0;
        let nDigits = 0;
        let radixPosition = 0;
        let firstNonZero = 0;
        const digits = [0];
        let nDigitsStored = 0;
        let digitsInsert = 0;
        let lastDigit = 0;
        let exponent = 0;
        let significandHigh = new Long(0, 0);
        let significandLow = new Long(0, 0);
        let biasedExponent = 0;
        let index = 0;
        if (representation.length >= 7e3) {
          throw new BSONError("" + representation + " not a valid Decimal128 string");
        }
        const stringMatch = representation.match(PARSE_STRING_REGEXP);
        const infMatch = representation.match(PARSE_INF_REGEXP);
        const nanMatch = representation.match(PARSE_NAN_REGEXP);
        if (!stringMatch && !infMatch && !nanMatch || representation.length === 0) {
          throw new BSONError("" + representation + " not a valid Decimal128 string");
        }
        if (stringMatch) {
          const unsignedNumber = stringMatch[2];
          const e2 = stringMatch[4];
          const expSign = stringMatch[5];
          const expNumber = stringMatch[6];
          if (e2 && expNumber === void 0)
            invalidErr(representation, "missing exponent power");
          if (e2 && unsignedNumber === void 0)
            invalidErr(representation, "missing exponent base");
          if (e2 === void 0 && (expSign || expNumber)) {
            invalidErr(representation, "missing e before exponent");
          }
        }
        if (representation[index] === "+" || representation[index] === "-") {
          sawSign = true;
          isNegative = representation[index++] === "-";
        }
        if (!isDigit(representation[index]) && representation[index] !== ".") {
          if (representation[index] === "i" || representation[index] === "I") {
            return new _Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
          } else if (representation[index] === "N") {
            return new _Decimal128(NAN_BUFFER);
          }
        }
        while (isDigit(representation[index]) || representation[index] === ".") {
          if (representation[index] === ".") {
            if (sawRadix)
              invalidErr(representation, "contains multiple periods");
            sawRadix = true;
            index = index + 1;
            continue;
          }
          if (nDigitsStored < MAX_DIGITS) {
            if (representation[index] !== "0" || foundNonZero) {
              if (!foundNonZero) {
                firstNonZero = nDigitsRead;
              }
              foundNonZero = true;
              digits[digitsInsert++] = parseInt(representation[index], 10);
              nDigitsStored = nDigitsStored + 1;
            }
          }
          if (foundNonZero)
            nDigits = nDigits + 1;
          if (sawRadix)
            radixPosition = radixPosition + 1;
          nDigitsRead = nDigitsRead + 1;
          index = index + 1;
        }
        if (sawRadix && !nDigitsRead)
          throw new BSONError("" + representation + " not a valid Decimal128 string");
        if (representation[index] === "e" || representation[index] === "E") {
          const match = representation.substr(++index).match(EXPONENT_REGEX);
          if (!match || !match[2])
            return new _Decimal128(NAN_BUFFER);
          exponent = parseInt(match[0], 10);
          index = index + match[0].length;
        }
        if (representation[index])
          return new _Decimal128(NAN_BUFFER);
        if (!nDigitsStored) {
          digits[0] = 0;
          nDigits = 1;
          nDigitsStored = 1;
          significantDigits = 0;
        } else {
          lastDigit = nDigitsStored - 1;
          significantDigits = nDigits;
          if (significantDigits !== 1) {
            while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === "0") {
              significantDigits = significantDigits - 1;
            }
          }
        }
        if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) {
          exponent = EXPONENT_MIN;
        } else {
          exponent = exponent - radixPosition;
        }
        while (exponent > EXPONENT_MAX) {
          lastDigit = lastDigit + 1;
          if (lastDigit >= MAX_DIGITS) {
            if (significantDigits === 0) {
              exponent = EXPONENT_MAX;
              break;
            }
            invalidErr(representation, "overflow");
          }
          exponent = exponent - 1;
        }
        if (options.allowRounding) {
          while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
            if (lastDigit === 0 && significantDigits < nDigitsStored) {
              exponent = EXPONENT_MIN;
              significantDigits = 0;
              break;
            }
            if (nDigitsStored < nDigits) {
              nDigits = nDigits - 1;
            } else {
              lastDigit = lastDigit - 1;
            }
            if (exponent < EXPONENT_MAX) {
              exponent = exponent + 1;
            } else {
              const digitsString = digits.join("");
              if (digitsString.match(/^0+$/)) {
                exponent = EXPONENT_MAX;
                break;
              }
              invalidErr(representation, "overflow");
            }
          }
          if (lastDigit + 1 < significantDigits) {
            let endOfString = nDigitsRead;
            if (sawRadix) {
              firstNonZero = firstNonZero + 1;
              endOfString = endOfString + 1;
            }
            if (sawSign) {
              firstNonZero = firstNonZero + 1;
              endOfString = endOfString + 1;
            }
            const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
            let roundBit = 0;
            if (roundDigit >= 5) {
              roundBit = 1;
              if (roundDigit === 5) {
                roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0;
                for (let i2 = firstNonZero + lastDigit + 2; i2 < endOfString; i2++) {
                  if (parseInt(representation[i2], 10)) {
                    roundBit = 1;
                    break;
                  }
                }
              }
            }
            if (roundBit) {
              let dIdx = lastDigit;
              for (; dIdx >= 0; dIdx--) {
                if (++digits[dIdx] > 9) {
                  digits[dIdx] = 0;
                  if (dIdx === 0) {
                    if (exponent < EXPONENT_MAX) {
                      exponent = exponent + 1;
                      digits[dIdx] = 1;
                    } else {
                      return new _Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
                    }
                  }
                } else {
                  break;
                }
              }
            }
          }
        } else {
          while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
            if (lastDigit === 0) {
              if (significantDigits === 0) {
                exponent = EXPONENT_MIN;
                break;
              }
              invalidErr(representation, "exponent underflow");
            }
            if (nDigitsStored < nDigits) {
              if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== "0" && significantDigits !== 0) {
                invalidErr(representation, "inexact rounding");
              }
              nDigits = nDigits - 1;
            } else {
              if (digits[lastDigit] !== 0) {
                invalidErr(representation, "inexact rounding");
              }
              lastDigit = lastDigit - 1;
            }
            if (exponent < EXPONENT_MAX) {
              exponent = exponent + 1;
            } else {
              invalidErr(representation, "overflow");
            }
          }
          if (lastDigit + 1 < significantDigits) {
            if (sawRadix) {
              firstNonZero = firstNonZero + 1;
            }
            if (sawSign) {
              firstNonZero = firstNonZero + 1;
            }
            const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
            if (roundDigit !== 0) {
              invalidErr(representation, "inexact rounding");
            }
          }
        }
        significandHigh = Long.fromNumber(0);
        significandLow = Long.fromNumber(0);
        if (significantDigits === 0) {
          significandHigh = Long.fromNumber(0);
          significandLow = Long.fromNumber(0);
        } else if (lastDigit < 17) {
          let dIdx = 0;
          significandLow = Long.fromNumber(digits[dIdx++]);
          significandHigh = new Long(0, 0);
          for (; dIdx <= lastDigit; dIdx++) {
            significandLow = significandLow.multiply(Long.fromNumber(10));
            significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
          }
        } else {
          let dIdx = 0;
          significandHigh = Long.fromNumber(digits[dIdx++]);
          for (; dIdx <= lastDigit - 17; dIdx++) {
            significandHigh = significandHigh.multiply(Long.fromNumber(10));
            significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
          }
          significandLow = Long.fromNumber(digits[dIdx++]);
          for (; dIdx <= lastDigit; dIdx++) {
            significandLow = significandLow.multiply(Long.fromNumber(10));
            significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
          }
        }
        const significand = multiply64x2(significandHigh, Long.fromString("100000000000000000"));
        significand.low = significand.low.add(significandLow);
        if (lessThan(significand.low, significandLow)) {
          significand.high = significand.high.add(Long.fromNumber(1));
        }
        biasedExponent = exponent + EXPONENT_BIAS;
        const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
        if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) {
          dec.high = dec.high.or(Long.fromNumber(3).shiftLeft(61));
          dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(16383).shiftLeft(47)));
          dec.high = dec.high.or(significand.high.and(Long.fromNumber(140737488355327)));
        } else {
          dec.high = dec.high.or(Long.fromNumber(biasedExponent & 16383).shiftLeft(49));
          dec.high = dec.high.or(significand.high.and(Long.fromNumber(562949953421311)));
        }
        dec.low = significand.low;
        if (isNegative) {
          dec.high = dec.high.or(Long.fromString("9223372036854775808"));
        }
        const buffer2 = ByteUtils.allocateUnsafe(16);
        index = 0;
        buffer2[index++] = dec.low.low & 255;
        buffer2[index++] = dec.low.low >> 8 & 255;
        buffer2[index++] = dec.low.low >> 16 & 255;
        buffer2[index++] = dec.low.low >> 24 & 255;
        buffer2[index++] = dec.low.high & 255;
        buffer2[index++] = dec.low.high >> 8 & 255;
        buffer2[index++] = dec.low.high >> 16 & 255;
        buffer2[index++] = dec.low.high >> 24 & 255;
        buffer2[index++] = dec.high.low & 255;
        buffer2[index++] = dec.high.low >> 8 & 255;
        buffer2[index++] = dec.high.low >> 16 & 255;
        buffer2[index++] = dec.high.low >> 24 & 255;
        buffer2[index++] = dec.high.high & 255;
        buffer2[index++] = dec.high.high >> 8 & 255;
        buffer2[index++] = dec.high.high >> 16 & 255;
        buffer2[index++] = dec.high.high >> 24 & 255;
        return new _Decimal128(buffer2);
      }
      toString() {
        let biased_exponent;
        let significand_digits = 0;
        const significand = new Array(36);
        for (let i2 = 0; i2 < significand.length; i2++)
          significand[i2] = 0;
        let index = 0;
        let is_zero = false;
        let significand_msb;
        let significand128 = { parts: [0, 0, 0, 0] };
        let j, k;
        const string4 = [];
        index = 0;
        const buffer2 = this.bytes;
        const low = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
        const midl = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
        const midh = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
        const high = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
        index = 0;
        const dec = {
          low: new Long(low, midl),
          high: new Long(midh, high)
        };
        if (dec.high.lessThan(Long.ZERO)) {
          string4.push("-");
        }
        const combination = high >> 26 & COMBINATION_MASK;
        if (combination >> 3 === 3) {
          if (combination === COMBINATION_INFINITY) {
            return string4.join("") + "Infinity";
          } else if (combination === COMBINATION_NAN) {
            return "NaN";
          } else {
            biased_exponent = high >> 15 & EXPONENT_MASK;
            significand_msb = 8 + (high >> 14 & 1);
          }
        } else {
          significand_msb = high >> 14 & 7;
          biased_exponent = high >> 17 & EXPONENT_MASK;
        }
        const exponent = biased_exponent - EXPONENT_BIAS;
        significand128.parts[0] = (high & 16383) + ((significand_msb & 15) << 14);
        significand128.parts[1] = midh;
        significand128.parts[2] = midl;
        significand128.parts[3] = low;
        if (significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0) {
          is_zero = true;
        } else {
          for (k = 3; k >= 0; k--) {
            let least_digits = 0;
            const result = divideu128(significand128);
            significand128 = result.quotient;
            least_digits = result.rem.low;
            if (!least_digits)
              continue;
            for (j = 8; j >= 0; j--) {
              significand[k * 9 + j] = least_digits % 10;
              least_digits = Math.floor(least_digits / 10);
            }
          }
        }
        if (is_zero) {
          significand_digits = 1;
          significand[index] = 0;
        } else {
          significand_digits = 36;
          while (!significand[index]) {
            significand_digits = significand_digits - 1;
            index = index + 1;
          }
        }
        const scientific_exponent = significand_digits - 1 + exponent;
        if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
          if (significand_digits > 34) {
            string4.push(`${0}`);
            if (exponent > 0)
              string4.push(`E+${exponent}`);
            else if (exponent < 0)
              string4.push(`E${exponent}`);
            return string4.join("");
          }
          string4.push(`${significand[index++]}`);
          significand_digits = significand_digits - 1;
          if (significand_digits) {
            string4.push(".");
          }
          for (let i2 = 0; i2 < significand_digits; i2++) {
            string4.push(`${significand[index++]}`);
          }
          string4.push("E");
          if (scientific_exponent > 0) {
            string4.push(`+${scientific_exponent}`);
          } else {
            string4.push(`${scientific_exponent}`);
          }
        } else {
          if (exponent >= 0) {
            for (let i2 = 0; i2 < significand_digits; i2++) {
              string4.push(`${significand[index++]}`);
            }
          } else {
            let radix_position = significand_digits + exponent;
            if (radix_position > 0) {
              for (let i2 = 0; i2 < radix_position; i2++) {
                string4.push(`${significand[index++]}`);
              }
            } else {
              string4.push("0");
            }
            string4.push(".");
            while (radix_position++ < 0) {
              string4.push("0");
            }
            for (let i2 = 0; i2 < significand_digits - Math.max(radix_position - 1, 0); i2++) {
              string4.push(`${significand[index++]}`);
            }
          }
        }
        return string4.join("");
      }
      toJSON() {
        return { $numberDecimal: this.toString() };
      }
      toExtendedJSON() {
        return { $numberDecimal: this.toString() };
      }
      static fromExtendedJSON(doc) {
        return _Decimal128.fromString(doc.$numberDecimal);
      }
      inspect(depth, options, inspect) {
        inspect ??= defaultInspect;
        const d128string = inspect(this.toString(), options);
        return `new Decimal128(${d128string})`;
      }
    };
    var Double = class _Double extends BSONValue {
      get _bsontype() {
        return "Double";
      }
      value;
      constructor(value) {
        super();
        if (value instanceof Number) {
          value = value.valueOf();
        }
        this.value = +value;
      }
      static fromString(value) {
        const coercedValue = Number(value);
        if (value === "NaN")
          return new _Double(NaN);
        if (value === "Infinity")
          return new _Double(Infinity);
        if (value === "-Infinity")
          return new _Double(-Infinity);
        if (!Number.isFinite(coercedValue)) {
          throw new BSONError(`Input: ${value} is not representable as a Double`);
        }
        if (value.trim() !== value) {
          throw new BSONError(`Input: '${value}' contains whitespace`);
        }
        if (value === "") {
          throw new BSONError(`Input is an empty string`);
        }
        if (/[^-0-9.+eE]/.test(value)) {
          throw new BSONError(`Input: '${value}' is not in decimal or exponential notation`);
        }
        return new _Double(coercedValue);
      }
      valueOf() {
        return this.value;
      }
      toJSON() {
        return this.value;
      }
      toString(radix) {
        return this.value.toString(radix);
      }
      toExtendedJSON(options) {
        if (options && (options.legacy || options.relaxed && isFinite(this.value))) {
          return this.value;
        }
        if (Object.is(Math.sign(this.value), -0)) {
          return { $numberDouble: "-0.0" };
        }
        return {
          $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString()
        };
      }
      static fromExtendedJSON(doc, options) {
        const doubleValue = parseFloat(doc.$numberDouble);
        return options && options.relaxed ? doubleValue : new _Double(doubleValue);
      }
      inspect(depth, options, inspect) {
        inspect ??= defaultInspect;
        return `new Double(${inspect(this.value, options)})`;
      }
    };
    var Int32 = class _Int32 extends BSONValue {
      get _bsontype() {
        return "Int32";
      }
      value;
      constructor(value) {
        super();
        if (value instanceof Number) {
          value = value.valueOf();
        }
        this.value = +value | 0;
      }
      static fromString(value) {
        const cleanedValue = removeLeadingZerosAndExplicitPlus(value);
        const coercedValue = Number(value);
        if (BSON_INT32_MAX < coercedValue) {
          throw new BSONError(`Input: '${value}' is larger than the maximum value for Int32`);
        } else if (BSON_INT32_MIN > coercedValue) {
          throw new BSONError(`Input: '${value}' is smaller than the minimum value for Int32`);
        } else if (!Number.isSafeInteger(coercedValue)) {
          throw new BSONError(`Input: '${value}' is not a safe integer`);
        } else if (coercedValue.toString() !== cleanedValue) {
          throw new BSONError(`Input: '${value}' is not a valid Int32 string`);
        }
        return new _Int32(coercedValue);
      }
      valueOf() {
        return this.value;
      }
      toString(radix) {
        return this.value.toString(radix);
      }
      toJSON() {
        return this.value;
      }
      toExtendedJSON(options) {
        if (options && (options.relaxed || options.legacy))
          return this.value;
        return { $numberInt: this.value.toString() };
      }
      static fromExtendedJSON(doc, options) {
        return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new _Int32(doc.$numberInt);
      }
      inspect(depth, options, inspect) {
        inspect ??= defaultInspect;
        return `new Int32(${inspect(this.value, options)})`;
      }
    };
    var MaxKey = class _MaxKey extends BSONValue {
      get _bsontype() {
        return "MaxKey";
      }
      toExtendedJSON() {
        return { $maxKey: 1 };
      }
      static fromExtendedJSON() {
        return new _MaxKey();
      }
      inspect() {
        return "new MaxKey()";
      }
    };
    var MinKey = class _MinKey extends BSONValue {
      get _bsontype() {
        return "MinKey";
      }
      toExtendedJSON() {
        return { $minKey: 1 };
      }
      static fromExtendedJSON() {
        return new _MinKey();
      }
      inspect() {
        return "new MinKey()";
      }
    };
    var __idCache = /* @__PURE__ */ new WeakMap();
    var ObjectId = class _ObjectId extends BSONValue {
      get _bsontype() {
        return "ObjectId";
      }
      static index = 0;
      static PROCESS_UNIQUE = null;
      static resetState = () => {
        this.index = Math.floor(Math.random() * 16777216);
        this.PROCESS_UNIQUE = ByteUtils.randomBytes(5);
      };
      static {
        this.resetState();
        const { startupSnapshot } = globalThis?.process?.getBuiltinModule?.("v8") ?? {};
        if (startupSnapshot?.isBuildingSnapshot?.()) {
          startupSnapshot?.addDeserializeCallback?.(this.resetState);
        }
      }
      static cacheHexString;
      buffer;
      constructor(inputId) {
        super();
        let workingId;
        if (typeof inputId === "object" && inputId && "id" in inputId) {
          if (typeof inputId.id !== "string" && !ArrayBuffer.isView(inputId.id)) {
            throw new BSONError("Argument passed in must have an id that is of type string or Buffer");
          }
          if ("toHexString" in inputId && typeof inputId.toHexString === "function") {
            workingId = ByteUtils.fromHex(inputId.toHexString());
          } else {
            workingId = inputId.id;
          }
        } else {
          workingId = inputId;
        }
        if (workingId == null) {
          this.buffer = _ObjectId.generate();
        } else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
          this.buffer = ByteUtils.toLocalBufferType(workingId);
        } else if (typeof workingId === "string") {
          if (_ObjectId.validateHexString(workingId)) {
            this.buffer = ByteUtils.fromHex(workingId);
            if (_ObjectId.cacheHexString) {
              __idCache.set(this, workingId);
            }
          } else {
            throw new BSONError("input must be a 24 character hex string, 12 byte Uint8Array, or an integer");
          }
        } else {
          throw new BSONError("Argument passed in does not match the accepted types");
        }
      }
      get id() {
        return this.buffer;
      }
      set id(value) {
        this.buffer = value;
        if (_ObjectId.cacheHexString) {
          __idCache.set(this, ByteUtils.toHex(value));
        }
      }
      static validateHexString(string4) {
        if (string4?.length !== 24)
          return false;
        for (let i2 = 0; i2 < 24; i2++) {
          const char = string4.charCodeAt(i2);
          if (char >= 48 && char <= 57 || char >= 97 && char <= 102 || char >= 65 && char <= 70) {
            continue;
          }
          return false;
        }
        return true;
      }
      toHexString() {
        if (_ObjectId.cacheHexString) {
          const __id = __idCache.get(this);
          if (__id)
            return __id;
        }
        const hexString = ByteUtils.toHex(this.id);
        if (_ObjectId.cacheHexString) {
          __idCache.set(this, hexString);
        }
        return hexString;
      }
      static getInc() {
        return _ObjectId.index = (_ObjectId.index + 1) % 16777216;
      }
      static generate(time3) {
        if ("number" !== typeof time3) {
          time3 = Math.floor(Date.now() / 1e3);
        }
        const inc = _ObjectId.getInc();
        const buffer2 = ByteUtils.allocateUnsafe(12);
        NumberUtils.setInt32BE(buffer2, 0, time3);
        const PROCESS_UNIQUE = this.PROCESS_UNIQUE;
        buffer2[4] = PROCESS_UNIQUE[0];
        buffer2[5] = PROCESS_UNIQUE[1];
        buffer2[6] = PROCESS_UNIQUE[2];
        buffer2[7] = PROCESS_UNIQUE[3];
        buffer2[8] = PROCESS_UNIQUE[4];
        buffer2[11] = inc & 255;
        buffer2[10] = inc >> 8 & 255;
        buffer2[9] = inc >> 16 & 255;
        return buffer2;
      }
      toString(encoding) {
        if (encoding === "base64")
          return ByteUtils.toBase64(this.id);
        if (encoding === "hex")
          return this.toHexString();
        return this.toHexString();
      }
      toJSON() {
        return this.toHexString();
      }
      static is(variable) {
        return variable != null && typeof variable === "object" && "_bsontype" in variable && variable._bsontype === "ObjectId";
      }
      equals(otherId) {
        if (otherId === void 0 || otherId === null) {
          return false;
        }
        if (_ObjectId.is(otherId)) {
          return this.buffer[11] === otherId.buffer[11] && ByteUtils.equals(this.buffer, otherId.buffer);
        }
        if (typeof otherId === "string") {
          return otherId.toLowerCase() === this.toHexString();
        }
        if (typeof otherId === "object" && typeof otherId.toHexString === "function") {
          const otherIdString = otherId.toHexString();
          const thisIdString = this.toHexString();
          return typeof otherIdString === "string" && otherIdString.toLowerCase() === thisIdString;
        }
        return false;
      }
      getTimestamp() {
        const timestamp = /* @__PURE__ */ new Date();
        const time3 = NumberUtils.getUint32BE(this.buffer, 0);
        timestamp.setTime(Math.floor(time3) * 1e3);
        return timestamp;
      }
      static createPk() {
        return new _ObjectId();
      }
      serializeInto(uint8array, index) {
        uint8array[index] = this.buffer[0];
        uint8array[index + 1] = this.buffer[1];
        uint8array[index + 2] = this.buffer[2];
        uint8array[index + 3] = this.buffer[3];
        uint8array[index + 4] = this.buffer[4];
        uint8array[index + 5] = this.buffer[5];
        uint8array[index + 6] = this.buffer[6];
        uint8array[index + 7] = this.buffer[7];
        uint8array[index + 8] = this.buffer[8];
        uint8array[index + 9] = this.buffer[9];
        uint8array[index + 10] = this.buffer[10];
        uint8array[index + 11] = this.buffer[11];
        return 12;
      }
      static createFromTime(time3) {
        const buffer2 = ByteUtils.allocate(12);
        for (let i2 = 11; i2 >= 4; i2--)
          buffer2[i2] = 0;
        NumberUtils.setInt32BE(buffer2, 0, time3);
        return new _ObjectId(buffer2);
      }
      static createFromHexString(hexString) {
        if (hexString?.length !== 24) {
          throw new BSONError("hex string must be 24 characters");
        }
        return new _ObjectId(ByteUtils.fromHex(hexString));
      }
      static createFromBase64(base643) {
        if (base643?.length !== 16) {
          throw new BSONError("base64 string must be 16 characters");
        }
        return new _ObjectId(ByteUtils.fromBase64(base643));
      }
      static isValid(id) {
        if (id == null)
          return false;
        if (typeof id === "string")
          return _ObjectId.validateHexString(id);
        try {
          new _ObjectId(id);
          return true;
        } catch {
          return false;
        }
      }
      toExtendedJSON() {
        if (this.toHexString)
          return { $oid: this.toHexString() };
        return { $oid: this.toString("hex") };
      }
      static fromExtendedJSON(doc) {
        return new _ObjectId(doc.$oid);
      }
      isCached() {
        return _ObjectId.cacheHexString && __idCache.has(this);
      }
      inspect(depth, options, inspect) {
        inspect ??= defaultInspect;
        return `new ObjectId(${inspect(this.toHexString(), options)})`;
      }
    };
    function internalCalculateObjectSize(object3, serializeFunctions, ignoreUndefined) {
      const objectStack = [
        { obj: object3, ignoreUndefined: ignoreUndefined ?? false }
      ];
      let total = 0;
      while (objectStack.length > 0) {
        const { obj, ignoreUndefined: frameIgnoreUndefined } = objectStack.pop();
        total += 5;
        const isObjArray = Array.isArray(obj);
        let target = obj;
        if (!isObjArray && typeof obj?.toBSON === "function") {
          target = obj.toBSON();
        }
        if (isObjArray) {
          const array2 = target;
          for (let i2 = 0; i2 < array2.length; i2++) {
            total += calculateElementSize(i2.toString(), array2[i2], serializeFunctions, true, frameIgnoreUndefined, objectStack);
          }
        } else {
          for (const key of Object.keys(target)) {
            total += calculateElementSize(key, target[key], serializeFunctions, false, frameIgnoreUndefined, objectStack);
          }
        }
      }
      return total;
    }
    function calculateElementSize(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false, objectStack) {
      if (typeof value?.toBSON === "function") {
        value = value.toBSON();
      }
      switch (typeof value) {
        case "string":
          return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1;
        case "number":
          if (Math.floor(value) === value && value >= JS_INT_MIN && value <= JS_INT_MAX) {
            if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
              return ByteUtils.utf8ByteLength(name) + 1 + (4 + 1);
            } else {
              return ByteUtils.utf8ByteLength(name) + 1 + (8 + 1);
            }
          } else {
            return ByteUtils.utf8ByteLength(name) + 1 + (8 + 1);
          }
        case "undefined":
          if (isArray || !ignoreUndefined)
            return ByteUtils.utf8ByteLength(name) + 1 + 1;
          return 0;
        case "boolean":
          return ByteUtils.utf8ByteLength(name) + 1 + (1 + 1);
        case "object":
          if (value != null && typeof value._bsontype === "string" && value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
            throw new BSONVersionError();
          } else if (value == null || value._bsontype === "MinKey" || value._bsontype === "MaxKey") {
            return ByteUtils.utf8ByteLength(name) + 1 + 1;
          } else if (value._bsontype === "ObjectId") {
            return ByteUtils.utf8ByteLength(name) + 1 + (12 + 1);
          } else if (value instanceof Date || isDate(value)) {
            return ByteUtils.utf8ByteLength(name) + 1 + (8 + 1);
          } else if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer || isAnyArrayBuffer(value)) {
            return ByteUtils.utf8ByteLength(name) + 1 + (1 + 4 + 1) + value.byteLength;
          } else if (value._bsontype === "Long" || value._bsontype === "Double" || value._bsontype === "Timestamp") {
            return ByteUtils.utf8ByteLength(name) + 1 + (8 + 1);
          } else if (value._bsontype === "Decimal128") {
            return ByteUtils.utf8ByteLength(name) + 1 + (16 + 1);
          } else if (value._bsontype === "Code") {
            if (value.scope != null && Object.keys(value.scope).length > 0) {
              objectStack.push({ obj: value.scope, ignoreUndefined });
              return ByteUtils.utf8ByteLength(name) + 1 + 1 + 4 + 4 + ByteUtils.utf8ByteLength(value.code.toString()) + 1;
            } else {
              return ByteUtils.utf8ByteLength(name) + 1 + 1 + 4 + ByteUtils.utf8ByteLength(value.code.toString()) + 1;
            }
          } else if (value._bsontype === "Binary") {
            const binary = value;
            if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
              return ByteUtils.utf8ByteLength(name) + 1 + (binary.position + 1 + 4 + 1 + 4);
            } else {
              return ByteUtils.utf8ByteLength(name) + 1 + (binary.position + 1 + 4 + 1);
            }
          } else if (value._bsontype === "Symbol") {
            return ByteUtils.utf8ByteLength(name) + 1 + ByteUtils.utf8ByteLength(value.value) + 4 + 1 + 1;
          } else if (value._bsontype === "DBRef") {
            const ordered_values = Object.assign({
              $ref: value.collection,
              $id: value.oid
            }, value.fields);
            if (value.db != null) {
              ordered_values["$db"] = value.db;
            }
            objectStack.push({ obj: ordered_values, ignoreUndefined: true });
            return ByteUtils.utf8ByteLength(name) + 1 + 1;
          } else if (value instanceof RegExp || isRegExp(value)) {
            return ByteUtils.utf8ByteLength(name) + 1 + 1 + ByteUtils.utf8ByteLength(value.source) + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1;
          } else if (value._bsontype === "BSONRegExp") {
            return ByteUtils.utf8ByteLength(name) + 1 + 1 + ByteUtils.utf8ByteLength(value.pattern) + 1 + ByteUtils.utf8ByteLength(value.options) + 1;
          } else {
            objectStack.push({ obj: value, ignoreUndefined });
            return ByteUtils.utf8ByteLength(name) + 1 + 1;
          }
        case "function":
          if (serializeFunctions) {
            return ByteUtils.utf8ByteLength(name) + 1 + 1 + 4 + ByteUtils.utf8ByteLength(value.toString()) + 1;
          }
          return 0;
        case "bigint":
          return ByteUtils.utf8ByteLength(name) + 1 + (8 + 1);
        case "symbol":
          return 0;
        default:
          throw new BSONError(`Unrecognized JS type: ${typeof value}`);
      }
    }
    function alphabetize(str) {
      return str.split("").sort().join("");
    }
    var BSONRegExp = class _BSONRegExp extends BSONValue {
      get _bsontype() {
        return "BSONRegExp";
      }
      pattern;
      options;
      constructor(pattern, options) {
        super();
        this.pattern = pattern;
        this.options = alphabetize(options ?? "");
        if (this.pattern.indexOf("\0") !== -1) {
          throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);
        }
        if (this.options.indexOf("\0") !== -1) {
          throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);
        }
        for (let i2 = 0; i2 < this.options.length; i2++) {
          if (!(this.options[i2] === "i" || this.options[i2] === "m" || this.options[i2] === "x" || this.options[i2] === "l" || this.options[i2] === "s" || this.options[i2] === "u")) {
            throw new BSONError(`The regular expression option [${this.options[i2]}] is not supported`);
          }
        }
      }
      static parseOptions(options) {
        return options ? options.split("").sort().join("") : "";
      }
      toExtendedJSON(options) {
        options = options || {};
        if (options.legacy) {
          return { $regex: this.pattern, $options: this.options };
        }
        return { $regularExpression: { pattern: this.pattern, options: this.options } };
      }
      static fromExtendedJSON(doc) {
        if ("$regex" in doc) {
          if (typeof doc.$regex !== "string") {
            if (doc.$regex._bsontype === "BSONRegExp") {
              return doc;
            }
          } else {
            return new _BSONRegExp(doc.$regex, _BSONRegExp.parseOptions(doc.$options));
          }
        }
        if ("$regularExpression" in doc) {
          return new _BSONRegExp(doc.$regularExpression.pattern, _BSONRegExp.parseOptions(doc.$regularExpression.options));
        }
        throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`);
      }
      inspect(depth, options, inspect) {
        const stylize = getStylizeFunction(options) ?? ((v) => v);
        inspect ??= defaultInspect;
        const pattern = stylize(inspect(this.pattern), "regexp");
        const flags = stylize(inspect(this.options), "regexp");
        return `new BSONRegExp(${pattern}, ${flags})`;
      }
    };
    var BSONSymbol = class _BSONSymbol extends BSONValue {
      get _bsontype() {
        return "BSONSymbol";
      }
      value;
      constructor(value) {
        super();
        this.value = value;
      }
      valueOf() {
        return this.value;
      }
      toString() {
        return this.value;
      }
      toJSON() {
        return this.value;
      }
      toExtendedJSON() {
        return { $symbol: this.value };
      }
      static fromExtendedJSON(doc) {
        return new _BSONSymbol(doc.$symbol);
      }
      inspect(depth, options, inspect) {
        inspect ??= defaultInspect;
        return `new BSONSymbol(${inspect(this.value, options)})`;
      }
    };
    var LongWithoutOverridesClass = Long;
    var Timestamp = class _Timestamp extends LongWithoutOverridesClass {
      get _bsontype() {
        return "Timestamp";
      }
      get [bsonType]() {
        return "Timestamp";
      }
      static MAX_VALUE = Long.MAX_UNSIGNED_VALUE;
      get i() {
        return this.low >>> 0;
      }
      get t() {
        return this.high >>> 0;
      }
      constructor(low) {
        if (low == null) {
          super(0, 0, true);
        } else if (typeof low === "bigint") {
          super(low, true);
        } else if (Long.isLong(low)) {
          super(low.low, low.high, true);
        } else if (typeof low === "object" && "t" in low && "i" in low) {
          if (typeof low.t !== "number" && (typeof low.t !== "object" || low.t._bsontype !== "Int32")) {
            throw new BSONError("Timestamp constructed from { t, i } must provide t as a number");
          }
          if (typeof low.i !== "number" && (typeof low.i !== "object" || low.i._bsontype !== "Int32")) {
            throw new BSONError("Timestamp constructed from { t, i } must provide i as a number");
          }
          const t2 = Number(low.t);
          const i2 = Number(low.i);
          if (t2 < 0 || Number.isNaN(t2)) {
            throw new BSONError("Timestamp constructed from { t, i } must provide a positive t");
          }
          if (i2 < 0 || Number.isNaN(i2)) {
            throw new BSONError("Timestamp constructed from { t, i } must provide a positive i");
          }
          if (t2 > 4294967295) {
            throw new BSONError("Timestamp constructed from { t, i } must provide t equal or less than uint32 max");
          }
          if (i2 > 4294967295) {
            throw new BSONError("Timestamp constructed from { t, i } must provide i equal or less than uint32 max");
          }
          super(i2, t2, true);
        } else {
          throw new BSONError("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }");
        }
      }
      toJSON() {
        return {
          $timestamp: this.toString()
        };
      }
      static fromInt(value) {
        return new _Timestamp(Long.fromInt(value, true));
      }
      static fromNumber(value) {
        return new _Timestamp(Long.fromNumber(value, true));
      }
      static fromBits(lowBits, highBits) {
        return new _Timestamp({ i: lowBits, t: highBits });
      }
      static fromString(str, optRadix) {
        return new _Timestamp(Long.fromString(str, true, optRadix));
      }
      toExtendedJSON() {
        return { $timestamp: { t: this.t, i: this.i } };
      }
      static fromExtendedJSON(doc) {
        const i2 = Long.isLong(doc.$timestamp.i) ? doc.$timestamp.i.getLowBitsUnsigned() : doc.$timestamp.i;
        const t2 = Long.isLong(doc.$timestamp.t) ? doc.$timestamp.t.getLowBitsUnsigned() : doc.$timestamp.t;
        return new _Timestamp({ t: t2, i: i2 });
      }
      inspect(depth, options, inspect) {
        inspect ??= defaultInspect;
        const t2 = inspect(this.t, options);
        const i2 = inspect(this.i, options);
        return `new Timestamp({ t: ${t2}, i: ${i2} })`;
      }
    };
    var JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX);
    var JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN);
    function internalDeserialize(buffer2, options, isArray) {
      options = options == null ? {} : options;
      const index = options && options.index ? options.index : 0;
      const size = NumberUtils.getInt32LE(buffer2, index);
      if (size < 5) {
        throw new BSONError(`bson size must be >= 5, is ${size}`);
      }
      if (options.allowObjectSmallerThanBufferSize && buffer2.length < size) {
        throw new BSONError(`buffer length ${buffer2.length} must be >= bson size ${size}`);
      }
      if (!options.allowObjectSmallerThanBufferSize && buffer2.length !== size) {
        throw new BSONError(`buffer length ${buffer2.length} must === bson size ${size}`);
      }
      if (size + index > buffer2.byteLength) {
        throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer2.byteLength})`);
      }
      if (buffer2[index + size - 1] !== 0) {
        throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
      }
      return deserializeObject(buffer2, index, options, isArray);
    }
    var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/;
    function assignValue(dest, name, value) {
      if (name === "__proto__") {
        Object.defineProperty(dest, name, {
          value,
          writable: true,
          enumerable: true,
          configurable: true
        });
      } else {
        dest[name] = value;
      }
    }
    function toPotentialDbRef(doc) {
      if (isDBRefLike(doc)) {
        const { $ref, $id, $db, ...fields } = doc;
        return new DBRef($ref, $id, $db, fields);
      }
      return doc;
    }
    function deserializeObject(buffer2, index, options, isArray = false) {
      options = { ...options };
      const fieldsAsRaw = options["fieldsAsRaw"] == null ? null : options["fieldsAsRaw"];
      const raw = options["raw"] == null ? false : options["raw"];
      const bsonRegExp = typeof options["bsonRegExp"] === "boolean" ? options["bsonRegExp"] : false;
      const promoteBuffers = options.promoteBuffers ?? false;
      const promoteLongs = options.promoteLongs ?? true;
      const promoteValues = options.promoteValues ?? true;
      const useBigInt64 = options.useBigInt64 ?? false;
      if (useBigInt64 && !promoteValues) {
        throw new BSONError("Must either request bigint or Long for int64 deserialization");
      }
      if (useBigInt64 && !promoteLongs) {
        throw new BSONError("Must either request bigint or Long for int64 deserialization");
      }
      const validation = options.validation == null ? { utf8: true } : options.validation;
      let globalUTFValidation = true;
      let validationSetting;
      let utf8KeysSet;
      const utf8ValidatedKeys = validation.utf8;
      if (typeof utf8ValidatedKeys === "boolean") {
        validationSetting = utf8ValidatedKeys;
      } else {
        globalUTFValidation = false;
        const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function(key) {
          return utf8ValidatedKeys[key];
        });
        if (utf8ValidationValues.length === 0) {
          throw new BSONError("UTF-8 validation setting cannot be empty");
        }
        if (typeof utf8ValidationValues[0] !== "boolean") {
          throw new BSONError("Invalid UTF-8 validation option, must specify boolean values");
        }
        validationSetting = utf8ValidationValues[0];
        if (!utf8ValidationValues.every((item) => item === validationSetting)) {
          throw new BSONError("Invalid UTF-8 validation option - keys must be all true or all false");
        }
      }
      if (!globalUTFValidation) {
        utf8KeysSet = /* @__PURE__ */ new Set();
        for (const key of Object.keys(utf8ValidatedKeys)) {
          utf8KeysSet.add(key);
        }
      }
      const startIndex = index;
      if (buffer2.length < 5)
        throw new BSONError("corrupt bson message < 5 bytes long");
      const size = NumberUtils.getInt32LE(buffer2, index);
      index += 4;
      if (size < 5 || size > buffer2.length)
        throw new BSONError("corrupt bson message");
      const rootObject = isArray ? [] : {};
      let arrayIndex = 0;
      let isPossibleDBRef = isArray ? false : null;
      let currentFrame = null;
      let currentDest = rootObject;
      let currentIsArray = isArray;
      while (true) {
        const elementType = buffer2[index++];
        if (elementType === 0) {
          if (currentFrame) {
            if (index === currentFrame.lastIndex) {
              const completedFrame = currentFrame;
              currentFrame = completedFrame.prev;
              if (currentFrame === null) {
                currentDest = rootObject;
                currentIsArray = isArray;
              } else {
                currentDest = currentFrame.holdingDocument;
                currentIsArray = currentFrame.isArray;
              }
              let result = completedFrame.holdingDocument;
              switch (completedFrame.elementType) {
                case BSON_DATA_OBJECT:
                  if (completedFrame.isPossibleDBRef) {
                    result = toPotentialDbRef(result);
                  }
                  break;
                case BSON_DATA_ARRAY:
                  break;
                case BSON_DATA_CODE_W_SCOPE:
                  result = new Code(completedFrame.functionString, completedFrame.holdingDocument);
                  break;
                default:
                  throw new BSONError("Unexpected element type in frame stack");
              }
              assignValue(currentDest, completedFrame.propertyName, result);
              continue;
            } else {
              if (currentFrame.elementType === BSON_DATA_ARRAY) {
                throw new BSONError("corrupted array bson");
              }
              throw new BSONError("Bad BSON Document: object not properly terminated");
            }
          } else {
            break;
          }
        }
        let i2 = index;
        while (buffer2[i2] !== 0 && i2 < buffer2.length) {
          i2++;
        }
        if (i2 >= buffer2.byteLength)
          throw new BSONError("Bad BSON Document: illegal CString");
        const name = currentIsArray ? currentFrame !== null ? currentFrame.arrayIndex++ : arrayIndex++ : ByteUtils.toUTF8(buffer2, index, i2, false);
        let shouldValidateKey;
        if (currentFrame !== null) {
          shouldValidateKey = currentFrame.validationSetting;
        } else if (globalUTFValidation || utf8KeysSet?.has(name)) {
          shouldValidateKey = validationSetting;
        } else {
          shouldValidateKey = !validationSetting;
        }
        if (currentFrame !== null) {
          if (currentFrame.isPossibleDBRef !== false && typeof name === "string" && name[0] === "$") {
            currentFrame.isPossibleDBRef = allowedDBRefKeys.test(name);
          }
        } else if (isPossibleDBRef !== false && name[0] === "$") {
          isPossibleDBRef = allowedDBRefKeys.test(name);
        }
        let value;
        let isDeferredValue = false;
        index = i2 + 1;
        if (elementType === BSON_DATA_STRING) {
          const stringSize = NumberUtils.getInt32LE(buffer2, index);
          index += 4;
          if (stringSize <= 0 || stringSize > buffer2.length - index || buffer2[index + stringSize - 1] !== 0) {
            throw new BSONError("bad string length in bson");
          }
          value = ByteUtils.toUTF8(buffer2, index, index + stringSize - 1, shouldValidateKey);
          index = index + stringSize;
        } else if (elementType === BSON_DATA_OID) {
          const oid = ByteUtils.allocateUnsafe(12);
          for (let i3 = 0; i3 < 12; i3++)
            oid[i3] = buffer2[index + i3];
          value = new ObjectId(oid);
          index = index + 12;
        } else if (elementType === BSON_DATA_INT && promoteValues === false) {
          value = new Int32(NumberUtils.getInt32LE(buffer2, index));
          index += 4;
        } else if (elementType === BSON_DATA_INT) {
          value = NumberUtils.getInt32LE(buffer2, index);
          index += 4;
        } else if (elementType === BSON_DATA_NUMBER) {
          value = NumberUtils.getFloat64LE(buffer2, index);
          index += 8;
          if (promoteValues === false)
            value = new Double(value);
        } else if (elementType === BSON_DATA_DATE) {
          const lowBits = NumberUtils.getInt32LE(buffer2, index);
          const highBits = NumberUtils.getInt32LE(buffer2, index + 4);
          index += 8;
          value = new Date(new Long(lowBits, highBits).toNumber());
        } else if (elementType === BSON_DATA_BOOLEAN) {
          if (buffer2[index] !== 0 && buffer2[index] !== 1)
            throw new BSONError("illegal boolean type value");
          value = buffer2[index++] === 1;
        } else if (elementType === BSON_DATA_OBJECT) {
          const objectSize = NumberUtils.getInt32LE(buffer2, index);
          if (objectSize < 5 || objectSize > buffer2.length - index)
            throw new BSONError("bad embedded document length in bson");
          if (raw || (currentFrame?.raw ?? false)) {
            value = buffer2.subarray(index, index + objectSize);
            index = index + objectSize;
          } else {
            isDeferredValue = true;
            const objectFrame = {
              holdingDocument: {},
              elementType: BSON_DATA_OBJECT,
              propertyName: name,
              functionString: null,
              lastIndex: index + objectSize,
              isArray: false,
              arrayIndex: 0,
              raw: false,
              isPossibleDBRef: null,
              validationSetting: shouldValidateKey,
              prev: currentFrame
            };
            currentFrame = objectFrame;
            currentDest = objectFrame.holdingDocument;
            currentIsArray = false;
            index = index + 4;
          }
        } else if (elementType === BSON_DATA_ARRAY) {
          const objectSize = NumberUtils.getInt32LE(buffer2, index);
          if (objectSize < 5 || objectSize > buffer2.length - index)
            throw new BSONError("bad embedded array length in bson");
          const stopIndex = index + objectSize;
          const arrayRaw = !!(fieldsAsRaw && fieldsAsRaw[name]) || (currentFrame?.raw ?? false);
          isDeferredValue = true;
          const arrayFrame = {
            holdingDocument: [],
            elementType: BSON_DATA_ARRAY,
            propertyName: name,
            functionString: null,
            lastIndex: stopIndex,
            isArray: true,
            arrayIndex: 0,
            raw: arrayRaw,
            isPossibleDBRef: false,
            validationSetting: shouldValidateKey,
            prev: currentFrame
          };
          currentFrame = arrayFrame;
          currentDest = arrayFrame.holdingDocument;
          currentIsArray = true;
          index = index + 4;
        } else if (elementType === BSON_DATA_UNDEFINED) {
          value = void 0;
        } else if (elementType === BSON_DATA_NULL) {
          value = null;
        } else if (elementType === BSON_DATA_LONG) {
          if (useBigInt64) {
            value = NumberUtils.getBigInt64LE(buffer2, index);
            index += 8;
          } else {
            const lowBits = NumberUtils.getInt32LE(buffer2, index);
            const highBits = NumberUtils.getInt32LE(buffer2, index + 4);
            index += 8;
            const long = new Long(lowBits, highBits);
            if (promoteLongs && promoteValues === true) {
              value = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long;
            } else {
              value = long;
            }
          }
        } else if (elementType === BSON_DATA_DECIMAL128) {
          const bytes = ByteUtils.allocateUnsafe(16);
          for (let i3 = 0; i3 < 16; i3++)
            bytes[i3] = buffer2[index + i3];
          index = index + 16;
          value = new Decimal128(bytes);
        } else if (elementType === BSON_DATA_BINARY) {
          let binarySize = NumberUtils.getInt32LE(buffer2, index);
          index += 4;
          const totalBinarySize = binarySize;
          const subType = buffer2[index++];
          if (binarySize < 0)
            throw new BSONError("Negative binary type element size found");
          if (binarySize > buffer2.byteLength)
            throw new BSONError("Binary type size larger than document size");
          if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
            binarySize = NumberUtils.getInt32LE(buffer2, index);
            index += 4;
            if (binarySize < 0)
              throw new BSONError("Negative binary type element size found for subtype 0x02");
            if (binarySize > totalBinarySize - 4)
              throw new BSONError("Binary type with subtype 0x02 contains too long binary size");
            if (binarySize < totalBinarySize - 4)
              throw new BSONError("Binary type with subtype 0x02 contains too short binary size");
          }
          if (promoteBuffers && promoteValues) {
            value = ByteUtils.toLocalBufferType(buffer2.subarray(index, index + binarySize));
          } else {
            value = new Binary(buffer2.subarray(index, index + binarySize), subType);
            if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) {
              value = value.toUUID();
            }
          }
          index = index + binarySize;
        } else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) {
          i2 = index;
          while (buffer2[i2] !== 0 && i2 < buffer2.length) {
            i2++;
          }
          if (i2 >= buffer2.length)
            throw new BSONError("Bad BSON Document: illegal CString");
          const source = ByteUtils.toUTF8(buffer2, index, i2, false);
          index = i2 + 1;
          i2 = index;
          while (buffer2[i2] !== 0 && i2 < buffer2.length) {
            i2++;
          }
          if (i2 >= buffer2.length)
            throw new BSONError("Bad BSON Document: illegal CString");
          const regExpOptions = ByteUtils.toUTF8(buffer2, index, i2, false);
          index = i2 + 1;
          const optionsArray = new Array(regExpOptions.length);
          for (i2 = 0; i2 < regExpOptions.length; i2++) {
            switch (regExpOptions[i2]) {
              case "m":
                optionsArray[i2] = "m";
                break;
              case "s":
                optionsArray[i2] = "g";
                break;
              case "i":
                optionsArray[i2] = "i";
                break;
            }
          }
          value = new RegExp(source, optionsArray.join(""));
        } else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) {
          i2 = index;
          while (buffer2[i2] !== 0 && i2 < buffer2.length) {
            i2++;
          }
          if (i2 >= buffer2.length)
            throw new BSONError("Bad BSON Document: illegal CString");
          const source = ByteUtils.toUTF8(buffer2, index, i2, false);
          index = i2 + 1;
          i2 = index;
          while (buffer2[i2] !== 0 && i2 < buffer2.length) {
            i2++;
          }
          if (i2 >= buffer2.length)
            throw new BSONError("Bad BSON Document: illegal CString");
          const regExpOptions = ByteUtils.toUTF8(buffer2, index, i2, false);
          index = i2 + 1;
          value = new BSONRegExp(source, regExpOptions);
        } else if (elementType === BSON_DATA_SYMBOL) {
          const stringSize = NumberUtils.getInt32LE(buffer2, index);
          index += 4;
          if (stringSize <= 0 || stringSize > buffer2.length - index || buffer2[index + stringSize - 1] !== 0) {
            throw new BSONError("bad string length in bson");
          }
          const symbol2 = ByteUtils.toUTF8(buffer2, index, index + stringSize - 1, shouldValidateKey);
          value = promoteValues ? symbol2 : new BSONSymbol(symbol2);
          index = index + stringSize;
        } else if (elementType === BSON_DATA_TIMESTAMP) {
          value = new Timestamp({
            i: NumberUtils.getUint32LE(buffer2, index),
            t: NumberUtils.getUint32LE(buffer2, index + 4)
          });
          index += 8;
        } else if (elementType === BSON_DATA_MIN_KEY) {
          value = new MinKey();
        } else if (elementType === BSON_DATA_MAX_KEY) {
          value = new MaxKey();
        } else if (elementType === BSON_DATA_CODE) {
          const stringSize = NumberUtils.getInt32LE(buffer2, index);
          index += 4;
          if (stringSize <= 0 || stringSize > buffer2.length - index || buffer2[index + stringSize - 1] !== 0) {
            throw new BSONError("bad string length in bson");
          }
          const functionString = ByteUtils.toUTF8(buffer2, index, index + stringSize - 1, shouldValidateKey);
          value = new Code(functionString);
          index = index + stringSize;
        } else if (elementType === BSON_DATA_CODE_W_SCOPE) {
          const totalSize = NumberUtils.getInt32LE(buffer2, index);
          index += 4;
          if (totalSize < 4 + 4 + 4 + 1) {
            throw new BSONError("code_w_scope total size shorter minimum expected length");
          }
          const stringSize = NumberUtils.getInt32LE(buffer2, index);
          index += 4;
          if (stringSize <= 0 || stringSize > buffer2.length - index || buffer2[index + stringSize - 1] !== 0) {
            throw new BSONError("bad string length in bson");
          }
          const functionString = ByteUtils.toUTF8(buffer2, index, index + stringSize - 1, shouldValidateKey);
          index = index + stringSize;
          const _index = index;
          const objectSize = NumberUtils.getInt32LE(buffer2, index);
          if (objectSize < 5 || objectSize > buffer2.length - index)
            throw new BSONError("bad scope document size in code_w_scope");
          if (totalSize < 4 + 4 + objectSize + stringSize) {
            throw new BSONError("code_w_scope total size is too short, truncating scope");
          }
          if (totalSize > 4 + 4 + objectSize + stringSize) {
            throw new BSONError("code_w_scope total size is too long, clips outer document");
          }
          isDeferredValue = true;
          const scopeFrame = {
            holdingDocument: {},
            elementType: BSON_DATA_CODE_W_SCOPE,
            propertyName: name,
            functionString,
            lastIndex: _index + objectSize,
            isArray: false,
            arrayIndex: 0,
            raw: false,
            isPossibleDBRef: null,
            validationSetting: shouldValidateKey,
            prev: currentFrame
          };
          currentFrame = scopeFrame;
          currentDest = scopeFrame.holdingDocument;
          currentIsArray = false;
          index = index + 4;
        } else if (elementType === BSON_DATA_DBPOINTER) {
          const stringSize = NumberUtils.getInt32LE(buffer2, index);
          index += 4;
          if (stringSize <= 0 || stringSize > buffer2.length - index || buffer2[index + stringSize - 1] !== 0)
            throw new BSONError("bad string length in bson");
          const namespace = ByteUtils.toUTF8(buffer2, index, index + stringSize - 1, shouldValidateKey);
          index = index + stringSize;
          const oidBuffer = ByteUtils.allocateUnsafe(12);
          for (let i3 = 0; i3 < 12; i3++)
            oidBuffer[i3] = buffer2[index + i3];
          const oid = new ObjectId(oidBuffer);
          index = index + 12;
          value = new DBRef(namespace, oid);
        } else {
          throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`);
        }
        if (!isDeferredValue) {
          assignValue(currentDest, name, value);
        }
      }
      if (currentFrame !== null) {
        throw new BSONError("corrupted bson, more objects expected based on the current document size");
      }
      const object3 = rootObject;
      if (size !== index - startIndex) {
        if (isArray)
          throw new BSONError("corrupt array bson");
        throw new BSONError("corrupt object bson");
      }
      if (!isPossibleDBRef)
        return object3;
      return toPotentialDbRef(object3);
    }
    var regexp = /\x00/;
    var ignoreKeys = /* @__PURE__ */ new Set(["$db", "$ref", "$id", "$clusterTime"]);
    function serializeString(buffer2, key, value, index) {
      buffer2[index++] = BSON_DATA_STRING;
      const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
      index = index + numberOfWrittenBytes + 1;
      buffer2[index - 1] = 0;
      const size = ByteUtils.encodeUTF8Into(buffer2, value, index + 4);
      NumberUtils.setInt32LE(buffer2, index, size + 1);
      index = index + 4 + size;
      buffer2[index++] = 0;
      return index;
    }
    function serializeNumber(buffer2, key, value, index) {
      const isNegativeZero = Object.is(value, -0);
      const type = !isNegativeZero && Number.isSafeInteger(value) && value <= BSON_INT32_MAX && value >= BSON_INT32_MIN ? BSON_DATA_INT : BSON_DATA_NUMBER;
      buffer2[index++] = type;
      const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
      index = index + numberOfWrittenBytes;
      buffer2[index++] = 0;
      if (type === BSON_DATA_INT) {
        index += NumberUtils.setInt32LE(buffer2, index, value);
      } else {
        index += NumberUtils.setFloat64LE(buffer2, index, value);
      }
      return index;
    }
    function serializeBigInt(buffer2, key, value, index) {
      buffer2[index++] = BSON_DATA_LONG;
      const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
      index += numberOfWrittenBytes;
      buffer2[index++] = 0;
      index += NumberUtils.setBigInt64LE(buffer2, index, value);
      return index;
    }
    function serializeNull(buffer2, key, _, index) {
      buffer2[index++] = BSON_DATA_NULL;
      const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
      index = index + numberOfWrittenBytes;
      buffer2[index++] = 0;
      return index;
    }
    function serializeBoolean(buffer2, key, value, index) {
      buffer2[index++] = BSON_DATA_BOOLEAN;
      const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
      index = index + numberOfWrittenBytes;
      buffer2[index++] = 0;
      buffer2[index++] = value ? 1 : 0;
      return index;
    }
    function serializeDate(buffer2, key, value, index) {
      buffer2[index++] = BSON_DATA_DATE;
      const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
      index = index + numberOfWrittenBytes;
      buffer2[index++] = 0;
      const dateInMilis = Long.fromNumber(value.getTime());
      const lowBits = dateInMilis.getLowBits();
      const highBits = dateInMilis.getHighBits();
      index += NumberUtils.setInt32LE(buffer2, index, lowBits);
      index += NumberUtils.setInt32LE(buffer2, index, highBits);
      return index;
    }
    function serializeRegExp(buffer2, key, value, index) {
      buffer2[index++] = BSON_DATA_REGEXP;
      const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
      index = index + numberOfWrittenBytes;
      buffer2[index++] = 0;
      if (value.source && value.source.match(regexp) != null) {
        throw new BSONError("value " + value.source + " must not contain null bytes");
      }
      index = index + ByteUtils.encodeUTF8Into(buffer2, value.source, index);
      buffer2[index++] = 0;
      if (value.ignoreCase)
        buffer2[index++] = 105;
      if (value.global)
        buffer2[index++] = 115;
      if (value.multiline)
        buffer2[index++] = 109;
      buffer2[index++] = 0;
      return index;
    }
    function serializeBSONRegExp(buffer2, key, value, index) {
      buffer2[index++] = BSON_DATA_REGEXP;
      const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
      index = index + numberOfWrittenBytes;
      buffer2[index++] = 0;
      if (value.pattern.match(regexp) != null) {
        throw new BSONError("pattern " + value.pattern + " must not contain null bytes");
      }
      index = index + ByteUtils.encodeUTF8Into(buffer2, value.pattern, index);
      buffer2[index++] = 0;
      const sortedOptions = value.options.split("").sort().join("");
      index = index + ByteUtils.encodeUTF8Into(buffer2, sortedOptions, index);
      buffer2[index++] = 0;
      return index;
    }
    function serializeMinMax(buffer2, key, value, index) {
      if (value === null) {
        buffer2[index++] = BSON_DATA_NULL;
      } else if (value[bsonType] === "MinKey") {
        buffer2[index++] = BSON_DATA_MIN_KEY;
      } else {
        buffer2[index++] = BSON_DATA_MAX_KEY;
      }
      const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
      index = index + numberOfWrittenBytes;
      buffer2[index++] = 0;
      return index;
    }
    function serializeObjectId(buffer2, key, value, index) {
      buffer2[index++] = BSON_DATA_OID;
      const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
      index = index + numberOfWrittenBytes;
      buffer2[index++] = 0;
      index += value.serializeInto(buffer2, index);
      return index;
    }
    function serializeBuffer(buffer2, key, value, index) {
      buffer2[index++] = BSON_DATA_BINARY;
      const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
      index = index + numberOfWrittenBytes;
      buffer2[index++] = 0;
      const size = value.length;
      index += NumberUtils.setInt32LE(buffer2, index, size);
      buffer2[index++] = BSON_BINARY_SUBTYPE_DEFAULT;
      if (size <= 16) {
        for (let i2 = 0; i2 < size; i2++)
          buffer2[index + i2] = value[i2];
      } else {
        buffer2.set(value, index);
      }
      index = index + size;
      return index;
    }
    function serializeDecimal128(buffer2, key, value, index) {
      buffer2[index++] = BSON_DATA_DECIMAL128;
      const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
      index = index + numberOfWrittenBytes;
      buffer2[index++] = 0;
      for (let i2 = 0; i2 < 16; i2++)
        buffer2[index + i2] = value.bytes[i2];
      return index + 16;
    }
    function serializeLong(buffer2, key, value, index) {
      buffer2[index++] = value[bsonType] === "Long" ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP;
      const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
      index = index + numberOfWrittenBytes;
      buffer2[index++] = 0;
      const lowBits = value.getLowBits();
      const highBits = value.getHighBits();
      index += NumberUtils.setInt32LE(buffer2, index, lowBits);
      index += NumberUtils.setInt32LE(buffer2, index, highBits);
      return index;
    }
    function serializeInt32(buffer2, key, value, index) {
      value = value.valueOf();
      buffer2[index++] = BSON_DATA_INT;
      const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
      index = index + numberOfWrittenBytes;
      buffer2[index++] = 0;
      index += NumberUtils.setInt32LE(buffer2, index, value);
      return index;
    }
    function serializeDouble(buffer2, key, value, index) {
      buffer2[index++] = BSON_DATA_NUMBER;
      const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
      index = index + numberOfWrittenBytes;
      buffer2[index++] = 0;
      index += NumberUtils.setFloat64LE(buffer2, index, value.value);
      return index;
    }
    function serializeFunction(buffer2, key, value, index) {
      buffer2[index++] = BSON_DATA_CODE;
      const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
      index = index + numberOfWrittenBytes;
      buffer2[index++] = 0;
      const functionString = value.toString();
      const size = ByteUtils.encodeUTF8Into(buffer2, functionString, index + 4) + 1;
      NumberUtils.setInt32LE(buffer2, index, size);
      index = index + 4 + size - 1;
      buffer2[index++] = 0;
      return index;
    }
    function serializeBinary(buffer2, key, value, index) {
      buffer2[index++] = BSON_DATA_BINARY;
      const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
      index = index + numberOfWrittenBytes;
      buffer2[index++] = 0;
      const data = value.buffer;
      let size = value.position;
      if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY)
        size = size + 4;
      index += NumberUtils.setInt32LE(buffer2, index, size);
      buffer2[index++] = value.sub_type;
      if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
        size = size - 4;
        index += NumberUtils.setInt32LE(buffer2, index, size);
      }
      if (value.sub_type === Binary.SUBTYPE_VECTOR) {
        validateBinaryVector(value);
      }
      if (size <= 16) {
        for (let i2 = 0; i2 < size; i2++)
          buffer2[index + i2] = data[i2];
      } else {
        buffer2.set(data, index);
      }
      index = index + value.position;
      return index;
    }
    function serializeSymbol(buffer2, key, value, index) {
      buffer2[index++] = BSON_DATA_SYMBOL;
      const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
      index = index + numberOfWrittenBytes;
      buffer2[index++] = 0;
      const size = ByteUtils.encodeUTF8Into(buffer2, value.value, index + 4) + 1;
      NumberUtils.setInt32LE(buffer2, index, size);
      index = index + 4 + size - 1;
      buffer2[index++] = 0;
      return index;
    }
    function makeFrame(sourceObject, objectSizeIndex, codeSizeIndex, prev, checkKeys, ignoreUndefined) {
      if (Array.isArray(sourceObject)) {
        return {
          sourceObject,
          isArray: true,
          objectSizeIndex,
          codeSizeIndex,
          iterTarget: sourceObject,
          keys: null,
          keyIndex: 0,
          mapIterator: null,
          prev,
          checkKeys,
          ignoreUndefined
        };
      }
      if (sourceObject instanceof Map || isMap(sourceObject)) {
        return {
          sourceObject,
          isArray: false,
          objectSizeIndex,
          codeSizeIndex,
          iterTarget: sourceObject,
          keys: null,
          keyIndex: 0,
          mapIterator: sourceObject.entries(),
          prev,
          checkKeys,
          ignoreUndefined
        };
      }
      let target = sourceObject;
      if (typeof target?.toBSON === "function") {
        target = target.toBSON();
        if (target != null && typeof target !== "object") {
          throw new BSONError("toBSON function did not return an object");
        }
      }
      return {
        sourceObject,
        isArray: false,
        objectSizeIndex,
        codeSizeIndex,
        iterTarget: target,
        keys: Object.keys(target),
        keyIndex: 0,
        mapIterator: null,
        prev,
        checkKeys,
        ignoreUndefined
      };
    }
    function serializeInto(buffer2, object3, checkKeys, startingIndex, serializeFunctions, ignoreUndefined, path) {
      if (path == null) {
        if (object3 == null) {
          buffer2[0] = 5;
          buffer2[1] = 0;
          buffer2[2] = 0;
          buffer2[3] = 0;
          buffer2[4] = 0;
          return 5;
        }
        if (Array.isArray(object3)) {
          throw new BSONError("serialize does not support an array as the root input");
        }
        if (typeof object3 !== "object") {
          throw new BSONError("serialize does not support non-object as the root input");
        } else if ("_bsontype" in object3 && typeof object3._bsontype === "string") {
          throw new BSONError(`BSON types cannot be serialized as a document`);
        } else if (isDate(object3) || isRegExp(object3) || isUint8Array(object3) || isAnyArrayBuffer(object3)) {
          throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`);
        }
        path = /* @__PURE__ */ new Set();
      }
      path.add(object3);
      let currentFrame = makeFrame(object3, startingIndex, null, null, checkKeys, ignoreUndefined);
      let index = startingIndex + 4;
      while (currentFrame !== null) {
        const frame = currentFrame;
        let key;
        let value;
        if (frame.mapIterator !== null) {
          const next = frame.mapIterator.next();
          if (next.done) {
            buffer2[index++] = 0;
            NumberUtils.setInt32LE(buffer2, frame.objectSizeIndex, index - frame.objectSizeIndex);
            if (frame.codeSizeIndex !== null) {
              NumberUtils.setInt32LE(buffer2, frame.codeSizeIndex, index - frame.codeSizeIndex);
            }
            path.delete(frame.sourceObject);
            currentFrame = frame.prev;
            continue;
          }
          key = next.value[0];
          value = next.value[1];
        } else if (frame.keys !== null) {
          if (frame.keyIndex >= frame.keys.length) {
            buffer2[index++] = 0;
            NumberUtils.setInt32LE(buffer2, frame.objectSizeIndex, index - frame.objectSizeIndex);
            if (frame.codeSizeIndex !== null) {
              NumberUtils.setInt32LE(buffer2, frame.codeSizeIndex, index - frame.codeSizeIndex);
            }
            path.delete(frame.sourceObject);
            currentFrame = frame.prev;
            continue;
          }
          key = frame.keys[frame.keyIndex++];
          value = frame.iterTarget[key];
        } else {
          const arr = frame.iterTarget;
          if (frame.keyIndex >= arr.length) {
            buffer2[index++] = 0;
            NumberUtils.setInt32LE(buffer2, frame.objectSizeIndex, index - frame.objectSizeIndex);
            if (frame.codeSizeIndex !== null) {
              NumberUtils.setInt32LE(buffer2, frame.codeSizeIndex, index - frame.codeSizeIndex);
            }
            path.delete(frame.sourceObject);
            currentFrame = frame.prev;
            continue;
          }
          const i2 = frame.keyIndex++;
          key = String(i2);
          value = arr[i2];
        }
        if (typeof value?.toBSON === "function") {
          value = value.toBSON();
        }
        if (!frame.isArray && typeof key === "string" && !(key[0] === "$" && ignoreKeys.has(key))) {
          if (regexp.test(key)) {
            throw new BSONError("key " + key + " must not contain null bytes");
          }
          if (frame.checkKeys) {
            if ("$" === key[0]) {
              throw new BSONError("key " + key + " must not start with '$'");
            } else if (key.includes(".")) {
              throw new BSONError("key " + key + " must not contain '.'");
            }
          }
        }
        const type = typeof value;
        if (value === void 0) {
          if (frame.isArray || frame.ignoreUndefined === false) {
            index = serializeNull(buffer2, key, value, index);
          }
        } else if (value === null) {
          index = serializeNull(buffer2, key, value, index);
        } else if (type === "string") {
          index = serializeString(buffer2, key, value, index);
        } else if (type === "number") {
          index = serializeNumber(buffer2, key, value, index);
        } else if (type === "bigint") {
          index = serializeBigInt(buffer2, key, value, index);
        } else if (type === "boolean") {
          index = serializeBoolean(buffer2, key, value, index);
        } else if (type === "object" && value._bsontype == null) {
          if (value instanceof Date || isDate(value)) {
            index = serializeDate(buffer2, key, value, index);
          } else if (value instanceof Uint8Array || isUint8Array(value)) {
            index = serializeBuffer(buffer2, key, value, index);
          } else if (value instanceof RegExp || isRegExp(value)) {
            index = serializeRegExp(buffer2, key, value, index);
          } else {
            if (path.has(value)) {
              throw new BSONError("Cannot convert circular structure to BSON");
            }
            const nestedIsArray = Array.isArray(value);
            buffer2[index++] = nestedIsArray ? BSON_DATA_ARRAY : BSON_DATA_OBJECT;
            index += ByteUtils.encodeUTF8Into(buffer2, key, index);
            buffer2[index++] = 0;
            const nestedStartIndex = index;
            path.add(value);
            currentFrame = makeFrame(value, nestedStartIndex, null, frame, frame.checkKeys, frame.ignoreUndefined);
            index += 4;
          }
        } else if (type === "object") {
          if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
            throw new BSONVersionError();
          }
          const tag = value[bsonType];
          if (tag === "ObjectId") {
            index = serializeObjectId(buffer2, key, value, index);
          } else if (tag === "Decimal128") {
            index = serializeDecimal128(buffer2, key, value, index);
          } else if (tag === "Long" || tag === "Timestamp") {
            index = serializeLong(buffer2, key, value, index);
          } else if (tag === "Double") {
            index = serializeDouble(buffer2, key, value, index);
          } else if (tag === "Code") {
            const codeValue = value;
            if (codeValue.scope && typeof codeValue.scope === "object") {
              buffer2[index++] = BSON_DATA_CODE_W_SCOPE;
              index += ByteUtils.encodeUTF8Into(buffer2, key, index);
              buffer2[index++] = 0;
              const codeTotalSizeIndex = index;
              index += 4;
              const functionString = codeValue.code;
              const codeSize = ByteUtils.encodeUTF8Into(buffer2, functionString, index + 4) + 1;
              NumberUtils.setInt32LE(buffer2, index, codeSize);
              buffer2[index + 4 + codeSize - 1] = 0;
              index = index + codeSize + 4;
              const scope = codeValue.scope;
              if (path.has(scope)) {
                throw new BSONError("Cannot convert circular structure to BSON");
              }
              path.add(scope);
              currentFrame = makeFrame(scope, index, codeTotalSizeIndex, frame, frame.checkKeys, frame.ignoreUndefined);
              index += 4;
            } else {
              buffer2[index++] = BSON_DATA_CODE;
              index += ByteUtils.encodeUTF8Into(buffer2, key, index);
              buffer2[index++] = 0;
              const functionString = codeValue.code.toString();
              const size = ByteUtils.encodeUTF8Into(buffer2, functionString, index + 4) + 1;
              NumberUtils.setInt32LE(buffer2, index, size);
              index = index + 4 + size - 1;
              buffer2[index++] = 0;
            }
          } else if (tag === "Binary") {
            index = serializeBinary(buffer2, key, value, index);
          } else if (tag === "BSONSymbol") {
            index = serializeSymbol(buffer2, key, value, index);
          } else if (tag === "DBRef") {
            const dbref = value;
            const orderedValues = Object.assign({ $ref: dbref.collection, $id: dbref.oid }, dbref.db != null ? { $db: dbref.db } : null, dbref.fields);
            buffer2[index++] = BSON_DATA_OBJECT;
            index += ByteUtils.encodeUTF8Into(buffer2, key, index);
            buffer2[index++] = 0;
            path.add(orderedValues);
            currentFrame = makeFrame(orderedValues, index, null, frame, false, true);
            index += 4;
          } else if (tag === "BSONRegExp") {
            index = serializeBSONRegExp(buffer2, key, value, index);
          } else if (tag === "Int32") {
            index = serializeInt32(buffer2, key, value, index);
          } else if (tag === "MinKey" || tag === "MaxKey") {
            index = serializeMinMax(buffer2, key, value, index);
          } else if (typeof value._bsontype !== "undefined") {
            throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
          }
        } else if (type === "function" && serializeFunctions) {
          index = serializeFunction(buffer2, key, value, index);
        }
      }
      return index;
    }
    function isBSONType(value) {
      return value != null && typeof value === "object" && "_bsontype" in value && typeof value._bsontype === "string";
    }
    var keysToCodecs = {
      $oid: ObjectId,
      $binary: Binary,
      $uuid: Binary,
      $symbol: BSONSymbol,
      $numberInt: Int32,
      $numberDecimal: Decimal128,
      $numberDouble: Double,
      $numberLong: Long,
      $minKey: MinKey,
      $maxKey: MaxKey,
      $regex: BSONRegExp,
      $regularExpression: BSONRegExp,
      $timestamp: Timestamp
    };
    function deserializeValue(value, options = {}) {
      if (typeof value === "number") {
        const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN;
        const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN;
        if (options.relaxed || options.legacy) {
          return value;
        }
        if (Number.isInteger(value) && !Object.is(value, -0)) {
          if (in32BitRange) {
            return new Int32(value);
          }
          if (in64BitRange) {
            if (options.useBigInt64) {
              return BigInt(value);
            }
            return Long.fromNumber(value);
          }
        }
        return new Double(value);
      }
      if (value == null || typeof value !== "object")
        return value;
      if (value.$undefined)
        return null;
      const keys = Object.keys(value).filter((k) => k.startsWith("$") && value[k] != null);
      for (let i2 = 0; i2 < keys.length; i2++) {
        const c = keysToCodecs[keys[i2]];
        if (c)
          return c.fromExtendedJSON(value, options);
      }
      if (value.$date != null) {
        const d = value.$date;
        const date5 = /* @__PURE__ */ new Date();
        if (options.legacy) {
          if (typeof d === "number")
            date5.setTime(d);
          else if (typeof d === "string")
            date5.setTime(Date.parse(d));
          else if (typeof d === "bigint")
            date5.setTime(Number(d));
          else
            throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
        } else {
          if (typeof d === "string")
            date5.setTime(Date.parse(d));
          else if (Long.isLong(d))
            date5.setTime(d.toNumber());
          else if (typeof d === "number" && options.relaxed)
            date5.setTime(d);
          else if (typeof d === "bigint")
            date5.setTime(Number(d));
          else
            throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
        }
        return date5;
      }
      if (value.$code != null) {
        const copy = Object.assign({}, value);
        if (value.$scope) {
          copy.$scope = deserializeValue(value.$scope);
        }
        return Code.fromExtendedJSON(value);
      }
      if (isDBRefLike(value) || value.$dbPointer) {
        const v = value.$ref ? value : value.$dbPointer;
        if (v instanceof DBRef)
          return v;
        const dollarKeys = Object.keys(v).filter((k) => k.startsWith("$"));
        let valid = true;
        dollarKeys.forEach((k) => {
          if (["$ref", "$id", "$db"].indexOf(k) === -1)
            valid = false;
        });
        if (valid)
          return DBRef.fromExtendedJSON(v);
      }
      return value;
    }
    function serializeArray(array2, options) {
      return array2.map((v, index) => {
        options.seenObjects.push({ propertyName: `index ${index}`, obj: null });
        try {
          return serializeValue(v, options);
        } finally {
          options.seenObjects.pop();
        }
      });
    }
    function getISOString(date5) {
      const isoStr = date5.toISOString();
      return date5.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + "Z";
    }
    function serializeValue(value, options) {
      if (value instanceof Map || isMap(value)) {
        const obj = /* @__PURE__ */ Object.create(null);
        for (const [k, v] of value) {
          if (typeof k !== "string") {
            throw new BSONError("Can only serialize maps with string keys");
          }
          obj[k] = v;
        }
        return serializeValue(obj, options);
      }
      if ((typeof value === "object" || typeof value === "function") && value !== null) {
        const index = options.seenObjects.findIndex((entry) => entry.obj === value);
        if (index !== -1) {
          const props = options.seenObjects.map((entry) => entry.propertyName);
          const leadingPart = props.slice(0, index).map((prop) => `${prop} -> `).join("");
          const alreadySeen = props[index];
          const circularPart = " -> " + props.slice(index + 1, props.length - 1).map((prop) => `${prop} -> `).join("");
          const current = props[props.length - 1];
          const leadingSpace = " ".repeat(leadingPart.length + alreadySeen.length / 2);
          const dashes = "-".repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
          throw new BSONError(`Converting circular structure to EJSON:
    ${leadingPart}${alreadySeen}${circularPart}${current}
    ${leadingSpace}\\${dashes}/`);
        }
        options.seenObjects[options.seenObjects.length - 1].obj = value;
      }
      if (Array.isArray(value))
        return serializeArray(value, options);
      if (value === void 0)
        return options.ignoreUndefined ? void 0 : null;
      if (value instanceof Date || isDate(value)) {
        const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 2534023188e5;
        if (options.legacy) {
          return options.relaxed && inRange ? { $date: value.getTime() } : { $date: getISOString(value) };
        }
        return options.relaxed && inRange ? { $date: getISOString(value) } : { $date: { $numberLong: value.getTime().toString() } };
      }
      if (typeof value === "number" && (!options.relaxed || !isFinite(value))) {
        if (Number.isInteger(value) && !Object.is(value, -0)) {
          if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
            return { $numberInt: value.toString() };
          }
          if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) {
            return { $numberLong: value.toString() };
          }
        }
        return { $numberDouble: Object.is(value, -0) ? "-0.0" : value.toString() };
      }
      if (typeof value === "bigint") {
        if (!options.relaxed) {
          return { $numberLong: BigInt.asIntN(64, value).toString() };
        }
        return Number(BigInt.asIntN(64, value));
      }
      if (value instanceof RegExp || isRegExp(value)) {
        let flags = value.flags;
        if (flags === void 0) {
          const match = value.toString().match(/[gimuy]*$/);
          if (match) {
            flags = match[0];
          }
        }
        const rx = new BSONRegExp(value.source, flags);
        return rx.toExtendedJSON(options);
      }
      if (value != null && typeof value === "object")
        return serializeDocument(value, options);
      return value;
    }
    var BSON_TYPE_MAPPINGS = {
      Binary: (o) => new Binary(o.value(), o.sub_type),
      Code: (o) => new Code(o.code, o.scope),
      DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields),
      Decimal128: (o) => new Decimal128(o.bytes),
      Double: (o) => new Double(o.value),
      Int32: (o) => new Int32(o.value),
      Long: (o) => Long.fromBits(o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_),
      MaxKey: () => new MaxKey(),
      MinKey: () => new MinKey(),
      ObjectId: (o) => new ObjectId(o),
      BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options),
      BSONSymbol: (o) => new BSONSymbol(o.value),
      Timestamp: (o) => Timestamp.fromBits(o.low, o.high)
    };
    function serializeDocument(doc, options) {
      if (doc == null || typeof doc !== "object")
        throw new BSONError("not an object instance");
      const bsontype = doc._bsontype;
      if (typeof bsontype === "undefined") {
        const _doc = {};
        for (const name of Object.keys(doc)) {
          options.seenObjects.push({ propertyName: name, obj: null });
          try {
            const value = serializeValue(doc[name], options);
            if (name === "__proto__") {
              Object.defineProperty(_doc, name, {
                value,
                writable: true,
                enumerable: true,
                configurable: true
              });
            } else {
              _doc[name] = value;
            }
          } finally {
            options.seenObjects.pop();
          }
        }
        return _doc;
      } else if (doc != null && typeof doc === "object" && typeof doc._bsontype === "string" && doc[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
        throw new BSONVersionError();
      } else if (isBSONType(doc)) {
        let outDoc = doc;
        if (typeof outDoc.toExtendedJSON !== "function") {
          const mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
          if (!mapper) {
            throw new BSONError("Unrecognized or invalid _bsontype: " + doc._bsontype);
          }
          outDoc = mapper(outDoc);
        }
        if (bsontype === "Code" && outDoc.scope) {
          outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options));
        } else if (bsontype === "DBRef" && outDoc.oid) {
          outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options));
        }
        return outDoc.toExtendedJSON(options);
      } else {
        throw new BSONError("_bsontype must be a string, but was: " + typeof bsontype);
      }
    }
    function parse3(text, options) {
      const ejsonOptions = {
        useBigInt64: options?.useBigInt64 ?? false,
        relaxed: options?.relaxed ?? true,
        legacy: options?.legacy ?? false
      };
      return JSON.parse(text, (key, value) => {
        if (key.indexOf("\0") !== -1) {
          throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`);
        }
        return deserializeValue(value, ejsonOptions);
      });
    }
    function stringify(value, replacerOrOptions, spaceOrOptions, options) {
      if (spaceOrOptions != null && typeof spaceOrOptions === "object") {
        options = spaceOrOptions;
        spaceOrOptions = void 0;
      }
      if (replacerOrOptions != null && typeof replacerOrOptions === "object" && !Array.isArray(replacerOrOptions)) {
        options = replacerOrOptions;
        replacerOrOptions = void 0;
      }
      const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, {
        seenObjects: [{ propertyName: "(root)", obj: null }]
      });
      const doc = serializeValue(value, serializeOptions);
      return JSON.stringify(doc, replacerOrOptions, spaceOrOptions);
    }
    function EJSONserialize(value, options) {
      options = options || {};
      return JSON.parse(stringify(value, options));
    }
    function EJSONdeserialize(ejson, options) {
      options = options || {};
      return parse3(JSON.stringify(ejson), options);
    }
    var EJSON = /* @__PURE__ */ Object.create(null);
    EJSON.parse = parse3;
    EJSON.stringify = stringify;
    EJSON.serialize = EJSONserialize;
    EJSON.deserialize = EJSONdeserialize;
    Object.freeze(EJSON);
    var BSONElementType = {
      double: 1,
      string: 2,
      object: 3,
      array: 4,
      binData: 5,
      undefined: 6,
      objectId: 7,
      bool: 8,
      date: 9,
      null: 10,
      regex: 11,
      dbPointer: 12,
      javascript: 13,
      symbol: 14,
      javascriptWithScope: 15,
      int: 16,
      timestamp: 17,
      long: 18,
      decimal: 19,
      minKey: 255,
      maxKey: 127
    };
    function getSize(source, offset) {
      try {
        return NumberUtils.getNonnegativeInt32LE(source, offset);
      } catch (cause) {
        throw new BSONOffsetError("BSON size cannot be negative", offset, { cause });
      }
    }
    function findNull(bytes, offset) {
      let nullTerminatorOffset = offset;
      for (; bytes[nullTerminatorOffset] !== 0; nullTerminatorOffset++)
        ;
      if (nullTerminatorOffset === bytes.length - 1) {
        throw new BSONOffsetError("Null terminator not found", offset);
      }
      return nullTerminatorOffset;
    }
    function parseToElements(bytes, startOffset = 0) {
      startOffset ??= 0;
      if (bytes.length < 5) {
        throw new BSONOffsetError(`Input must be at least 5 bytes, got ${bytes.length} bytes`, startOffset);
      }
      const documentSize = getSize(bytes, startOffset);
      if (documentSize > bytes.length - startOffset) {
        throw new BSONOffsetError(`Parsed documentSize (${documentSize} bytes) does not match input length (${bytes.length} bytes)`, startOffset);
      }
      if (bytes[startOffset + documentSize - 1] !== 0) {
        throw new BSONOffsetError("BSON documents must end in 0x00", startOffset + documentSize);
      }
      const elements = [];
      let offset = startOffset + 4;
      while (offset <= documentSize + startOffset) {
        const type = bytes[offset];
        offset += 1;
        if (type === 0) {
          if (offset - startOffset !== documentSize) {
            throw new BSONOffsetError(`Invalid 0x00 type byte`, offset);
          }
          break;
        }
        const nameOffset = offset;
        const nameLength = findNull(bytes, offset) - nameOffset;
        offset += nameLength + 1;
        let length;
        if (type === BSONElementType.double || type === BSONElementType.long || type === BSONElementType.date || type === BSONElementType.timestamp) {
          length = 8;
        } else if (type === BSONElementType.int) {
          length = 4;
        } else if (type === BSONElementType.objectId) {
          length = 12;
        } else if (type === BSONElementType.decimal) {
          length = 16;
        } else if (type === BSONElementType.bool) {
          length = 1;
        } else if (type === BSONElementType.null || type === BSONElementType.undefined || type === BSONElementType.maxKey || type === BSONElementType.minKey) {
          length = 0;
        } else if (type === BSONElementType.regex) {
          length = findNull(bytes, findNull(bytes, offset) + 1) + 1 - offset;
        } else if (type === BSONElementType.object || type === BSONElementType.array || type === BSONElementType.javascriptWithScope) {
          length = getSize(bytes, offset);
        } else if (type === BSONElementType.string || type === BSONElementType.binData || type === BSONElementType.dbPointer || type === BSONElementType.javascript || type === BSONElementType.symbol) {
          length = getSize(bytes, offset) + 4;
          if (type === BSONElementType.binData) {
            length += 1;
          }
          if (type === BSONElementType.dbPointer) {
            length += 12;
          }
        } else {
          throw new BSONOffsetError(`Invalid 0x${type.toString(16).padStart(2, "0")} type byte`, offset);
        }
        if (length > documentSize) {
          throw new BSONOffsetError("value reports length larger than document", offset);
        }
        elements.push([type, nameOffset, nameLength, offset, length]);
        offset += length;
      }
      return elements;
    }
    var onDemand = /* @__PURE__ */ Object.create(null);
    onDemand.parseToElements = parseToElements;
    onDemand.ByteUtils = ByteUtils;
    onDemand.NumberUtils = NumberUtils;
    Object.freeze(onDemand);
    var MAXSIZE = 1024 * 1024 * 17;
    var buffer = ByteUtils.allocate(MAXSIZE);
    function setInternalBufferSize(size) {
      if (buffer.length < size) {
        buffer = ByteUtils.allocate(size);
      }
    }
    function serialize(object3, options = {}) {
      const checkKeys = typeof options.checkKeys === "boolean" ? options.checkKeys : false;
      const serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false;
      const ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : true;
      const minInternalBufferSize = typeof options.minInternalBufferSize === "number" ? options.minInternalBufferSize : MAXSIZE;
      if (buffer.length < minInternalBufferSize) {
        buffer = ByteUtils.allocate(minInternalBufferSize);
      }
      const serializationIndex = serializeInto(buffer, object3, checkKeys, 0, serializeFunctions, ignoreUndefined, null);
      const finishedBuffer = ByteUtils.allocateUnsafe(serializationIndex);
      finishedBuffer.set(buffer.subarray(0, serializationIndex), 0);
      return finishedBuffer;
    }
    function serializeWithBufferAndIndex(object3, finalBuffer, options = {}) {
      const checkKeys = typeof options.checkKeys === "boolean" ? options.checkKeys : false;
      const serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false;
      const ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : true;
      const startIndex = typeof options.index === "number" ? options.index : 0;
      const serializationIndex = serializeInto(buffer, object3, checkKeys, 0, serializeFunctions, ignoreUndefined, null);
      finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex);
      return startIndex + serializationIndex - 1;
    }
    function deserialize(buffer2, options = {}) {
      return internalDeserialize(ByteUtils.toLocalBufferType(buffer2), options);
    }
    function calculateObjectSize(object3, options = {}) {
      options = options || {};
      const serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false;
      const ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : true;
      return internalCalculateObjectSize(object3, serializeFunctions, ignoreUndefined);
    }
    function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
      const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options);
      const bufferData = ByteUtils.toLocalBufferType(data);
      let index = startIndex;
      for (let i2 = 0; i2 < numberOfDocuments; i2++) {
        const size = NumberUtils.getInt32LE(bufferData, index);
        internalOptions.index = index;
        documents[docStartIndex + i2] = internalDeserialize(bufferData, internalOptions);
        index = index + size;
      }
      return index;
    }
    var bson = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      BSONError,
      BSONOffsetError,
      BSONRegExp,
      BSONRuntimeError,
      BSONSymbol,
      BSONType,
      BSONValue,
      BSONVersionError,
      Binary,
      ByteUtils,
      Code,
      DBRef,
      Decimal128,
      Double,
      EJSON,
      Int32,
      Long,
      MaxKey,
      MinKey,
      NumberUtils,
      ObjectId,
      Timestamp,
      UUID,
      bsonType,
      calculateObjectSize,
      deserialize,
      deserializeStream,
      onDemand,
      serialize,
      serializeWithBufferAndIndex,
      setInternalBufferSize
    });
    exports2.BSON = bson;
    exports2.BSONError = BSONError;
    exports2.BSONOffsetError = BSONOffsetError;
    exports2.BSONRegExp = BSONRegExp;
    exports2.BSONRuntimeError = BSONRuntimeError;
    exports2.BSONSymbol = BSONSymbol;
    exports2.BSONType = BSONType;
    exports2.BSONValue = BSONValue;
    exports2.BSONVersionError = BSONVersionError;
    exports2.Binary = Binary;
    exports2.ByteUtils = ByteUtils;
    exports2.Code = Code;
    exports2.DBRef = DBRef;
    exports2.Decimal128 = Decimal128;
    exports2.Double = Double;
    exports2.EJSON = EJSON;
    exports2.Int32 = Int32;
    exports2.Long = Long;
    exports2.MaxKey = MaxKey;
    exports2.MinKey = MinKey;
    exports2.NumberUtils = NumberUtils;
    exports2.ObjectId = ObjectId;
    exports2.Timestamp = Timestamp;
    exports2.UUID = UUID;
    exports2.bsonType = bsonType;
    exports2.calculateObjectSize = calculateObjectSize;
    exports2.deserialize = deserialize;
    exports2.deserializeStream = deserializeStream;
    exports2.onDemand = onDemand;
    exports2.serialize = serialize;
    exports2.serializeWithBufferAndIndex = serializeWithBufferAndIndex;
    exports2.setInternalBufferSize = setInternalBufferSize;
  }
});

// node_modules/mongodb/lib/bson.js
var require_bson2 = __commonJS({
  "node_modules/mongodb/lib/bson.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.setUint32LE = exports2.readUint8 = exports2.readInt32LE = exports2.UUID = exports2.Timestamp = exports2.serialize = exports2.ObjectId = exports2.NumberUtils = exports2.MinKey = exports2.MaxKey = exports2.Long = exports2.Int32 = exports2.EJSON = exports2.Double = exports2.deserialize = exports2.Decimal128 = exports2.DBRef = exports2.Code = exports2.calculateObjectSize = exports2.ByteUtils = exports2.BSONType = exports2.BSONSymbol = exports2.BSONRegExp = exports2.BSONError = exports2.BSON = exports2.Binary = void 0;
    exports2.parseToElementsToArray = parseToElementsToArray;
    exports2.pluckBSONSerializeOptions = pluckBSONSerializeOptions;
    exports2.resolveBSONOptions = resolveBSONOptions;
    exports2.parseUtf8ValidationOption = parseUtf8ValidationOption;
    var bson_1 = require_bson();
    var bson_2 = require_bson();
    Object.defineProperty(exports2, "Binary", { enumerable: true, get: function() {
      return bson_2.Binary;
    } });
    Object.defineProperty(exports2, "BSON", { enumerable: true, get: function() {
      return bson_2.BSON;
    } });
    Object.defineProperty(exports2, "BSONError", { enumerable: true, get: function() {
      return bson_2.BSONError;
    } });
    Object.defineProperty(exports2, "BSONRegExp", { enumerable: true, get: function() {
      return bson_2.BSONRegExp;
    } });
    Object.defineProperty(exports2, "BSONSymbol", { enumerable: true, get: function() {
      return bson_2.BSONSymbol;
    } });
    Object.defineProperty(exports2, "BSONType", { enumerable: true, get: function() {
      return bson_2.BSONType;
    } });
    Object.defineProperty(exports2, "ByteUtils", { enumerable: true, get: function() {
      return bson_2.ByteUtils;
    } });
    Object.defineProperty(exports2, "calculateObjectSize", { enumerable: true, get: function() {
      return bson_2.calculateObjectSize;
    } });
    Object.defineProperty(exports2, "Code", { enumerable: true, get: function() {
      return bson_2.Code;
    } });
    Object.defineProperty(exports2, "DBRef", { enumerable: true, get: function() {
      return bson_2.DBRef;
    } });
    Object.defineProperty(exports2, "Decimal128", { enumerable: true, get: function() {
      return bson_2.Decimal128;
    } });
    Object.defineProperty(exports2, "deserialize", { enumerable: true, get: function() {
      return bson_2.deserialize;
    } });
    Object.defineProperty(exports2, "Double", { enumerable: true, get: function() {
      return bson_2.Double;
    } });
    Object.defineProperty(exports2, "EJSON", { enumerable: true, get: function() {
      return bson_2.EJSON;
    } });
    Object.defineProperty(exports2, "Int32", { enumerable: true, get: function() {
      return bson_2.Int32;
    } });
    Object.defineProperty(exports2, "Long", { enumerable: true, get: function() {
      return bson_2.Long;
    } });
    Object.defineProperty(exports2, "MaxKey", { enumerable: true, get: function() {
      return bson_2.MaxKey;
    } });
    Object.defineProperty(exports2, "MinKey", { enumerable: true, get: function() {
      return bson_2.MinKey;
    } });
    Object.defineProperty(exports2, "NumberUtils", { enumerable: true, get: function() {
      return bson_2.NumberUtils;
    } });
    Object.defineProperty(exports2, "ObjectId", { enumerable: true, get: function() {
      return bson_2.ObjectId;
    } });
    Object.defineProperty(exports2, "serialize", { enumerable: true, get: function() {
      return bson_2.serialize;
    } });
    Object.defineProperty(exports2, "Timestamp", { enumerable: true, get: function() {
      return bson_2.Timestamp;
    } });
    Object.defineProperty(exports2, "UUID", { enumerable: true, get: function() {
      return bson_2.UUID;
    } });
    function parseToElementsToArray(bytes, offset) {
      const res = bson_1.BSON.onDemand.parseToElements(bytes, offset);
      return Array.isArray(res) ? res : [...res];
    }
    var validateBufferInputs = (buffer, offset, length) => {
      if (offset < 0 || offset + length > buffer.length) {
        throw new RangeError(`Attempt to access memory outside buffer bounds: buffer length: ${buffer.length}, offset: ${offset}, length: ${length}`);
      }
    };
    var readInt32LE = (buffer, offset) => {
      validateBufferInputs(buffer, offset, 4);
      return bson_1.NumberUtils.getInt32LE(buffer, offset);
    };
    exports2.readInt32LE = readInt32LE;
    var readUint8 = (buffer, offset) => {
      validateBufferInputs(buffer, offset, 1);
      return buffer[offset];
    };
    exports2.readUint8 = readUint8;
    var setUint32LE = (destination, offset, value) => {
      destination[offset] = value;
      value >>>= 8;
      destination[offset + 1] = value;
      value >>>= 8;
      destination[offset + 2] = value;
      value >>>= 8;
      destination[offset + 3] = value;
      return 4;
    };
    exports2.setUint32LE = setUint32LE;
    function pluckBSONSerializeOptions(options) {
      const { fieldsAsRaw, useBigInt64, promoteValues, promoteBuffers, promoteLongs, serializeFunctions, ignoreUndefined, bsonRegExp, raw, enableUtf8Validation } = options;
      return {
        fieldsAsRaw,
        useBigInt64,
        promoteValues,
        promoteBuffers,
        promoteLongs,
        serializeFunctions,
        ignoreUndefined,
        bsonRegExp,
        raw,
        enableUtf8Validation
      };
    }
    function resolveBSONOptions(options, parent) {
      const parentOptions = parent?.bsonOptions;
      return {
        raw: options?.raw ?? parentOptions?.raw ?? false,
        useBigInt64: options?.useBigInt64 ?? parentOptions?.useBigInt64 ?? false,
        promoteLongs: options?.promoteLongs ?? parentOptions?.promoteLongs ?? true,
        promoteValues: options?.promoteValues ?? parentOptions?.promoteValues ?? true,
        promoteBuffers: options?.promoteBuffers ?? parentOptions?.promoteBuffers ?? false,
        ignoreUndefined: options?.ignoreUndefined ?? parentOptions?.ignoreUndefined ?? false,
        bsonRegExp: options?.bsonRegExp ?? parentOptions?.bsonRegExp ?? false,
        serializeFunctions: options?.serializeFunctions ?? parentOptions?.serializeFunctions ?? false,
        fieldsAsRaw: options?.fieldsAsRaw ?? parentOptions?.fieldsAsRaw ?? {},
        enableUtf8Validation: options?.enableUtf8Validation ?? parentOptions?.enableUtf8Validation ?? true
      };
    }
    function parseUtf8ValidationOption(options) {
      const enableUtf8Validation = options?.enableUtf8Validation;
      if (enableUtf8Validation === false) {
        return { utf8: false };
      }
      return { utf8: { writeErrors: false } };
    }
  }
});

// node_modules/mongodb/lib/cmap/wire_protocol/constants.js
var require_constants = __commonJS({
  "node_modules/mongodb/lib/cmap/wire_protocol/constants.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OP_MSG = exports2.OP_COMPRESSED = exports2.OP_DELETE = exports2.OP_QUERY = exports2.OP_INSERT = exports2.OP_UPDATE = exports2.OP_REPLY = exports2.MIN_SUPPORTED_RAW_DATA_SERVER_VERSION = exports2.MIN_SUPPORTED_RAW_DATA_WIRE_VERSION = exports2.MIN_SUPPORTED_QE_SERVER_VERSION = exports2.MIN_SUPPORTED_QE_WIRE_VERSION = exports2.MAX_SUPPORTED_WIRE_VERSION = exports2.MIN_SUPPORTED_WIRE_VERSION = exports2.MIN_SUPPORTED_SNAPSHOT_READS_SERVER_VERSION = exports2.MIN_SUPPORTED_SNAPSHOT_READS_WIRE_VERSION = exports2.MAX_SUPPORTED_SERVER_VERSION = exports2.MIN_SUPPORTED_SERVER_VERSION = void 0;
    exports2.MIN_SUPPORTED_SERVER_VERSION = "4.2";
    exports2.MAX_SUPPORTED_SERVER_VERSION = "9.0";
    exports2.MIN_SUPPORTED_SNAPSHOT_READS_WIRE_VERSION = 13;
    exports2.MIN_SUPPORTED_SNAPSHOT_READS_SERVER_VERSION = "5.0";
    exports2.MIN_SUPPORTED_WIRE_VERSION = 8;
    exports2.MAX_SUPPORTED_WIRE_VERSION = 29;
    exports2.MIN_SUPPORTED_QE_WIRE_VERSION = 21;
    exports2.MIN_SUPPORTED_QE_SERVER_VERSION = "7.0";
    exports2.MIN_SUPPORTED_RAW_DATA_WIRE_VERSION = 27;
    exports2.MIN_SUPPORTED_RAW_DATA_SERVER_VERSION = "8.2";
    exports2.OP_REPLY = 1;
    exports2.OP_UPDATE = 2001;
    exports2.OP_INSERT = 2002;
    exports2.OP_QUERY = 2004;
    exports2.OP_DELETE = 2006;
    exports2.OP_COMPRESSED = 2012;
    exports2.OP_MSG = 2013;
  }
});

// node_modules/mongodb/lib/error.js
var require_error = __commonJS({
  "node_modules/mongodb/lib/error.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MongoWriteConcernError = exports2.MongoServerSelectionError = exports2.MongoSystemError = exports2.MongoMissingDependencyError = exports2.MongoMissingCredentialsError = exports2.MongoCompatibilityError = exports2.MongoInvalidArgumentError = exports2.MongoParseError = exports2.MongoNetworkTimeoutError = exports2.MongoNetworkError = exports2.MongoClientClosedError = exports2.MongoTopologyClosedError = exports2.MongoCursorExhaustedError = exports2.MongoServerClosedError = exports2.MongoCursorInUseError = exports2.MongoOperationTimeoutError = exports2.MongoUnexpectedServerResponseError = exports2.MongoGridFSChunkError = exports2.MongoGridFSStreamError = exports2.MongoTailableCursorError = exports2.MongoChangeStreamError = exports2.MongoClientBulkWriteExecutionError = exports2.MongoClientBulkWriteCursorError = exports2.MongoClientBulkWriteError = exports2.MongoGCPError = exports2.MongoAzureError = exports2.MongoOIDCError = exports2.MongoAWSError = exports2.MongoKerberosError = exports2.MongoExpiredSessionError = exports2.MongoTransactionError = exports2.MongoNotConnectedError = exports2.MongoDecompressionError = exports2.MongoBatchReExecutionError = exports2.MongoStalePrimaryError = exports2.MongoRuntimeError = exports2.MongoAPIError = exports2.MongoDriverError = exports2.MongoServerError = exports2.MongoError = exports2.MongoErrorLabel = exports2.GET_MORE_RESUMABLE_CODES = exports2.MONGODB_ERROR_CODES = exports2.NODE_IS_RECOVERING_ERROR_MESSAGE = exports2.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = exports2.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = void 0;
    exports2.needsRetryableWriteLabel = needsRetryableWriteLabel;
    exports2.isRetryableWriteError = isRetryableWriteError;
    exports2.isRetryableReadError = isRetryableReadError;
    exports2.isNodeShuttingDownError = isNodeShuttingDownError;
    exports2.isStateChangeError = isStateChangeError;
    exports2.isNetworkTimeoutError = isNetworkTimeoutError;
    exports2.isResumableError = isResumableError;
    exports2.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = new RegExp("not master", "i");
    exports2.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = new RegExp("not master or secondary", "i");
    exports2.NODE_IS_RECOVERING_ERROR_MESSAGE = new RegExp("node is recovering", "i");
    exports2.MONGODB_ERROR_CODES = Object.freeze({
      HostUnreachable: 6,
      HostNotFound: 7,
      AuthenticationFailed: 18,
      NetworkTimeout: 89,
      ShutdownInProgress: 91,
      PrimarySteppedDown: 189,
      ExceededTimeLimit: 262,
      SocketException: 9001,
      NotWritablePrimary: 10107,
      InterruptedAtShutdown: 11600,
      InterruptedDueToReplStateChange: 11602,
      NotPrimaryNoSecondaryOk: 13435,
      NotPrimaryOrSecondary: 13436,
      StaleShardVersion: 63,
      StaleEpoch: 150,
      StaleConfig: 13388,
      RetryChangeStream: 234,
      FailedToSatisfyReadPreference: 133,
      CursorNotFound: 43,
      LegacyNotPrimary: 10058,
      // WriteConcernTimeout is WriteConcernFailed on pre-8.1 servers
      WriteConcernTimeout: 64,
      NamespaceNotFound: 26,
      IllegalOperation: 20,
      MaxTimeMSExpired: 50,
      UnknownReplWriteConcern: 79,
      UnsatisfiableWriteConcern: 100,
      Reauthenticate: 391,
      ReadConcernMajorityNotAvailableYet: 134
    });
    exports2.GET_MORE_RESUMABLE_CODES = /* @__PURE__ */ new Set([
      exports2.MONGODB_ERROR_CODES.HostUnreachable,
      exports2.MONGODB_ERROR_CODES.HostNotFound,
      exports2.MONGODB_ERROR_CODES.NetworkTimeout,
      exports2.MONGODB_ERROR_CODES.ShutdownInProgress,
      exports2.MONGODB_ERROR_CODES.PrimarySteppedDown,
      exports2.MONGODB_ERROR_CODES.ExceededTimeLimit,
      exports2.MONGODB_ERROR_CODES.SocketException,
      exports2.MONGODB_ERROR_CODES.NotWritablePrimary,
      exports2.MONGODB_ERROR_CODES.InterruptedAtShutdown,
      exports2.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange,
      exports2.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk,
      exports2.MONGODB_ERROR_CODES.NotPrimaryOrSecondary,
      exports2.MONGODB_ERROR_CODES.StaleShardVersion,
      exports2.MONGODB_ERROR_CODES.StaleEpoch,
      exports2.MONGODB_ERROR_CODES.StaleConfig,
      exports2.MONGODB_ERROR_CODES.RetryChangeStream,
      exports2.MONGODB_ERROR_CODES.FailedToSatisfyReadPreference,
      exports2.MONGODB_ERROR_CODES.CursorNotFound
    ]);
    exports2.MongoErrorLabel = Object.freeze({
      RetryableWriteError: "RetryableWriteError",
      TransientTransactionError: "TransientTransactionError",
      UnknownTransactionCommitResult: "UnknownTransactionCommitResult",
      ResumableChangeStreamError: "ResumableChangeStreamError",
      HandshakeError: "HandshakeError",
      ResetPool: "ResetPool",
      PoolRequestedRetry: "PoolRequestedRetry",
      InterruptInUseConnections: "InterruptInUseConnections",
      NoWritesPerformed: "NoWritesPerformed",
      RetryableError: "RetryableError",
      SystemOverloadedError: "SystemOverloadedError"
    });
    function isAggregateError(e2) {
      return e2 != null && typeof e2 === "object" && "errors" in e2 && Array.isArray(e2.errors);
    }
    var MongoError = class extends Error {
      get errorLabels() {
        return Array.from(this.errorLabelSet);
      }
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message, options) {
        super(message, options);
        this.errorLabelSet = /* @__PURE__ */ new Set();
      }
      /** @internal */
      static buildErrorMessage(e2) {
        if (typeof e2 === "string") {
          return e2;
        }
        if (isAggregateError(e2) && e2.message.length === 0) {
          return e2.errors.length === 0 ? "AggregateError has an empty errors array. Please check the `cause` property for more information." : e2.errors.map(({ message }) => message).join(", ");
        }
        return e2 != null && typeof e2 === "object" && "message" in e2 && typeof e2.message === "string" ? e2.message : "empty error message";
      }
      get name() {
        return "MongoError";
      }
      /** Legacy name for server error responses */
      get errmsg() {
        return this.message;
      }
      /**
       * Checks the error to see if it has an error label
       *
       * @param label - The error label to check for
       * @returns returns true if the error has the provided error label
       */
      hasErrorLabel(label) {
        return this.errorLabelSet.has(label);
      }
      addErrorLabel(label) {
        this.errorLabelSet.add(label);
      }
    };
    exports2.MongoError = MongoError;
    var MongoServerError = class extends MongoError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message) {
        super(message.message || message.errmsg || message.$err || "n/a");
        if (message.errorLabels) {
          for (const label of message.errorLabels)
            this.addErrorLabel(label);
        }
        this.errorResponse = message;
        for (const name in message) {
          if (name !== "errorLabels" && name !== "errmsg" && name !== "message" && name !== "errorResponse") {
            this[name] = message[name];
          }
        }
      }
      get name() {
        return "MongoServerError";
      }
    };
    exports2.MongoServerError = MongoServerError;
    var MongoDriverError = class extends MongoError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message, options) {
        super(message, options);
      }
      get name() {
        return "MongoDriverError";
      }
    };
    exports2.MongoDriverError = MongoDriverError;
    var MongoAPIError = class extends MongoDriverError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message, options) {
        super(message, options);
      }
      get name() {
        return "MongoAPIError";
      }
    };
    exports2.MongoAPIError = MongoAPIError;
    var MongoRuntimeError = class extends MongoDriverError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message, options) {
        super(message, options);
      }
      get name() {
        return "MongoRuntimeError";
      }
    };
    exports2.MongoRuntimeError = MongoRuntimeError;
    var MongoStalePrimaryError = class extends MongoRuntimeError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message, options) {
        super(message, options);
      }
      get name() {
        return "MongoStalePrimaryError";
      }
    };
    exports2.MongoStalePrimaryError = MongoStalePrimaryError;
    var MongoBatchReExecutionError = class extends MongoAPIError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message = "This batch has already been executed, create new batch to execute") {
        super(message);
      }
      get name() {
        return "MongoBatchReExecutionError";
      }
    };
    exports2.MongoBatchReExecutionError = MongoBatchReExecutionError;
    var MongoDecompressionError = class extends MongoRuntimeError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message) {
        super(message);
      }
      get name() {
        return "MongoDecompressionError";
      }
    };
    exports2.MongoDecompressionError = MongoDecompressionError;
    var MongoNotConnectedError = class extends MongoAPIError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message) {
        super(message);
      }
      get name() {
        return "MongoNotConnectedError";
      }
    };
    exports2.MongoNotConnectedError = MongoNotConnectedError;
    var MongoTransactionError = class extends MongoAPIError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message) {
        super(message);
      }
      get name() {
        return "MongoTransactionError";
      }
    };
    exports2.MongoTransactionError = MongoTransactionError;
    var MongoExpiredSessionError = class extends MongoAPIError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message = "Cannot use a session that has ended") {
        super(message);
      }
      get name() {
        return "MongoExpiredSessionError";
      }
    };
    exports2.MongoExpiredSessionError = MongoExpiredSessionError;
    var MongoKerberosError = class extends MongoRuntimeError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message) {
        super(message);
      }
      get name() {
        return "MongoKerberosError";
      }
    };
    exports2.MongoKerberosError = MongoKerberosError;
    var MongoAWSError = class extends MongoRuntimeError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message, options) {
        super(message, options);
      }
      get name() {
        return "MongoAWSError";
      }
    };
    exports2.MongoAWSError = MongoAWSError;
    var MongoOIDCError = class extends MongoRuntimeError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message) {
        super(message);
      }
      get name() {
        return "MongoOIDCError";
      }
    };
    exports2.MongoOIDCError = MongoOIDCError;
    var MongoAzureError = class extends MongoOIDCError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message) {
        super(message);
      }
      get name() {
        return "MongoAzureError";
      }
    };
    exports2.MongoAzureError = MongoAzureError;
    var MongoGCPError = class extends MongoOIDCError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message) {
        super(message);
      }
      get name() {
        return "MongoGCPError";
      }
    };
    exports2.MongoGCPError = MongoGCPError;
    var MongoClientBulkWriteError = class extends MongoServerError {
      /**
       * Initialize the client bulk write error.
       * @param message - The error message.
       */
      constructor(message) {
        super(message);
        this.writeConcernErrors = [];
        this.writeErrors = /* @__PURE__ */ new Map();
      }
      get name() {
        return "MongoClientBulkWriteError";
      }
    };
    exports2.MongoClientBulkWriteError = MongoClientBulkWriteError;
    var MongoClientBulkWriteCursorError = class extends MongoRuntimeError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message) {
        super(message);
      }
      get name() {
        return "MongoClientBulkWriteCursorError";
      }
    };
    exports2.MongoClientBulkWriteCursorError = MongoClientBulkWriteCursorError;
    var MongoClientBulkWriteExecutionError = class extends MongoRuntimeError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message) {
        super(message);
      }
      get name() {
        return "MongoClientBulkWriteExecutionError";
      }
    };
    exports2.MongoClientBulkWriteExecutionError = MongoClientBulkWriteExecutionError;
    var MongoChangeStreamError = class extends MongoRuntimeError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message) {
        super(message);
      }
      get name() {
        return "MongoChangeStreamError";
      }
    };
    exports2.MongoChangeStreamError = MongoChangeStreamError;
    var MongoTailableCursorError = class extends MongoAPIError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message = "Tailable cursor does not support this operation") {
        super(message);
      }
      get name() {
        return "MongoTailableCursorError";
      }
    };
    exports2.MongoTailableCursorError = MongoTailableCursorError;
    var MongoGridFSStreamError = class extends MongoRuntimeError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message) {
        super(message);
      }
      get name() {
        return "MongoGridFSStreamError";
      }
    };
    exports2.MongoGridFSStreamError = MongoGridFSStreamError;
    var MongoGridFSChunkError = class extends MongoRuntimeError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message) {
        super(message);
      }
      get name() {
        return "MongoGridFSChunkError";
      }
    };
    exports2.MongoGridFSChunkError = MongoGridFSChunkError;
    var MongoUnexpectedServerResponseError = class extends MongoRuntimeError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message, options) {
        super(message, options);
      }
      get name() {
        return "MongoUnexpectedServerResponseError";
      }
    };
    exports2.MongoUnexpectedServerResponseError = MongoUnexpectedServerResponseError;
    var MongoOperationTimeoutError = class extends MongoDriverError {
      get name() {
        return "MongoOperationTimeoutError";
      }
    };
    exports2.MongoOperationTimeoutError = MongoOperationTimeoutError;
    var MongoCursorInUseError = class extends MongoAPIError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message = "Cursor is already initialized") {
        super(message);
      }
      get name() {
        return "MongoCursorInUseError";
      }
    };
    exports2.MongoCursorInUseError = MongoCursorInUseError;
    var MongoServerClosedError = class extends MongoAPIError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message = "Server is closed") {
        super(message);
      }
      get name() {
        return "MongoServerClosedError";
      }
    };
    exports2.MongoServerClosedError = MongoServerClosedError;
    var MongoCursorExhaustedError = class extends MongoAPIError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message) {
        super(message || "Cursor is exhausted");
      }
      get name() {
        return "MongoCursorExhaustedError";
      }
    };
    exports2.MongoCursorExhaustedError = MongoCursorExhaustedError;
    var MongoTopologyClosedError = class extends MongoAPIError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message = "Topology is closed") {
        super(message);
      }
      get name() {
        return "MongoTopologyClosedError";
      }
    };
    exports2.MongoTopologyClosedError = MongoTopologyClosedError;
    var MongoClientClosedError = class extends MongoAPIError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor() {
        super("Operation interrupted because client was closed");
      }
      get name() {
        return "MongoClientClosedError";
      }
    };
    exports2.MongoClientClosedError = MongoClientClosedError;
    var MongoNetworkError = class extends MongoError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message, options) {
        super(message, { cause: options?.cause });
        this.beforeHandshake = !!options?.beforeHandshake;
      }
      get name() {
        return "MongoNetworkError";
      }
    };
    exports2.MongoNetworkError = MongoNetworkError;
    var MongoNetworkTimeoutError = class extends MongoNetworkError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message, options) {
        super(message, options);
      }
      get name() {
        return "MongoNetworkTimeoutError";
      }
    };
    exports2.MongoNetworkTimeoutError = MongoNetworkTimeoutError;
    var MongoParseError = class extends MongoDriverError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message) {
        super(message);
      }
      get name() {
        return "MongoParseError";
      }
    };
    exports2.MongoParseError = MongoParseError;
    var MongoInvalidArgumentError = class extends MongoAPIError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message, options) {
        super(message, options);
      }
      get name() {
        return "MongoInvalidArgumentError";
      }
    };
    exports2.MongoInvalidArgumentError = MongoInvalidArgumentError;
    var MongoCompatibilityError = class extends MongoAPIError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message) {
        super(message);
      }
      get name() {
        return "MongoCompatibilityError";
      }
    };
    exports2.MongoCompatibilityError = MongoCompatibilityError;
    var MongoMissingCredentialsError = class extends MongoAPIError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message) {
        super(message);
      }
      get name() {
        return "MongoMissingCredentialsError";
      }
    };
    exports2.MongoMissingCredentialsError = MongoMissingCredentialsError;
    var MongoMissingDependencyError = class extends MongoAPIError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message, options) {
        super(message, options);
        this.dependencyName = options.dependencyName;
      }
      get name() {
        return "MongoMissingDependencyError";
      }
    };
    exports2.MongoMissingDependencyError = MongoMissingDependencyError;
    var MongoSystemError = class extends MongoError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message, reason) {
        if (reason && reason.error) {
          super(MongoError.buildErrorMessage(reason.error.message || reason.error), {
            cause: reason.error
          });
        } else {
          super(message);
        }
        if (reason) {
          this.reason = reason;
        }
        this.code = reason.error?.code;
      }
      get name() {
        return "MongoSystemError";
      }
    };
    exports2.MongoSystemError = MongoSystemError;
    var MongoServerSelectionError = class extends MongoSystemError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message, reason) {
        super(message, reason);
      }
      get name() {
        return "MongoServerSelectionError";
      }
    };
    exports2.MongoServerSelectionError = MongoServerSelectionError;
    var MongoWriteConcernError = class extends MongoServerError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(result) {
        super({ ...result.writeConcernError, ...result });
        this.errInfo = result.writeConcernError.errInfo;
        this.result = result;
      }
      get name() {
        return "MongoWriteConcernError";
      }
    };
    exports2.MongoWriteConcernError = MongoWriteConcernError;
    var RETRYABLE_READ_ERROR_CODES = /* @__PURE__ */ new Set([
      exports2.MONGODB_ERROR_CODES.HostUnreachable,
      exports2.MONGODB_ERROR_CODES.HostNotFound,
      exports2.MONGODB_ERROR_CODES.NetworkTimeout,
      exports2.MONGODB_ERROR_CODES.ShutdownInProgress,
      exports2.MONGODB_ERROR_CODES.PrimarySteppedDown,
      exports2.MONGODB_ERROR_CODES.SocketException,
      exports2.MONGODB_ERROR_CODES.NotWritablePrimary,
      exports2.MONGODB_ERROR_CODES.InterruptedAtShutdown,
      exports2.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange,
      exports2.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk,
      exports2.MONGODB_ERROR_CODES.NotPrimaryOrSecondary,
      exports2.MONGODB_ERROR_CODES.ExceededTimeLimit,
      exports2.MONGODB_ERROR_CODES.ReadConcernMajorityNotAvailableYet
    ]);
    var RETRYABLE_WRITE_ERROR_CODES = RETRYABLE_READ_ERROR_CODES;
    function needsRetryableWriteLabel(error51, maxWireVersion, serverType) {
      if (error51 instanceof MongoNetworkError) {
        return true;
      }
      if (error51 instanceof MongoError) {
        if ((maxWireVersion >= 9 || isRetryableWriteError(error51)) && !error51.hasErrorLabel(exports2.MongoErrorLabel.HandshakeError)) {
          return false;
        }
      }
      if (error51 instanceof MongoWriteConcernError) {
        if (serverType === "Mongos" && maxWireVersion < 9) {
          return RETRYABLE_WRITE_ERROR_CODES.has(error51.result.code ?? 0);
        }
        const code = error51.result.writeConcernError.code ?? Number(error51.code);
        return RETRYABLE_WRITE_ERROR_CODES.has(Number.isNaN(code) ? 0 : code);
      }
      if (error51 instanceof MongoError) {
        return RETRYABLE_WRITE_ERROR_CODES.has(Number(error51.code));
      }
      const isNotWritablePrimaryError2 = exports2.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(error51.message);
      if (isNotWritablePrimaryError2) {
        return true;
      }
      const isNodeIsRecoveringError = exports2.NODE_IS_RECOVERING_ERROR_MESSAGE.test(error51.message);
      if (isNodeIsRecoveringError) {
        return true;
      }
      return false;
    }
    function isRetryableWriteError(error51) {
      return error51.hasErrorLabel(exports2.MongoErrorLabel.RetryableWriteError) || error51.hasErrorLabel(exports2.MongoErrorLabel.PoolRequestedRetry);
    }
    function isRetryableReadError(error51) {
      const hasRetryableErrorCode = typeof error51.code === "number" ? RETRYABLE_READ_ERROR_CODES.has(error51.code) : false;
      if (hasRetryableErrorCode) {
        return true;
      }
      if (error51 instanceof MongoNetworkError) {
        return true;
      }
      const isNotWritablePrimaryError2 = exports2.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(error51.message);
      if (isNotWritablePrimaryError2) {
        return true;
      }
      const isNodeIsRecoveringError = exports2.NODE_IS_RECOVERING_ERROR_MESSAGE.test(error51.message);
      if (isNodeIsRecoveringError) {
        return true;
      }
      return false;
    }
    var SDAM_RECOVERING_CODES = /* @__PURE__ */ new Set([
      exports2.MONGODB_ERROR_CODES.ShutdownInProgress,
      exports2.MONGODB_ERROR_CODES.PrimarySteppedDown,
      exports2.MONGODB_ERROR_CODES.InterruptedAtShutdown,
      exports2.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange,
      exports2.MONGODB_ERROR_CODES.NotPrimaryOrSecondary
    ]);
    var SDAM_NOT_PRIMARY_CODES = /* @__PURE__ */ new Set([
      exports2.MONGODB_ERROR_CODES.NotWritablePrimary,
      exports2.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk,
      exports2.MONGODB_ERROR_CODES.LegacyNotPrimary
    ]);
    var SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = /* @__PURE__ */ new Set([
      exports2.MONGODB_ERROR_CODES.InterruptedAtShutdown,
      exports2.MONGODB_ERROR_CODES.ShutdownInProgress
    ]);
    function isRecoveringError(err) {
      if (typeof err.code === "number") {
        return SDAM_RECOVERING_CODES.has(err.code);
      }
      return exports2.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE.test(err.message) || exports2.NODE_IS_RECOVERING_ERROR_MESSAGE.test(err.message);
    }
    function isNotWritablePrimaryError(err) {
      if (typeof err.code === "number") {
        return SDAM_NOT_PRIMARY_CODES.has(err.code);
      }
      if (isRecoveringError(err)) {
        return false;
      }
      return exports2.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(err.message);
    }
    function isNodeShuttingDownError(err) {
      return !!(typeof err.code === "number" && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code));
    }
    function isStateChangeError(error51) {
      return isRecoveringError(error51) || isNotWritablePrimaryError(error51);
    }
    function isNetworkTimeoutError(err) {
      return !!(err instanceof MongoNetworkError && err.message.match(/timed out/));
    }
    function isResumableError(error51, wireVersion) {
      if (error51 == null || !(error51 instanceof MongoError)) {
        return false;
      }
      if (error51 instanceof MongoNetworkError) {
        return true;
      }
      if (error51 instanceof MongoServerSelectionError) {
        return true;
      }
      if (wireVersion != null && wireVersion >= 9) {
        if (error51.code === exports2.MONGODB_ERROR_CODES.CursorNotFound) {
          return true;
        }
        return error51.hasErrorLabel(exports2.MongoErrorLabel.ResumableChangeStreamError);
      }
      if (typeof error51.code === "number") {
        return exports2.GET_MORE_RESUMABLE_CODES.has(error51.code);
      }
      return false;
    }
  }
});

// node_modules/mongodb/lib/read_preference.js
var require_read_preference = __commonJS({
  "node_modules/mongodb/lib/read_preference.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ReadPreference = exports2.ReadPreferenceMode = void 0;
    var error_1 = require_error();
    exports2.ReadPreferenceMode = Object.freeze({
      primary: "primary",
      primaryPreferred: "primaryPreferred",
      secondary: "secondary",
      secondaryPreferred: "secondaryPreferred",
      nearest: "nearest"
    });
    var ReadPreference = class _ReadPreference {
      static {
        this.PRIMARY = exports2.ReadPreferenceMode.primary;
      }
      static {
        this.PRIMARY_PREFERRED = exports2.ReadPreferenceMode.primaryPreferred;
      }
      static {
        this.SECONDARY = exports2.ReadPreferenceMode.secondary;
      }
      static {
        this.SECONDARY_PREFERRED = exports2.ReadPreferenceMode.secondaryPreferred;
      }
      static {
        this.NEAREST = exports2.ReadPreferenceMode.nearest;
      }
      static {
        this.primary = new _ReadPreference(exports2.ReadPreferenceMode.primary);
      }
      static {
        this.primaryPreferred = new _ReadPreference(exports2.ReadPreferenceMode.primaryPreferred);
      }
      static {
        this.secondary = new _ReadPreference(exports2.ReadPreferenceMode.secondary);
      }
      static {
        this.secondaryPreferred = new _ReadPreference(exports2.ReadPreferenceMode.secondaryPreferred);
      }
      static {
        this.nearest = new _ReadPreference(exports2.ReadPreferenceMode.nearest);
      }
      /**
       * @param mode - A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest)
       * @param tags - A tag set used to target reads to members with the specified tag(s). tagSet is not available if using read preference mode primary.
       * @param options - Additional read preference options
       */
      constructor(mode, tags, options) {
        if (!_ReadPreference.isValid(mode)) {
          throw new error_1.MongoInvalidArgumentError(`Invalid read preference mode ${JSON.stringify(mode)}`);
        }
        if (options == null && typeof tags === "object" && !Array.isArray(tags)) {
          options = tags;
          tags = void 0;
        } else if (tags && !Array.isArray(tags)) {
          throw new error_1.MongoInvalidArgumentError("ReadPreference tags must be an array");
        }
        this.mode = mode;
        this.tags = tags;
        this.hedge = options?.hedge;
        this.maxStalenessSeconds = void 0;
        options = options ?? {};
        if (options.maxStalenessSeconds != null) {
          if (options.maxStalenessSeconds <= 0) {
            throw new error_1.MongoInvalidArgumentError("maxStalenessSeconds must be a positive integer");
          }
          this.maxStalenessSeconds = options.maxStalenessSeconds;
        }
        if (this.mode === _ReadPreference.PRIMARY) {
          if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) {
            throw new error_1.MongoInvalidArgumentError("Primary read preference cannot be combined with tags");
          }
          if (this.maxStalenessSeconds) {
            throw new error_1.MongoInvalidArgumentError("Primary read preference cannot be combined with maxStalenessSeconds");
          }
          if (this.hedge) {
            throw new error_1.MongoInvalidArgumentError("Primary read preference cannot be combined with hedge");
          }
        }
      }
      // Support the deprecated `preference` property introduced in the porcelain layer
      get preference() {
        return this.mode;
      }
      static fromString(mode) {
        return new _ReadPreference(mode);
      }
      /**
       * Construct a ReadPreference given an options object.
       *
       * @param options - The options object from which to extract the read preference.
       */
      static fromOptions(options) {
        if (!options)
          return;
        const readPreference = options.readPreference ?? options.session?.transaction.options.readPreference;
        const readPreferenceTags = options.readPreferenceTags;
        if (readPreference == null) {
          return;
        }
        if (typeof readPreference === "string") {
          return new _ReadPreference(readPreference, readPreferenceTags, {
            maxStalenessSeconds: options.maxStalenessSeconds,
            hedge: options.hedge
          });
        } else if (!(readPreference instanceof _ReadPreference) && typeof readPreference === "object") {
          const mode = readPreference.mode || readPreference.preference;
          if (mode && typeof mode === "string") {
            return new _ReadPreference(mode, readPreference.tags ?? readPreferenceTags, {
              maxStalenessSeconds: readPreference.maxStalenessSeconds,
              hedge: options.hedge
            });
          }
        }
        if (readPreferenceTags) {
          readPreference.tags = readPreferenceTags;
        }
        return readPreference;
      }
      /**
       * Replaces options.readPreference with a ReadPreference instance
       */
      static translate(options) {
        if (options.readPreference == null)
          return options;
        const r2 = options.readPreference;
        if (typeof r2 === "string") {
          options.readPreference = new _ReadPreference(r2);
        } else if (r2 && !(r2 instanceof _ReadPreference) && typeof r2 === "object") {
          const mode = r2.mode || r2.preference;
          if (mode && typeof mode === "string") {
            options.readPreference = new _ReadPreference(mode, r2.tags, {
              maxStalenessSeconds: r2.maxStalenessSeconds
            });
          }
        } else if (!(r2 instanceof _ReadPreference)) {
          throw new error_1.MongoInvalidArgumentError(`Invalid read preference: ${r2}`);
        }
        return options;
      }
      /**
       * Validate if a mode is legal
       *
       * @param mode - The string representing the read preference mode.
       */
      static isValid(mode) {
        const VALID_MODES = /* @__PURE__ */ new Set([
          _ReadPreference.PRIMARY,
          _ReadPreference.PRIMARY_PREFERRED,
          _ReadPreference.SECONDARY,
          _ReadPreference.SECONDARY_PREFERRED,
          _ReadPreference.NEAREST,
          null
        ]);
        return VALID_MODES.has(mode);
      }
      /**
       * Validate if a mode is legal
       *
       * @param mode - The string representing the read preference mode.
       */
      isValid(mode) {
        return _ReadPreference.isValid(typeof mode === "string" ? mode : this.mode);
      }
      /**
       * Indicates that this readPreference needs the "SecondaryOk" bit when sent over the wire
       * @see https://www.mongodb.com/docs/manual/reference/mongodb-wire-protocol/#op-query
       */
      secondaryOk() {
        const NEEDS_SECONDARYOK = /* @__PURE__ */ new Set([
          _ReadPreference.PRIMARY_PREFERRED,
          _ReadPreference.SECONDARY,
          _ReadPreference.SECONDARY_PREFERRED,
          _ReadPreference.NEAREST
        ]);
        return NEEDS_SECONDARYOK.has(this.mode);
      }
      /**
       * Check if the two ReadPreferences are equivalent
       *
       * @param readPreference - The read preference with which to check equality
       */
      equals(readPreference) {
        return readPreference.mode === this.mode;
      }
      /** Return JSON representation */
      toJSON() {
        const readPreference = { mode: this.mode };
        if (Array.isArray(this.tags))
          readPreference.tags = this.tags;
        if (this.maxStalenessSeconds)
          readPreference.maxStalenessSeconds = this.maxStalenessSeconds;
        if (this.hedge)
          readPreference.hedge = this.hedge;
        return readPreference;
      }
    };
    exports2.ReadPreference = ReadPreference;
  }
});

// node_modules/mongodb/lib/sdam/common.js
var require_common = __commonJS({
  "node_modules/mongodb/lib/sdam/common.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ServerType = exports2.TopologyType = exports2.STATE_CONNECTED = exports2.STATE_CONNECTING = exports2.STATE_CLOSED = exports2.STATE_CLOSING = void 0;
    exports2._advanceClusterTime = _advanceClusterTime;
    exports2.STATE_CLOSING = "closing";
    exports2.STATE_CLOSED = "closed";
    exports2.STATE_CONNECTING = "connecting";
    exports2.STATE_CONNECTED = "connected";
    exports2.TopologyType = Object.freeze({
      Single: "Single",
      ReplicaSetNoPrimary: "ReplicaSetNoPrimary",
      ReplicaSetWithPrimary: "ReplicaSetWithPrimary",
      Sharded: "Sharded",
      Unknown: "Unknown",
      LoadBalanced: "LoadBalanced"
    });
    exports2.ServerType = Object.freeze({
      Standalone: "Standalone",
      Mongos: "Mongos",
      PossiblePrimary: "PossiblePrimary",
      RSPrimary: "RSPrimary",
      RSSecondary: "RSSecondary",
      RSArbiter: "RSArbiter",
      RSOther: "RSOther",
      RSGhost: "RSGhost",
      Unknown: "Unknown",
      LoadBalancer: "LoadBalancer"
    });
    function _advanceClusterTime(entity, $clusterTime) {
      if (entity.clusterTime == null) {
        entity.clusterTime = $clusterTime;
      } else {
        if ($clusterTime.clusterTime.greaterThan(entity.clusterTime.clusterTime)) {
          entity.clusterTime = $clusterTime;
        }
      }
    }
  }
});

// node_modules/mongodb/lib/sdam/server_selection.js
var require_server_selection = __commonJS({
  "node_modules/mongodb/lib/sdam/server_selection.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DeprioritizedServers = exports2.MIN_SECONDARY_WRITE_WIRE_VERSION = void 0;
    exports2.writableServerSelector = writableServerSelector;
    exports2.sameServerSelector = sameServerSelector;
    exports2.secondaryWritableServerSelector = secondaryWritableServerSelector;
    exports2.readPreferenceServerSelector = readPreferenceServerSelector;
    var error_1 = require_error();
    var read_preference_1 = require_read_preference();
    var common_1 = require_common();
    var IDLE_WRITE_PERIOD = 1e4;
    var SMALLEST_MAX_STALENESS_SECONDS = 90;
    exports2.MIN_SECONDARY_WRITE_WIRE_VERSION = 13;
    var DeprioritizedServers = class {
      constructor(descriptions) {
        this.deprioritized = /* @__PURE__ */ new Set();
        for (const description of descriptions ?? []) {
          this.add(description);
        }
      }
      add({ address }) {
        this.deprioritized.add(address);
      }
      has({ address }) {
        return this.deprioritized.has(address);
      }
    };
    exports2.DeprioritizedServers = DeprioritizedServers;
    function filterDeprioritized(candidates, deprioritized) {
      const filtered = candidates.filter((candidate) => !deprioritized.has(candidate));
      return filtered.length ? filtered : candidates;
    }
    function writableServerSelector() {
      return function writableServer(topologyDescription, servers, deprioritized) {
        const eligibleServers = filterDeprioritized(servers.filter(({ isWritable }) => isWritable), deprioritized);
        return latencyWindowReducer(topologyDescription, eligibleServers);
      };
    }
    function sameServerSelector(description) {
      return function sameServerSelector2(_topologyDescription, servers, _deprioritized) {
        if (!description)
          return [];
        return servers.filter((sd) => {
          return sd.address === description.address && sd.type !== common_1.ServerType.Unknown;
        });
      };
    }
    function secondaryWritableServerSelector(wireVersion, readPreference) {
      if (!readPreference || !wireVersion || wireVersion && wireVersion < exports2.MIN_SECONDARY_WRITE_WIRE_VERSION) {
        return readPreferenceServerSelector(read_preference_1.ReadPreference.primary);
      }
      return readPreferenceServerSelector(readPreference);
    }
    function maxStalenessReducer(readPreference, topologyDescription, servers) {
      if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) {
        return servers;
      }
      const maxStaleness = readPreference.maxStalenessSeconds;
      const maxStalenessVariance = (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1e3;
      if (maxStaleness < maxStalenessVariance) {
        throw new error_1.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${maxStalenessVariance} seconds`);
      }
      if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) {
        throw new error_1.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds`);
      }
      if (topologyDescription.type === common_1.TopologyType.ReplicaSetWithPrimary) {
        const primary = Array.from(topologyDescription.servers.values()).filter(primaryFilter)[0];
        return servers.filter((server) => {
          const stalenessMS = server.lastUpdateTime - server.lastWriteDate - (primary.lastUpdateTime - primary.lastWriteDate) + topologyDescription.heartbeatFrequencyMS;
          const staleness = stalenessMS / 1e3;
          const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0;
          return staleness <= maxStalenessSeconds;
        });
      }
      if (topologyDescription.type === common_1.TopologyType.ReplicaSetNoPrimary) {
        if (servers.length === 0) {
          return servers;
        }
        const sMax = servers.reduce((max, s2) => s2.lastWriteDate > max.lastWriteDate ? s2 : max);
        return servers.filter((server) => {
          const stalenessMS = sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS;
          const staleness = stalenessMS / 1e3;
          const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0;
          return staleness <= maxStalenessSeconds;
        });
      }
      return servers;
    }
    function tagSetMatch(tagSet, serverTags) {
      return Object.entries(tagSet).every(([key, value]) => serverTags[key] != null && serverTags[key] === value);
    }
    function tagSetReducer({ tags }, servers) {
      if (tags == null || tags.length === 0) {
        return servers;
      }
      for (const tagSet of tags) {
        const serversMatchingTagset = servers.filter((s2) => tagSetMatch(tagSet, s2.tags));
        if (serversMatchingTagset.length) {
          return serversMatchingTagset;
        }
      }
      return [];
    }
    function latencyWindowReducer(topologyDescription, servers) {
      const low = servers.reduce((min, server) => Math.min(server.roundTripTime, min), Infinity);
      const high = low + topologyDescription.localThresholdMS;
      return servers.filter((server) => server.roundTripTime <= high && server.roundTripTime >= low);
    }
    function primaryFilter(server) {
      return server.type === common_1.ServerType.RSPrimary;
    }
    function secondaryFilter(server) {
      return server.type === common_1.ServerType.RSSecondary;
    }
    function nearestFilter(server) {
      return server.type === common_1.ServerType.RSSecondary || server.type === common_1.ServerType.RSPrimary;
    }
    function knownFilter(server) {
      return server.type !== common_1.ServerType.Unknown;
    }
    function loadBalancerFilter(server) {
      return server.type === common_1.ServerType.LoadBalancer;
    }
    function isDeprioritizedFactory(deprioritized) {
      return (server) => (
        // if any deprioritized servers equal the server, here we are.
        !deprioritized.has(server)
      );
    }
    function secondarySelector(readPreference, topologyDescription, servers, deprioritized) {
      const mode = readPreference.mode;
      switch (mode) {
        case "primary":
          return servers.filter(primaryFilter);
        case "primaryPreferred": {
          const primary = servers.filter(primaryFilter);
          const eligiblePrimary = primary.filter(isDeprioritizedFactory(deprioritized));
          if (eligiblePrimary.length) {
            return eligiblePrimary;
          }
          const secondaries = tagSetReducer(readPreference, maxStalenessReducer(readPreference, topologyDescription, servers.filter(secondaryFilter)));
          const eligibleSecondaries = secondaries.filter(isDeprioritizedFactory(deprioritized));
          if (eligibleSecondaries.length) {
            return latencyWindowReducer(topologyDescription, eligibleSecondaries);
          }
          return primary.length ? primary : latencyWindowReducer(topologyDescription, secondaries);
        }
        case "nearest": {
          const eligible = filterDeprioritized(tagSetReducer(readPreference, maxStalenessReducer(readPreference, topologyDescription, servers.filter(nearestFilter))), deprioritized);
          return latencyWindowReducer(topologyDescription, eligible);
        }
        case "secondary":
        case "secondaryPreferred": {
          const secondaries = tagSetReducer(readPreference, maxStalenessReducer(readPreference, topologyDescription, servers.filter(secondaryFilter)));
          const eligibleSecondaries = secondaries.filter(isDeprioritizedFactory(deprioritized));
          if (eligibleSecondaries.length) {
            return latencyWindowReducer(topologyDescription, eligibleSecondaries);
          }
          if (mode === read_preference_1.ReadPreference.SECONDARY_PREFERRED) {
            const primary = servers.filter(primaryFilter);
            const eligiblePrimary = primary.filter(isDeprioritizedFactory(deprioritized));
            if (eligiblePrimary.length)
              return eligiblePrimary;
            return secondaries.length ? latencyWindowReducer(topologyDescription, secondaries) : primary;
          }
          return latencyWindowReducer(topologyDescription, secondaries);
        }
        default: {
          const _exhaustiveCheck = mode;
          throw new error_1.MongoRuntimeError(`unexpected readPreference=${mode} (should never happen).  Please report a bug in the Node driver Jira project.`);
        }
      }
    }
    function readPreferenceServerSelector(readPreference) {
      if (!readPreference.isValid()) {
        throw new error_1.MongoInvalidArgumentError("Invalid read preference specified");
      }
      return function readPreferenceServers(topologyDescription, servers, deprioritized) {
        switch (topologyDescription.type) {
          case "Single":
            return latencyWindowReducer(topologyDescription, servers.filter(knownFilter));
          case "ReplicaSetNoPrimary":
          case "ReplicaSetWithPrimary":
            return secondarySelector(readPreference, topologyDescription, servers, deprioritized);
          case "Sharded": {
            const selectable = filterDeprioritized(servers, deprioritized);
            return latencyWindowReducer(topologyDescription, selectable.filter(knownFilter));
          }
          case "Unknown":
            return [];
          case "LoadBalanced":
            return servers.filter(loadBalancerFilter);
          default: {
            const _exhaustiveCheck = topologyDescription.type;
            throw new error_1.MongoRuntimeError(`unexpected topology type: ${topologyDescription.type} (this should never happen).  Please file a bug in the Node driver Jira project.`);
          }
        }
      };
    }
  }
});

// node_modules/mongodb/lib/constants.js
var require_constants2 = __commonJS({
  "node_modules/mongodb/lib/constants.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.END = exports2.CHANGE = exports2.INIT = exports2.MORE = exports2.RESPONSE = exports2.SERVER_HEARTBEAT_FAILED = exports2.SERVER_HEARTBEAT_SUCCEEDED = exports2.SERVER_HEARTBEAT_STARTED = exports2.COMMAND_FAILED = exports2.COMMAND_SUCCEEDED = exports2.COMMAND_STARTED = exports2.CLUSTER_TIME_RECEIVED = exports2.CONNECTION_CHECKED_IN = exports2.CONNECTION_CHECKED_OUT = exports2.CONNECTION_CHECK_OUT_FAILED = exports2.CONNECTION_CHECK_OUT_STARTED = exports2.CONNECTION_CLOSED = exports2.CONNECTION_READY = exports2.CONNECTION_CREATED = exports2.CONNECTION_POOL_READY = exports2.CONNECTION_POOL_CLEARED = exports2.CONNECTION_POOL_CLOSED = exports2.CONNECTION_POOL_CREATED = exports2.WAITING_FOR_SUITABLE_SERVER = exports2.SERVER_SELECTION_SUCCEEDED = exports2.SERVER_SELECTION_FAILED = exports2.SERVER_SELECTION_STARTED = exports2.TOPOLOGY_DESCRIPTION_CHANGED = exports2.TOPOLOGY_CLOSED = exports2.TOPOLOGY_OPENING = exports2.SERVER_DESCRIPTION_CHANGED = exports2.SERVER_CLOSED = exports2.SERVER_OPENING = exports2.DESCRIPTION_RECEIVED = exports2.UNPINNED = exports2.PINNED = exports2.MESSAGE = exports2.ENDED = exports2.CLOSED = exports2.CONNECT = exports2.OPEN = exports2.CLOSE = exports2.TIMEOUT = exports2.ERROR = exports2.SYSTEM_JS_COLLECTION = exports2.SYSTEM_COMMAND_COLLECTION = exports2.SYSTEM_USER_COLLECTION = exports2.SYSTEM_PROFILE_COLLECTION = exports2.SYSTEM_INDEX_COLLECTION = exports2.SYSTEM_NAMESPACE_COLLECTION = void 0;
    exports2.kDecoratedKeys = exports2.kDecorateResult = exports2.LEGACY_HELLO_COMMAND_CAMEL_CASE = exports2.LEGACY_HELLO_COMMAND = exports2.MONGO_CLIENT_EVENTS = exports2.LOCAL_SERVER_EVENTS = exports2.SERVER_RELAY_EVENTS = exports2.APM_EVENTS = exports2.TOPOLOGY_EVENTS = exports2.CMAP_EVENTS = exports2.HEARTBEAT_EVENTS = exports2.RESUME_TOKEN_CHANGED = void 0;
    exports2.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces";
    exports2.SYSTEM_INDEX_COLLECTION = "system.indexes";
    exports2.SYSTEM_PROFILE_COLLECTION = "system.profile";
    exports2.SYSTEM_USER_COLLECTION = "system.users";
    exports2.SYSTEM_COMMAND_COLLECTION = "$cmd";
    exports2.SYSTEM_JS_COLLECTION = "system.js";
    exports2.ERROR = "error";
    exports2.TIMEOUT = "timeout";
    exports2.CLOSE = "close";
    exports2.OPEN = "open";
    exports2.CONNECT = "connect";
    exports2.CLOSED = "closed";
    exports2.ENDED = "ended";
    exports2.MESSAGE = "message";
    exports2.PINNED = "pinned";
    exports2.UNPINNED = "unpinned";
    exports2.DESCRIPTION_RECEIVED = "descriptionReceived";
    exports2.SERVER_OPENING = "serverOpening";
    exports2.SERVER_CLOSED = "serverClosed";
    exports2.SERVER_DESCRIPTION_CHANGED = "serverDescriptionChanged";
    exports2.TOPOLOGY_OPENING = "topologyOpening";
    exports2.TOPOLOGY_CLOSED = "topologyClosed";
    exports2.TOPOLOGY_DESCRIPTION_CHANGED = "topologyDescriptionChanged";
    exports2.SERVER_SELECTION_STARTED = "serverSelectionStarted";
    exports2.SERVER_SELECTION_FAILED = "serverSelectionFailed";
    exports2.SERVER_SELECTION_SUCCEEDED = "serverSelectionSucceeded";
    exports2.WAITING_FOR_SUITABLE_SERVER = "waitingForSuitableServer";
    exports2.CONNECTION_POOL_CREATED = "connectionPoolCreated";
    exports2.CONNECTION_POOL_CLOSED = "connectionPoolClosed";
    exports2.CONNECTION_POOL_CLEARED = "connectionPoolCleared";
    exports2.CONNECTION_POOL_READY = "connectionPoolReady";
    exports2.CONNECTION_CREATED = "connectionCreated";
    exports2.CONNECTION_READY = "connectionReady";
    exports2.CONNECTION_CLOSED = "connectionClosed";
    exports2.CONNECTION_CHECK_OUT_STARTED = "connectionCheckOutStarted";
    exports2.CONNECTION_CHECK_OUT_FAILED = "connectionCheckOutFailed";
    exports2.CONNECTION_CHECKED_OUT = "connectionCheckedOut";
    exports2.CONNECTION_CHECKED_IN = "connectionCheckedIn";
    exports2.CLUSTER_TIME_RECEIVED = "clusterTimeReceived";
    exports2.COMMAND_STARTED = "commandStarted";
    exports2.COMMAND_SUCCEEDED = "commandSucceeded";
    exports2.COMMAND_FAILED = "commandFailed";
    exports2.SERVER_HEARTBEAT_STARTED = "serverHeartbeatStarted";
    exports2.SERVER_HEARTBEAT_SUCCEEDED = "serverHeartbeatSucceeded";
    exports2.SERVER_HEARTBEAT_FAILED = "serverHeartbeatFailed";
    exports2.RESPONSE = "response";
    exports2.MORE = "more";
    exports2.INIT = "init";
    exports2.CHANGE = "change";
    exports2.END = "end";
    exports2.RESUME_TOKEN_CHANGED = "resumeTokenChanged";
    exports2.HEARTBEAT_EVENTS = Object.freeze([
      exports2.SERVER_HEARTBEAT_STARTED,
      exports2.SERVER_HEARTBEAT_SUCCEEDED,
      exports2.SERVER_HEARTBEAT_FAILED
    ]);
    exports2.CMAP_EVENTS = Object.freeze([
      exports2.CONNECTION_POOL_CREATED,
      exports2.CONNECTION_POOL_READY,
      exports2.CONNECTION_POOL_CLEARED,
      exports2.CONNECTION_POOL_CLOSED,
      exports2.CONNECTION_CREATED,
      exports2.CONNECTION_READY,
      exports2.CONNECTION_CLOSED,
      exports2.CONNECTION_CHECK_OUT_STARTED,
      exports2.CONNECTION_CHECK_OUT_FAILED,
      exports2.CONNECTION_CHECKED_OUT,
      exports2.CONNECTION_CHECKED_IN
    ]);
    exports2.TOPOLOGY_EVENTS = Object.freeze([
      exports2.SERVER_OPENING,
      exports2.SERVER_CLOSED,
      exports2.SERVER_DESCRIPTION_CHANGED,
      exports2.TOPOLOGY_OPENING,
      exports2.TOPOLOGY_CLOSED,
      exports2.TOPOLOGY_DESCRIPTION_CHANGED,
      exports2.ERROR,
      exports2.TIMEOUT,
      exports2.CLOSE
    ]);
    exports2.APM_EVENTS = Object.freeze([
      exports2.COMMAND_STARTED,
      exports2.COMMAND_SUCCEEDED,
      exports2.COMMAND_FAILED
    ]);
    exports2.SERVER_RELAY_EVENTS = Object.freeze([
      exports2.SERVER_HEARTBEAT_STARTED,
      exports2.SERVER_HEARTBEAT_SUCCEEDED,
      exports2.SERVER_HEARTBEAT_FAILED,
      exports2.COMMAND_STARTED,
      exports2.COMMAND_SUCCEEDED,
      exports2.COMMAND_FAILED,
      ...exports2.CMAP_EVENTS
    ]);
    exports2.LOCAL_SERVER_EVENTS = Object.freeze([
      exports2.CONNECT,
      exports2.DESCRIPTION_RECEIVED,
      exports2.CLOSED,
      exports2.ENDED
    ]);
    exports2.MONGO_CLIENT_EVENTS = Object.freeze([
      ...exports2.CMAP_EVENTS,
      ...exports2.APM_EVENTS,
      ...exports2.TOPOLOGY_EVENTS,
      ...exports2.HEARTBEAT_EVENTS
    ]);
    exports2.LEGACY_HELLO_COMMAND = "ismaster";
    exports2.LEGACY_HELLO_COMMAND_CAMEL_CASE = "isMaster";
    exports2.kDecorateResult = /* @__PURE__ */ Symbol.for("@@mdb.decorateDecryptionResult");
    exports2.kDecoratedKeys = /* @__PURE__ */ Symbol.for("@@mdb.decryptedKeys");
  }
});

// node_modules/mongodb/lib/read_concern.js
var require_read_concern = __commonJS({
  "node_modules/mongodb/lib/read_concern.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ReadConcern = exports2.ReadConcernLevel = void 0;
    exports2.ReadConcernLevel = Object.freeze({
      local: "local",
      majority: "majority",
      linearizable: "linearizable",
      available: "available",
      snapshot: "snapshot"
    });
    var ReadConcern = class _ReadConcern {
      /** Constructs a ReadConcern from the read concern level.*/
      constructor(level) {
        this.level = exports2.ReadConcernLevel[level] ?? level;
      }
      /**
       * Construct a ReadConcern given an options object.
       *
       * @param options - The options object from which to extract the write concern.
       */
      static fromOptions(options) {
        if (options == null) {
          return;
        }
        if (options.readConcern) {
          const { readConcern } = options;
          if (readConcern instanceof _ReadConcern) {
            return readConcern;
          } else if (typeof readConcern === "string") {
            return new _ReadConcern(readConcern);
          } else if ("level" in readConcern && readConcern.level) {
            return new _ReadConcern(readConcern.level);
          }
        }
        if (options.level) {
          return new _ReadConcern(options.level);
        }
        return;
      }
      static get MAJORITY() {
        return exports2.ReadConcernLevel.majority;
      }
      static get AVAILABLE() {
        return exports2.ReadConcernLevel.available;
      }
      static get LINEARIZABLE() {
        return exports2.ReadConcernLevel.linearizable;
      }
      static get SNAPSHOT() {
        return exports2.ReadConcernLevel.snapshot;
      }
      toJSON() {
        return { level: this.level };
      }
    };
    exports2.ReadConcern = ReadConcern;
  }
});

// node_modules/mongodb/lib/cmap/wire_protocol/on_demand/document.js
var require_document = __commonJS({
  "node_modules/mongodb/lib/cmap/wire_protocol/on_demand/document.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OnDemandDocument = void 0;
    var bson_1 = require_bson2();
    var BSONElementOffset = {
      type: 0,
      nameOffset: 1,
      nameLength: 2,
      offset: 3,
      length: 4
    };
    var OnDemandDocument = class _OnDemandDocument {
      constructor(bson, offset = 0, isArray = false, elements) {
        this.cache = /* @__PURE__ */ Object.create(null);
        this.indexFound = /* @__PURE__ */ Object.create(null);
        this.bson = bson;
        this.offset = offset;
        this.isArray = isArray;
        this.elements = elements ?? (0, bson_1.parseToElementsToArray)(this.bson, offset);
      }
      /** Only supports basic latin strings */
      isElementName(name, element) {
        const nameLength = element[BSONElementOffset.nameLength];
        const nameOffset = element[BSONElementOffset.nameOffset];
        if (name.length !== nameLength)
          return false;
        const nameEnd = nameOffset + nameLength;
        for (let byteIndex = nameOffset, charIndex = 0; charIndex < name.length && byteIndex < nameEnd; charIndex++, byteIndex++) {
          if (this.bson[byteIndex] !== name.charCodeAt(charIndex))
            return false;
        }
        return true;
      }
      /**
       * Seeks into the elements array for an element matching the given name.
       *
       * @remarks
       * Caching:
       * - Caches the existence of a property making subsequent look ups for non-existent properties return immediately
       * - Caches names mapped to elements to avoid reiterating the array and comparing the name again
       * - Caches the index at which an element has been found to prevent rechecking against elements already determined to belong to another name
       *
       * @param name - a basic latin string name of a BSON element
       * @returns
       */
      getElement(name) {
        const cachedElement = this.cache[name];
        if (cachedElement === false)
          return null;
        if (cachedElement != null) {
          return cachedElement;
        }
        if (typeof name === "number") {
          if (this.isArray) {
            if (name < this.elements.length) {
              const element = this.elements[name];
              const cachedElement2 = { element, value: void 0 };
              this.cache[name] = cachedElement2;
              this.indexFound[name] = true;
              return cachedElement2;
            } else {
              return null;
            }
          } else {
            return null;
          }
        }
        for (let index = 0; index < this.elements.length; index++) {
          const element = this.elements[index];
          if (!(index in this.indexFound) && this.isElementName(name, element)) {
            const cachedElement2 = { element, value: void 0 };
            this.cache[name] = cachedElement2;
            this.indexFound[index] = true;
            return cachedElement2;
          }
        }
        this.cache[name] = false;
        return null;
      }
      toJSValue(element, as) {
        const type = element[BSONElementOffset.type];
        const offset = element[BSONElementOffset.offset];
        const length = element[BSONElementOffset.length];
        if (as !== type) {
          return null;
        }
        switch (as) {
          case bson_1.BSONType.null:
          case bson_1.BSONType.undefined:
            return null;
          case bson_1.BSONType.double:
            return bson_1.NumberUtils.getFloat64LE(this.bson, offset);
          case bson_1.BSONType.int:
            return bson_1.NumberUtils.getInt32LE(this.bson, offset);
          case bson_1.BSONType.long:
            return bson_1.NumberUtils.getBigInt64LE(this.bson, offset);
          case bson_1.BSONType.bool:
            return Boolean(this.bson[offset]);
          case bson_1.BSONType.objectId:
            return new bson_1.ObjectId(this.bson.subarray(offset, offset + 12));
          case bson_1.BSONType.timestamp:
            return new bson_1.Timestamp(bson_1.NumberUtils.getBigInt64LE(this.bson, offset));
          case bson_1.BSONType.string:
            return bson_1.ByteUtils.toUTF8(this.bson, offset + 4, offset + length - 1, false);
          case bson_1.BSONType.binData: {
            const totalBinarySize = bson_1.NumberUtils.getInt32LE(this.bson, offset);
            const subType = this.bson[offset + 4];
            if (subType === 2) {
              const subType2BinarySize = bson_1.NumberUtils.getInt32LE(this.bson, offset + 1 + 4);
              if (subType2BinarySize < 0)
                throw new bson_1.BSONError("Negative binary type element size found for subtype 0x02");
              if (subType2BinarySize > totalBinarySize - 4)
                throw new bson_1.BSONError("Binary type with subtype 0x02 contains too long binary size");
              if (subType2BinarySize < totalBinarySize - 4)
                throw new bson_1.BSONError("Binary type with subtype 0x02 contains too short binary size");
              return new bson_1.Binary(this.bson.subarray(offset + 1 + 4 + 4, offset + 1 + 4 + 4 + subType2BinarySize), 2);
            }
            return new bson_1.Binary(this.bson.subarray(offset + 1 + 4, offset + 1 + 4 + totalBinarySize), subType);
          }
          case bson_1.BSONType.date:
            return new Date(Number(bson_1.NumberUtils.getBigInt64LE(this.bson, offset)));
          case bson_1.BSONType.object:
            return new _OnDemandDocument(this.bson, offset);
          case bson_1.BSONType.array:
            return new _OnDemandDocument(this.bson, offset, true);
          default:
            throw new bson_1.BSONError(`Unsupported BSON type: ${as}`);
        }
      }
      /**
       * Returns the number of elements in this BSON document
       */
      size() {
        return this.elements.length;
      }
      /**
       * Checks for the existence of an element by name.
       *
       * @remarks
       * Uses `getElement` with the expectation that will populate caches such that a `has` call
       * followed by a `getElement` call will not repeat the cost paid by the first look up.
       *
       * @param name - element name
       */
      has(name) {
        const cachedElement = this.cache[name];
        if (cachedElement === false)
          return false;
        if (cachedElement != null)
          return true;
        return this.getElement(name) != null;
      }
      get(name, as, required2) {
        const element = this.getElement(name);
        if (element == null) {
          if (required2 === true) {
            throw new bson_1.BSONError(`BSON element "${name}" is missing`);
          } else {
            return null;
          }
        }
        if (element.value == null) {
          const value = this.toJSValue(element.element, as);
          if (value == null) {
            if (required2 === true) {
              throw new bson_1.BSONError(`BSON element "${name}" is missing`);
            } else {
              return null;
            }
          }
          element.value = value;
        }
        return element.value;
      }
      getNumber(name, required2) {
        const maybeBool = this.get(name, bson_1.BSONType.bool);
        const bool = maybeBool == null ? null : maybeBool ? 1 : 0;
        const maybeLong = this.get(name, bson_1.BSONType.long);
        const long = maybeLong == null ? null : Number(maybeLong);
        const result = bool ?? long ?? this.get(name, bson_1.BSONType.int) ?? this.get(name, bson_1.BSONType.double);
        if (required2 === true && result == null) {
          throw new bson_1.BSONError(`BSON element "${name}" is missing`);
        }
        return result;
      }
      /**
       * Deserialize this object, DOES NOT cache result so avoid multiple invocations
       * @param options - BSON deserialization options
       */
      toObject(options) {
        return (0, bson_1.deserialize)(this.bson, {
          ...options,
          index: this.offset,
          allowObjectSmallerThanBufferSize: true
        });
      }
      /** Returns this document's bytes only */
      toBytes() {
        const size = bson_1.NumberUtils.getInt32LE(this.bson, this.offset);
        return this.bson.subarray(this.offset, this.offset + size);
      }
    };
    exports2.OnDemandDocument = OnDemandDocument;
  }
});

// node_modules/mongodb/lib/cmap/wire_protocol/responses.js
var require_responses = __commonJS({
  "node_modules/mongodb/lib/cmap/wire_protocol/responses.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ClientBulkWriteCursorResponse = exports2.ExplainedCursorResponse = exports2.CursorResponse = exports2.MongoDBResponse = void 0;
    exports2.isErrorResponse = isErrorResponse;
    var bson_1 = require_bson2();
    var error_1 = require_error();
    var utils_1 = require_utils();
    var document_1 = require_document();
    var BSONElementOffset = {
      type: 0,
      nameOffset: 1,
      nameLength: 2,
      offset: 3,
      length: 4
    };
    function isErrorResponse(bson, elements) {
      for (let eIdx = 0; eIdx < elements.length; eIdx++) {
        const element = elements[eIdx];
        if (element[BSONElementOffset.nameLength] === 2) {
          const nameOffset = element[BSONElementOffset.nameOffset];
          if (bson[nameOffset] === 111 && bson[nameOffset + 1] === 107) {
            const valueOffset = element[BSONElementOffset.offset];
            const valueLength = element[BSONElementOffset.length];
            for (let i2 = valueOffset; i2 < valueOffset + valueLength; i2++) {
              if (bson[i2] !== 0)
                return false;
            }
            return true;
          }
        }
      }
      return true;
    }
    var MongoDBResponse = class _MongoDBResponse extends document_1.OnDemandDocument {
      get(name, as, required2) {
        try {
          return super.get(name, as, required2);
        } catch (cause) {
          throw new error_1.MongoUnexpectedServerResponseError(cause.message, { cause });
        }
      }
      static is(value) {
        return value instanceof _MongoDBResponse;
      }
      static make(bson) {
        const elements = (0, bson_1.parseToElementsToArray)(bson, 0);
        const isError = isErrorResponse(bson, elements);
        return isError ? new _MongoDBResponse(bson, 0, false, elements) : new this(bson, 0, false, elements);
      }
      static {
        this.empty = new _MongoDBResponse(new Uint8Array([13, 0, 0, 0, 16, 111, 107, 0, 1, 0, 0, 0, 0]));
      }
      /**
       * Returns true iff:
       * - ok is 0 and the top-level code === 50
       * - ok is 1 and the writeErrors array contains a code === 50
       * - ok is 1 and the writeConcern object contains a code === 50
       */
      get isMaxTimeExpiredError() {
        const isTopLevel = this.ok === 0 && this.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired;
        if (isTopLevel)
          return true;
        if (this.ok === 0)
          return false;
        const isWriteConcern = this.get("writeConcernError", bson_1.BSONType.object)?.getNumber("code") === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired;
        if (isWriteConcern)
          return true;
        const writeErrors = this.get("writeErrors", bson_1.BSONType.array);
        if (writeErrors?.size()) {
          for (let i2 = 0; i2 < writeErrors.size(); i2++) {
            const isWriteError = writeErrors.get(i2, bson_1.BSONType.object)?.getNumber("code") === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired;
            if (isWriteError)
              return true;
          }
        }
        return false;
      }
      /**
       * Drivers can safely assume that the `recoveryToken` field is always a BSON document but drivers MUST NOT modify the
       * contents of the document.
       */
      get recoveryToken() {
        return this.get("recoveryToken", bson_1.BSONType.object)?.toObject({
          promoteValues: false,
          promoteLongs: false,
          promoteBuffers: false,
          validation: { utf8: true }
        }) ?? null;
      }
      /**
       * The server creates a cursor in response to a snapshot find/aggregate command and reports atClusterTime within the cursor field in the response.
       * For the distinct command the server adds a top-level atClusterTime field to the response.
       * The atClusterTime field represents the timestamp of the read and is guaranteed to be majority committed.
       */
      get atClusterTime() {
        return this.get("cursor", bson_1.BSONType.object)?.get("atClusterTime", bson_1.BSONType.timestamp) ?? this.get("atClusterTime", bson_1.BSONType.timestamp);
      }
      get operationTime() {
        return this.get("operationTime", bson_1.BSONType.timestamp);
      }
      /** Normalizes whatever BSON value is "ok" to a JS number 1 or 0. */
      get ok() {
        return this.getNumber("ok") ? 1 : 0;
      }
      get $err() {
        return this.get("$err", bson_1.BSONType.string);
      }
      get errmsg() {
        return this.get("errmsg", bson_1.BSONType.string);
      }
      get code() {
        return this.getNumber("code");
      }
      get $clusterTime() {
        if (!("clusterTime" in this)) {
          const clusterTimeDoc = this.get("$clusterTime", bson_1.BSONType.object);
          if (clusterTimeDoc == null) {
            this.clusterTime = null;
            return null;
          }
          const clusterTime = clusterTimeDoc.get("clusterTime", bson_1.BSONType.timestamp, true);
          const signature = clusterTimeDoc.get("signature", bson_1.BSONType.object)?.toObject();
          this.clusterTime = { clusterTime, signature };
        }
        return this.clusterTime ?? null;
      }
      toObject(options) {
        const exactBSONOptions = {
          ...(0, bson_1.pluckBSONSerializeOptions)(options ?? {}),
          validation: (0, bson_1.parseUtf8ValidationOption)(options)
        };
        return super.toObject(exactBSONOptions);
      }
    };
    exports2.MongoDBResponse = MongoDBResponse;
    var CursorResponse = class _CursorResponse extends MongoDBResponse {
      constructor() {
        super(...arguments);
        this._batch = null;
        this.iterated = 0;
        this._encryptedBatch = null;
      }
      /**
       * This supports a feature of the FindCursor.
       * It is an optimization to avoid an extra getMore when the limit has been reached
       */
      static get emptyGetMore() {
        return new _CursorResponse((0, bson_1.serialize)({ ok: 1, cursor: { id: 0n, nextBatch: [] } }));
      }
      static is(value) {
        return value instanceof _CursorResponse || value === _CursorResponse.emptyGetMore;
      }
      get cursor() {
        return this.get("cursor", bson_1.BSONType.object, true);
      }
      get id() {
        try {
          return bson_1.Long.fromBigInt(this.cursor.get("id", bson_1.BSONType.long, true));
        } catch (cause) {
          throw new error_1.MongoUnexpectedServerResponseError(cause.message, { cause });
        }
      }
      get ns() {
        const namespace = this.cursor.get("ns", bson_1.BSONType.string);
        if (namespace != null)
          return (0, utils_1.ns)(namespace);
        return null;
      }
      get length() {
        return Math.max(this.batchSize - this.iterated, 0);
      }
      get encryptedBatch() {
        if (this.encryptedResponse == null)
          return null;
        if (this._encryptedBatch != null)
          return this._encryptedBatch;
        const cursor = this.encryptedResponse?.get("cursor", bson_1.BSONType.object);
        if (cursor?.has("firstBatch"))
          this._encryptedBatch = cursor.get("firstBatch", bson_1.BSONType.array, true);
        else if (cursor?.has("nextBatch"))
          this._encryptedBatch = cursor.get("nextBatch", bson_1.BSONType.array, true);
        else
          throw new error_1.MongoUnexpectedServerResponseError("Cursor document did not contain a batch");
        return this._encryptedBatch;
      }
      get batch() {
        if (this._batch != null)
          return this._batch;
        const cursor = this.cursor;
        if (cursor.has("firstBatch"))
          this._batch = cursor.get("firstBatch", bson_1.BSONType.array, true);
        else if (cursor.has("nextBatch"))
          this._batch = cursor.get("nextBatch", bson_1.BSONType.array, true);
        else
          throw new error_1.MongoUnexpectedServerResponseError("Cursor document did not contain a batch");
        return this._batch;
      }
      get batchSize() {
        return this.batch?.size();
      }
      get postBatchResumeToken() {
        return this.cursor.get("postBatchResumeToken", bson_1.BSONType.object)?.toObject({
          promoteValues: false,
          promoteLongs: false,
          promoteBuffers: false,
          validation: { utf8: true }
        }) ?? null;
      }
      shift(options) {
        if (this.iterated >= this.batchSize) {
          return null;
        }
        const result = this.batch.get(this.iterated, bson_1.BSONType.object, true) ?? null;
        const encryptedResult = this.encryptedBatch?.get(this.iterated, bson_1.BSONType.object, true) ?? null;
        this.iterated += 1;
        if (options?.raw) {
          return result.toBytes();
        } else {
          const object3 = result.toObject(options);
          if (encryptedResult) {
            (0, utils_1.decorateDecryptionResult)(object3, encryptedResult.toObject(options), true);
          }
          return object3;
        }
      }
      clear() {
        this.iterated = this.batchSize;
      }
    };
    exports2.CursorResponse = CursorResponse;
    var ExplainedCursorResponse = class extends CursorResponse {
      constructor() {
        super(...arguments);
        this.isExplain = true;
        this._length = 1;
      }
      get id() {
        return bson_1.Long.fromBigInt(0n);
      }
      get batchSize() {
        return 0;
      }
      get ns() {
        return null;
      }
      get length() {
        return this._length;
      }
      shift(options) {
        if (this._length === 0)
          return null;
        this._length -= 1;
        return this.toObject(options);
      }
    };
    exports2.ExplainedCursorResponse = ExplainedCursorResponse;
    var ClientBulkWriteCursorResponse = class extends CursorResponse {
      get insertedCount() {
        return this.get("nInserted", bson_1.BSONType.int, true);
      }
      get upsertedCount() {
        return this.get("nUpserted", bson_1.BSONType.int, true);
      }
      get matchedCount() {
        return this.get("nMatched", bson_1.BSONType.int, true);
      }
      get modifiedCount() {
        return this.get("nModified", bson_1.BSONType.int, true);
      }
      get deletedCount() {
        return this.get("nDeleted", bson_1.BSONType.int, true);
      }
      get writeConcernError() {
        return this.get("writeConcernError", bson_1.BSONType.object, false);
      }
    };
    exports2.ClientBulkWriteCursorResponse = ClientBulkWriteCursorResponse;
  }
});

// node_modules/mongodb/lib/write_concern.js
var require_write_concern = __commonJS({
  "node_modules/mongodb/lib/write_concern.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.WriteConcern = exports2.WRITE_CONCERN_KEYS = void 0;
    exports2.throwIfWriteConcernError = throwIfWriteConcernError;
    var responses_1 = require_responses();
    var error_1 = require_error();
    exports2.WRITE_CONCERN_KEYS = ["w", "wtimeout", "j", "journal", "fsync"];
    var WriteConcern = class _WriteConcern {
      /**
       * Constructs a WriteConcern from the write concern properties.
       * @param w - request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags.
       * @param wtimeoutMS - specify a time limit to prevent write operations from blocking indefinitely
       * @param journal - request acknowledgment that the write operation has been written to the on-disk journal
       * @param fsync - equivalent to the j option. Is deprecated and will be removed in the next major version.
       */
      constructor(w, wtimeoutMS, journal, fsync) {
        if (w != null) {
          if (!Number.isNaN(Number(w))) {
            this.w = Number(w);
          } else {
            this.w = w;
          }
        }
        if (wtimeoutMS != null) {
          this.wtimeoutMS = this.wtimeout = wtimeoutMS;
        }
        if (journal != null) {
          this.journal = this.j = journal;
        }
        if (fsync != null) {
          this.journal = this.j = fsync ? true : false;
        }
      }
      /**
       * Apply a write concern to a command document. Will modify and return the command.
       */
      static apply(command, writeConcern) {
        const wc = {};
        if (writeConcern.w != null)
          wc.w = writeConcern.w;
        if (writeConcern.wtimeoutMS != null)
          wc.wtimeout = writeConcern.wtimeoutMS;
        if (writeConcern.journal != null)
          wc.j = writeConcern.j;
        command.writeConcern = wc;
        return command;
      }
      /** Construct a WriteConcern given an options object. */
      static fromOptions(options, inherit) {
        if (options == null)
          return void 0;
        inherit = inherit ?? {};
        let opts;
        if (typeof options === "string" || typeof options === "number") {
          opts = { w: options };
        } else if (options instanceof _WriteConcern) {
          opts = options;
        } else {
          opts = options.writeConcern;
        }
        const parentOpts = inherit instanceof _WriteConcern ? inherit : inherit.writeConcern;
        const mergedOpts = { ...parentOpts, ...opts };
        const { w = void 0, wtimeout = void 0, j = void 0, fsync = void 0, journal = void 0, wtimeoutMS = void 0 } = mergedOpts;
        if (w != null || wtimeout != null || wtimeoutMS != null || j != null || journal != null || fsync != null) {
          return new _WriteConcern(w, wtimeout ?? wtimeoutMS, j ?? journal, fsync);
        }
        return void 0;
      }
    };
    exports2.WriteConcern = WriteConcern;
    function throwIfWriteConcernError(response) {
      if (typeof response === "object" && response != null) {
        const writeConcernError = responses_1.MongoDBResponse.is(response) && response.has("writeConcernError") ? response.toObject() : !responses_1.MongoDBResponse.is(response) && "writeConcernError" in response ? response : null;
        if (writeConcernError != null) {
          throw new error_1.MongoWriteConcernError(writeConcernError);
        }
      }
    }
  }
});

// node_modules/mongodb/lib/utils.js
var require_utils = __commonJS({
  "node_modules/mongodb/lib/utils.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.kDispose = exports2.randomBytes = exports2.COSMOS_DB_MSG = exports2.DOCUMENT_DB_MSG = exports2.COSMOS_DB_CHECK = exports2.DOCUMENT_DB_CHECK = exports2.MONGODB_WARNING_CODE = exports2.DEFAULT_PK_FACTORY = exports2.HostAddress = exports2.BufferPool = exports2.List = exports2.MongoDBCollectionNamespace = exports2.MongoDBNamespace = void 0;
    exports2.isUint8Array = isUint8Array;
    exports2.hostMatchesWildcards = hostMatchesWildcards;
    exports2.normalizeHintField = normalizeHintField;
    exports2.isObject = isObject2;
    exports2.mergeOptions = mergeOptions;
    exports2.filterOptions = filterOptions;
    exports2.isPromiseLike = isPromiseLike;
    exports2.decorateWithCollation = decorateWithCollation;
    exports2.decorateWithReadConcern = decorateWithReadConcern;
    exports2.getTopology = getTopology;
    exports2.ns = ns;
    exports2.makeCounter = makeCounter;
    exports2.uuidV4 = uuidV4;
    exports2.maxWireVersion = maxWireVersion;
    exports2.arrayStrictEqual = arrayStrictEqual;
    exports2.errorStrictEqual = errorStrictEqual;
    exports2.makeStateMachine = makeStateMachine;
    exports2.processTimeMS = processTimeMS;
    exports2.calculateDurationInMs = calculateDurationInMs;
    exports2.hasAtomicOperators = hasAtomicOperators;
    exports2.resolveTimeoutOptions = resolveTimeoutOptions;
    exports2.resolveOptions = resolveOptions;
    exports2.isSuperset = isSuperset;
    exports2.isHello = isHello;
    exports2.setDifference = setDifference;
    exports2.isRecord = isRecord;
    exports2.emitWarning = emitWarning;
    exports2.emitWarningOnce = emitWarningOnce;
    exports2.enumToString = enumToString;
    exports2.supportsRetryableWrites = supportsRetryableWrites;
    exports2.shuffle = shuffle;
    exports2.commandSupportsReadConcern = commandSupportsReadConcern;
    exports2.commandSupportsAfterClusterTime = commandSupportsAfterClusterTime;
    exports2.compareObjectId = compareObjectId;
    exports2.parseInteger = parseInteger;
    exports2.parseUnsignedInteger = parseUnsignedInteger;
    exports2.checkParentDomainMatch = checkParentDomainMatch;
    exports2.get = get;
    exports2.isHostMatch = isHostMatch;
    exports2.promiseWithResolvers = promiseWithResolvers;
    exports2.squashError = squashError;
    exports2.once = once;
    exports2.maybeAddIdToDocuments = maybeAddIdToDocuments;
    exports2.fileIsAccessible = fileIsAccessible;
    exports2.csotMin = csotMin;
    exports2.noop = noop2;
    exports2.decorateDecryptionResult = decorateDecryptionResult;
    exports2.addAbortListener = addAbortListener;
    exports2.abortable = abortable;
    var fs_1 = require("fs");
    var http3 = require("http");
    var process4 = require("process");
    var timers_1 = require("timers");
    var bson_1 = require_bson2();
    var constants_1 = require_constants();
    var constants_2 = require_constants2();
    var error_1 = require_error();
    var read_concern_1 = require_read_concern();
    var read_preference_1 = require_read_preference();
    var common_1 = require_common();
    var write_concern_1 = require_write_concern();
    function isUint8Array(value) {
      return value != null && typeof value === "object" && Symbol.toStringTag in value && value[Symbol.toStringTag] === "Uint8Array";
    }
    function hostMatchesWildcards(host, wildcards) {
      for (const wildcard of wildcards) {
        if (host === wildcard) {
          return true;
        }
        if (wildcard.startsWith("*.")) {
          const suffix = wildcard.substring(2);
          if (host === suffix || host.endsWith(`.${suffix}`)) {
            return true;
          }
        }
        if (wildcard.startsWith("*/")) {
          const suffix = wildcard.substring(2);
          if (host === suffix || host.endsWith(`/${suffix}`)) {
            return true;
          }
        }
      }
      return false;
    }
    function normalizeHintField(hint) {
      let finalHint = void 0;
      if (typeof hint === "string") {
        finalHint = hint;
      } else if (Array.isArray(hint)) {
        finalHint = {};
        hint.forEach((param) => {
          finalHint[param] = 1;
        });
      } else if (hint != null && typeof hint === "object") {
        finalHint = {};
        for (const name in hint) {
          finalHint[name] = hint[name];
        }
      }
      return finalHint;
    }
    var TO_STRING = (object3) => Object.prototype.toString.call(object3);
    function isObject2(arg) {
      return "[object Object]" === TO_STRING(arg);
    }
    function mergeOptions(target, source) {
      return { ...target, ...source };
    }
    function filterOptions(options, names) {
      const filterOptions2 = {};
      for (const name in options) {
        if (names.includes(name)) {
          filterOptions2[name] = options[name];
        }
      }
      return filterOptions2;
    }
    function isPromiseLike(value) {
      return value != null && typeof value === "object" && "then" in value && typeof value.then === "function";
    }
    function decorateWithCollation(command, options) {
      if (options.collation && typeof options.collation === "object") {
        command.collation = options.collation;
      }
    }
    function decorateWithReadConcern(command, coll, options) {
      if (options && options.session && options.session.inTransaction()) {
        return;
      }
      const readConcern = Object.assign({}, command.readConcern || {});
      if (coll.s.readConcern) {
        Object.assign(readConcern, coll.s.readConcern);
      }
      if (Object.keys(readConcern).length > 0) {
        Object.assign(command, { readConcern });
      }
    }
    function getTopology(provider) {
      if ("topology" in provider && provider.topology) {
        return provider.topology;
      } else if ("client" in provider && provider.client.topology) {
        return provider.client.topology;
      }
      throw new error_1.MongoNotConnectedError("MongoClient must be connected to perform this operation");
    }
    function ns(ns2) {
      return MongoDBNamespace.fromString(ns2);
    }
    var MongoDBNamespace = class _MongoDBNamespace {
      /**
       * Create a namespace object
       *
       * @param db - database name
       * @param collection - collection name
       */
      constructor(db, collection) {
        this.db = db;
        this.collection = collection === "" ? void 0 : collection;
      }
      toString() {
        return this.collection ? `${this.db}.${this.collection}` : this.db;
      }
      withCollection(collection) {
        return new MongoDBCollectionNamespace(this.db, collection);
      }
      static fromString(namespace) {
        if (typeof namespace !== "string" || namespace === "") {
          throw new error_1.MongoRuntimeError(`Cannot parse namespace from "${namespace}"`);
        }
        const [db, ...collectionParts] = namespace.split(".");
        const collection = collectionParts.join(".");
        return new _MongoDBNamespace(db, collection === "" ? void 0 : collection);
      }
    };
    exports2.MongoDBNamespace = MongoDBNamespace;
    var MongoDBCollectionNamespace = class extends MongoDBNamespace {
      constructor(db, collection) {
        super(db, collection);
        this.collection = collection;
      }
      static fromString(namespace) {
        return super.fromString(namespace);
      }
    };
    exports2.MongoDBCollectionNamespace = MongoDBCollectionNamespace;
    function* makeCounter(seed = 0) {
      let count = seed;
      while (true) {
        const newCount = count;
        count += 1;
        yield newCount;
      }
    }
    function uuidV4() {
      const result = crypto.getRandomValues(new Uint8Array(16));
      result[6] = result[6] & 15 | 64;
      result[8] = result[8] & 63 | 128;
      return result;
    }
    function maxWireVersion(handshakeAware) {
      if (handshakeAware) {
        if (handshakeAware.hello) {
          return handshakeAware.hello.maxWireVersion;
        }
        if (handshakeAware.serverApi?.version) {
          return constants_1.MAX_SUPPORTED_WIRE_VERSION;
        }
        if (handshakeAware.loadBalanced) {
          return constants_1.MAX_SUPPORTED_WIRE_VERSION;
        }
        if ("lastHello" in handshakeAware && typeof handshakeAware.lastHello === "function") {
          const lastHello = handshakeAware.lastHello();
          if (lastHello) {
            return lastHello.maxWireVersion;
          }
        }
        if (handshakeAware.description && "maxWireVersion" in handshakeAware.description && handshakeAware.description.maxWireVersion != null) {
          return handshakeAware.description.maxWireVersion;
        }
      }
      return 0;
    }
    function arrayStrictEqual(arr, arr2) {
      if (!Array.isArray(arr) || !Array.isArray(arr2)) {
        return false;
      }
      return arr.length === arr2.length && arr.every((elt, idx) => elt === arr2[idx]);
    }
    function errorStrictEqual(lhs, rhs) {
      if (lhs === rhs) {
        return true;
      }
      if (!lhs || !rhs) {
        return lhs === rhs;
      }
      if (lhs == null && rhs != null || lhs != null && rhs == null) {
        return false;
      }
      if (lhs.constructor.name !== rhs.constructor.name) {
        return false;
      }
      if (lhs.message !== rhs.message) {
        return false;
      }
      return true;
    }
    function makeStateMachine(stateTable) {
      return function stateTransition(target, newState) {
        const legalStates = stateTable[target.s.state];
        if (legalStates && legalStates.indexOf(newState) < 0) {
          throw new error_1.MongoRuntimeError(`illegal state transition from [${target.s.state}] => [${newState}], allowed: [${legalStates}]`);
        }
        target.emit("stateChanged", target.s.state, newState);
        target.s.state = newState;
      };
    }
    function processTimeMS() {
      return Math.floor(performance.now());
    }
    function calculateDurationInMs(started) {
      if (typeof started !== "number") {
        return -1;
      }
      const elapsed = processTimeMS() - started;
      return elapsed < 0 ? 0 : elapsed;
    }
    function hasAtomicOperators(doc, options) {
      if (Array.isArray(doc)) {
        for (const document2 of doc) {
          if (hasAtomicOperators(document2)) {
            return true;
          }
        }
        return false;
      }
      const keys = Object.keys(doc);
      if (options?.ignoreUndefined) {
        let allUndefined = true;
        for (const key of keys) {
          if (doc[key] !== void 0) {
            allUndefined = false;
            break;
          }
        }
        if (allUndefined) {
          throw new error_1.MongoInvalidArgumentError("Update operations require that all atomic operators have defined values, but none were provided.");
        }
      }
      return keys.length > 0 && keys[0][0] === "$";
    }
    function resolveTimeoutOptions(client, options) {
      const { socketTimeoutMS, serverSelectionTimeoutMS, waitQueueTimeoutMS, timeoutMS } = client.s.options;
      return { socketTimeoutMS, serverSelectionTimeoutMS, waitQueueTimeoutMS, timeoutMS, ...options };
    }
    function resolveOptions(parent, options) {
      const result = Object.assign({}, options, (0, bson_1.resolveBSONOptions)(options, parent));
      const timeoutMS = options?.timeoutMS ?? parent?.timeoutMS;
      const session = options?.session;
      if (!session?.inTransaction()) {
        const readConcern = read_concern_1.ReadConcern.fromOptions(options) ?? parent?.readConcern;
        if (readConcern) {
          result.readConcern = readConcern;
        }
        let writeConcern = write_concern_1.WriteConcern.fromOptions(options) ?? parent?.writeConcern;
        if (writeConcern) {
          if (timeoutMS != null) {
            writeConcern = write_concern_1.WriteConcern.fromOptions({
              writeConcern: {
                ...writeConcern,
                wtimeout: void 0,
                wtimeoutMS: void 0
              }
            });
          }
          result.writeConcern = writeConcern;
        }
      }
      result.timeoutMS = timeoutMS;
      const readPreference = read_preference_1.ReadPreference.fromOptions(options) ?? parent?.readPreference;
      if (readPreference) {
        result.readPreference = readPreference;
      }
      const isConvenientTransaction = session?.explicit && session?.timeoutContext != null;
      if (isConvenientTransaction && options?.timeoutMS != null) {
        throw new error_1.MongoInvalidArgumentError("An operation cannot be given a timeoutMS setting when inside a withTransaction call that has a timeoutMS setting");
      }
      return result;
    }
    function isSuperset(set2, subset) {
      set2 = Array.isArray(set2) ? new Set(set2) : set2;
      subset = Array.isArray(subset) ? new Set(subset) : subset;
      for (const elem of subset) {
        if (!set2.has(elem)) {
          return false;
        }
      }
      return true;
    }
    function isHello(doc) {
      return doc[constants_2.LEGACY_HELLO_COMMAND] || doc.hello ? true : false;
    }
    function setDifference(setA, setB) {
      const difference = new Set(setA);
      for (const elem of setB) {
        difference.delete(elem);
      }
      return difference;
    }
    var HAS_OWN = (object3, prop) => Object.prototype.hasOwnProperty.call(object3, prop);
    function isRecord(value, requiredKeys = void 0) {
      if (!isObject2(value)) {
        return false;
      }
      const ctor = value.constructor;
      if (ctor && ctor.prototype) {
        if (!isObject2(ctor.prototype)) {
          return false;
        }
        if (!HAS_OWN(ctor.prototype, "isPrototypeOf")) {
          return false;
        }
      }
      if (requiredKeys) {
        const keys = Object.keys(value);
        return isSuperset(keys, requiredKeys);
      }
      return true;
    }
    var List = class {
      get length() {
        return this.count;
      }
      get [Symbol.toStringTag]() {
        return "List";
      }
      constructor() {
        this.count = 0;
        this.head = {
          next: null,
          prev: null,
          value: null
        };
        this.head.next = this.head;
        this.head.prev = this.head;
      }
      toArray() {
        return Array.from(this);
      }
      toString() {
        return `head <=> ${this.toArray().join(" <=> ")} <=> head`;
      }
      *[Symbol.iterator]() {
        for (const node of this.nodes()) {
          yield node.value;
        }
      }
      *nodes() {
        let ptr = this.head.next;
        while (ptr !== this.head) {
          const { next } = ptr;
          yield ptr;
          ptr = next;
        }
      }
      /** Insert at end of list */
      push(value) {
        this.count += 1;
        const newNode = {
          next: this.head,
          prev: this.head.prev,
          value
        };
        this.head.prev.next = newNode;
        this.head.prev = newNode;
      }
      /** Inserts every item inside an iterable instead of the iterable itself */
      pushMany(iterable) {
        for (const value of iterable) {
          this.push(value);
        }
      }
      /** Insert at front of list */
      unshift(value) {
        this.count += 1;
        const newNode = {
          next: this.head.next,
          prev: this.head,
          value
        };
        this.head.next.prev = newNode;
        this.head.next = newNode;
      }
      remove(node) {
        if (node === this.head || this.length === 0) {
          return null;
        }
        this.count -= 1;
        const prevNode = node.prev;
        const nextNode = node.next;
        prevNode.next = nextNode;
        nextNode.prev = prevNode;
        return node.value;
      }
      /** Removes the first node at the front of the list */
      shift() {
        return this.remove(this.head.next);
      }
      /** Removes the last node at the end of the list */
      pop() {
        return this.remove(this.head.prev);
      }
      /** Iterates through the list and removes nodes where filter returns true */
      prune(filter) {
        for (const node of this.nodes()) {
          if (filter(node.value)) {
            this.remove(node);
          }
        }
      }
      clear() {
        this.count = 0;
        this.head.next = this.head;
        this.head.prev = this.head;
      }
      /** Returns the first item in the list, does not remove */
      first() {
        return this.head.next.value;
      }
      /** Returns the last item in the list, does not remove */
      last() {
        return this.head.prev.value;
      }
    };
    exports2.List = List;
    var BufferPool = class {
      constructor() {
        this.buffers = new List();
        this.totalByteLength = 0;
      }
      get length() {
        return this.totalByteLength;
      }
      /** Adds a buffer to the internal buffer pool list */
      append(buffer) {
        this.buffers.push(buffer);
        this.totalByteLength += buffer.length;
      }
      /**
       * If BufferPool contains 4 bytes or more construct an int32 from the leading bytes,
       * otherwise return null. Size can be negative, caller should error check.
       */
      getInt32() {
        if (this.totalByteLength < 4) {
          return null;
        }
        const firstBuffer = this.buffers.first();
        if (firstBuffer != null && firstBuffer.byteLength >= 4) {
          return bson_1.NumberUtils.getInt32LE(firstBuffer, 0);
        }
        const top4Bytes = this.read(4);
        const value = bson_1.NumberUtils.getInt32LE(top4Bytes, 0);
        this.totalByteLength += 4;
        this.buffers.unshift(top4Bytes);
        return value;
      }
      /** Reads the requested number of bytes, optionally consuming them */
      read(size) {
        if (typeof size !== "number" || size < 0) {
          throw new error_1.MongoInvalidArgumentError('Argument "size" must be a non-negative number');
        }
        if (size > this.totalByteLength) {
          return bson_1.ByteUtils.allocate(0);
        }
        const result = bson_1.ByteUtils.allocateUnsafe(size);
        for (let bytesRead = 0; bytesRead < size; ) {
          const buffer = this.buffers.shift();
          if (buffer == null) {
            break;
          }
          const bytesRemaining = size - bytesRead;
          const bytesReadable = Math.min(bytesRemaining, buffer.byteLength);
          const bytes = buffer.subarray(0, bytesReadable);
          result.set(bytes, bytesRead);
          bytesRead += bytesReadable;
          this.totalByteLength -= bytesReadable;
          if (bytesReadable < buffer.byteLength) {
            this.buffers.unshift(buffer.subarray(bytesReadable));
          }
        }
        return result;
      }
    };
    exports2.BufferPool = BufferPool;
    var HostAddress = class _HostAddress {
      constructor(hostString) {
        this.host = void 0;
        this.port = void 0;
        this.socketPath = void 0;
        this.isIPv6 = false;
        const escapedHost = hostString.split(" ").join("%20");
        if (escapedHost.endsWith(".sock")) {
          this.socketPath = decodeURIComponent(escapedHost);
          return;
        }
        const urlString = `iLoveJS://${escapedHost}`;
        let url2;
        try {
          url2 = new URL(urlString);
        } catch (urlError) {
          const runtimeError = new error_1.MongoRuntimeError(`Unable to parse ${escapedHost} with URL`);
          runtimeError.cause = urlError;
          throw runtimeError;
        }
        const hostname3 = url2.hostname;
        const port = url2.port;
        let normalized = decodeURIComponent(hostname3).toLowerCase();
        if (normalized.startsWith("[") && normalized.endsWith("]")) {
          this.isIPv6 = true;
          normalized = normalized.substring(1, hostname3.length - 1);
        }
        this.host = normalized.toLowerCase();
        if (typeof port === "number") {
          this.port = port;
        } else if (typeof port === "string" && port !== "") {
          this.port = Number.parseInt(port, 10);
        } else {
          this.port = 27017;
        }
        if (this.port === 0) {
          throw new error_1.MongoParseError("Invalid port (zero) with hostname");
        }
        Object.freeze(this);
      }
      [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
        return this.inspect();
      }
      inspect() {
        return `new HostAddress('${this.toString()}')`;
      }
      toString() {
        if (typeof this.host === "string") {
          if (this.isIPv6) {
            return `[${this.host}]:${this.port}`;
          }
          return `${this.host}:${this.port}`;
        }
        return `${this.socketPath}`;
      }
      static fromString(s2) {
        return new _HostAddress(s2);
      }
      static fromHostPort(host, port) {
        if (host.includes(":")) {
          host = `[${host}]`;
        }
        return _HostAddress.fromString(`${host}:${port}`);
      }
      static fromSrvRecord({ name, port }) {
        return _HostAddress.fromHostPort(name, port);
      }
      toHostPort() {
        if (this.socketPath) {
          return { host: this.socketPath, port: 0 };
        }
        const host = this.host ?? "";
        const port = this.port ?? 0;
        return { host, port };
      }
    };
    exports2.HostAddress = HostAddress;
    exports2.DEFAULT_PK_FACTORY = {
      // We prefer not to rely on ObjectId having a createPk method
      createPk() {
        return new bson_1.ObjectId();
      }
    };
    exports2.MONGODB_WARNING_CODE = "MONGODB DRIVER";
    function emitWarning(message) {
      return process4.emitWarning(message, { code: exports2.MONGODB_WARNING_CODE });
    }
    var emittedWarnings = /* @__PURE__ */ new Set();
    function emitWarningOnce(message) {
      if (!emittedWarnings.has(message)) {
        emittedWarnings.add(message);
        return emitWarning(message);
      }
    }
    function enumToString(en) {
      return Object.values(en).join(", ");
    }
    function supportsRetryableWrites(server) {
      if (!server) {
        return false;
      }
      if (server.loadBalanced) {
        return true;
      }
      if (server.description.logicalSessionTimeoutMinutes != null) {
        if (server.description.type !== common_1.ServerType.Standalone) {
          return true;
        }
      }
      return false;
    }
    function shuffle(sequence, limit = 0) {
      const items = Array.from(sequence);
      if (limit > items.length) {
        throw new error_1.MongoRuntimeError("Limit must be less than the number of items");
      }
      let remainingItemsToShuffle = items.length;
      const lowerBound = limit % items.length === 0 ? 1 : items.length - limit;
      while (remainingItemsToShuffle > lowerBound) {
        const randomIndex = Math.floor(Math.random() * remainingItemsToShuffle);
        remainingItemsToShuffle -= 1;
        const swapHold = items[remainingItemsToShuffle];
        items[remainingItemsToShuffle] = items[randomIndex];
        items[randomIndex] = swapHold;
      }
      return limit % items.length === 0 ? items : items.slice(lowerBound);
    }
    function commandSupportsReadConcern(command) {
      if (command.aggregate || command.count || command.distinct || command.find || command.geoNear) {
        return true;
      }
      return false;
    }
    function commandSupportsAfterClusterTime(command) {
      if (command.aggregate || command.count || command.distinct || command.find || command.geoNear) {
        return true;
      }
      if (command.bulkWrite || command.create || command.createIndexes || command.delete || command.drop || command.dropDatabase || command.dropIndexes || command.findAndModify || command.insert || command.update) {
        return true;
      }
      return false;
    }
    function compareObjectId(oid1, oid2) {
      if (oid1 == null && oid2 == null) {
        return 0;
      }
      if (oid1 == null) {
        return -1;
      }
      if (oid2 == null) {
        return 1;
      }
      return bson_1.ByteUtils.compare(oid1.id, oid2.id);
    }
    function parseInteger(value) {
      if (typeof value === "number")
        return Math.trunc(value);
      const parsedValue = Number.parseInt(String(value), 10);
      return Number.isNaN(parsedValue) ? null : parsedValue;
    }
    function parseUnsignedInteger(value) {
      const parsedInt = parseInteger(value);
      return parsedInt != null && parsedInt >= 0 ? parsedInt : null;
    }
    function checkParentDomainMatch(address, srvHost) {
      const normalizedAddress = address.endsWith(".") ? address.slice(0, address.length - 1) : address;
      const normalizedSrvHost = srvHost.endsWith(".") ? srvHost.slice(0, srvHost.length - 1) : srvHost;
      const allCharacterBeforeFirstDot = /^.*?\./;
      const srvIsLessThanThreeParts = normalizedSrvHost.split(".").length < 3;
      const addressDomain = `.${normalizedAddress.replace(allCharacterBeforeFirstDot, "")}`;
      let srvHostDomain = srvIsLessThanThreeParts ? normalizedSrvHost : `.${normalizedSrvHost.replace(allCharacterBeforeFirstDot, "")}`;
      if (!srvHostDomain.startsWith(".")) {
        srvHostDomain = "." + srvHostDomain;
      }
      if (srvIsLessThanThreeParts && normalizedAddress.split(".").length <= normalizedSrvHost.split(".").length) {
        throw new error_1.MongoAPIError("Server record does not have at least one more domain level than parent URI");
      }
      if (!addressDomain.endsWith(srvHostDomain)) {
        throw new error_1.MongoAPIError("Server record does not share hostname with parent URI");
      }
    }
    function get(url2, options = {}) {
      return new Promise((resolve2, reject) => {
        let timeoutId;
        const request = http3.get(url2, options, (response) => {
          response.setEncoding("utf8");
          let body = "";
          response.on("data", (chunk) => body += chunk);
          response.on("end", () => {
            (0, timers_1.clearTimeout)(timeoutId);
            resolve2({ status: response.statusCode, body });
          });
        }).on("error", (error51) => {
          (0, timers_1.clearTimeout)(timeoutId);
          reject(error51);
        }).end();
        timeoutId = (0, timers_1.setTimeout)(() => {
          request.destroy(new error_1.MongoNetworkTimeoutError(`request timed out after 10 seconds`));
        }, 1e4);
      });
    }
    exports2.DOCUMENT_DB_CHECK = /(\.docdb\.amazonaws\.com$)|(\.docdb-elastic\.amazonaws\.com$)/;
    exports2.COSMOS_DB_CHECK = /\.cosmos\.azure\.com$/;
    exports2.DOCUMENT_DB_MSG = "You appear to be connected to a DocumentDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/documentdb";
    exports2.COSMOS_DB_MSG = "You appear to be connected to a CosmosDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/cosmosdb";
    function isHostMatch(match, host) {
      return host && match.test(host.toLowerCase()) ? true : false;
    }
    function promiseWithResolvers() {
      let resolve2;
      let reject;
      const promise2 = new Promise(function withResolversExecutor(promiseResolve, promiseReject) {
        resolve2 = promiseResolve;
        reject = promiseReject;
      });
      return { promise: promise2, resolve: resolve2, reject };
    }
    function squashError(_error) {
      return;
    }
    var randomBytes = (size) => {
      return Promise.resolve(crypto.getRandomValues(new Uint8Array(size)));
    };
    exports2.randomBytes = randomBytes;
    async function once(ee, name, options) {
      options?.signal?.throwIfAborted();
      const { promise: promise2, resolve: resolve2, reject } = promiseWithResolvers();
      const onEvent = (data) => resolve2(data);
      const onError = (error51) => reject(error51);
      const abortListener = addAbortListener(options?.signal, function() {
        reject(this.reason);
      });
      ee.once(name, onEvent).once("error", onError);
      try {
        return await promise2;
      } finally {
        ee.off(name, onEvent);
        ee.off("error", onError);
        abortListener?.[exports2.kDispose]();
      }
    }
    function maybeAddIdToDocuments(collection, document2, options) {
      const forceServerObjectId = options.forceServerObjectId ?? collection.db.options?.forceServerObjectId ?? false;
      if (forceServerObjectId) {
        return document2;
      }
      if (document2._id == null) {
        document2._id = collection.s.pkFactory.createPk();
      }
      return document2;
    }
    async function fileIsAccessible(fileName, mode) {
      try {
        await fs_1.promises.access(fileName, mode);
        return true;
      } catch {
        return false;
      }
    }
    function csotMin(duration1, duration22) {
      if (duration1 === 0)
        return duration22;
      if (duration22 === 0)
        return duration1;
      return Math.min(duration1, duration22);
    }
    function noop2() {
      return;
    }
    function decorateDecryptionResult(decrypted, original, isTopLevelDecorateCall = true) {
      if (isTopLevelDecorateCall) {
        if (bson_1.ByteUtils.isUint8Array(original)) {
          original = (0, bson_1.deserialize)(original);
        }
        if (bson_1.ByteUtils.isUint8Array(decrypted)) {
          throw new error_1.MongoRuntimeError("Expected result of decryption to be deserialized BSON object");
        }
      }
      if (!decrypted || typeof decrypted !== "object")
        return;
      for (const k of Object.keys(decrypted)) {
        const originalValue = original[k];
        if (originalValue && originalValue._bsontype === "Binary" && originalValue.sub_type === 6) {
          if (!decrypted[constants_2.kDecoratedKeys]) {
            Object.defineProperty(decrypted, constants_2.kDecoratedKeys, {
              value: [],
              configurable: true,
              enumerable: false,
              writable: false
            });
          }
          decrypted[constants_2.kDecoratedKeys].push(k);
          continue;
        }
        decorateDecryptionResult(decrypted[k], originalValue, false);
      }
    }
    exports2.kDispose = Symbol.dispose ?? /* @__PURE__ */ Symbol("dispose");
    function addAbortListener(signal, listener) {
      if (signal == null)
        return;
      signal.addEventListener("abort", listener, { once: true });
      return { [exports2.kDispose]: () => signal.removeEventListener("abort", listener) };
    }
    async function abortable(promise2, { signal }) {
      if (signal == null) {
        return await promise2;
      }
      const { promise: aborted2, reject } = promiseWithResolvers();
      const abortListener = signal.aborted ? reject(signal.reason) : addAbortListener(signal, function() {
        reject(this.reason);
      });
      try {
        return await Promise.race([promise2, aborted2]);
      } finally {
        abortListener?.[exports2.kDispose]();
      }
    }
  }
});

// node_modules/mongodb/lib/timeout.js
var require_timeout = __commonJS({
  "node_modules/mongodb/lib/timeout.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LegacyTimeoutContext = exports2.CSOTTimeoutContext = exports2.TimeoutContext = exports2.Timeout = exports2.TimeoutError = void 0;
    var timers_1 = require("timers");
    var error_1 = require_error();
    var utils_1 = require_utils();
    var TimeoutError = class extends Error {
      get name() {
        return "TimeoutError";
      }
      constructor(message, options) {
        super(message, options);
        this.duration = options.duration;
      }
      static is(error51) {
        return error51 != null && typeof error51 === "object" && "name" in error51 && error51.name === "TimeoutError";
      }
    };
    exports2.TimeoutError = TimeoutError;
    var Timeout = class _Timeout extends Promise {
      get remainingTime() {
        if (this.timedOut)
          return 0;
        if (this.duration === 0)
          return Infinity;
        return this.start + this.duration - Math.trunc(performance.now());
      }
      get timeElapsed() {
        return Math.trunc(performance.now()) - this.start;
      }
      /** Create a new timeout that expires in `duration` ms */
      constructor(executor = () => null, options) {
        const duration3 = options?.duration ?? 0;
        const unref = !!options?.unref;
        const rejection = options?.rejection;
        if (duration3 < 0) {
          throw new error_1.MongoInvalidArgumentError("Cannot create a Timeout with a negative duration");
        }
        let reject;
        super((_, promiseReject) => {
          reject = promiseReject;
          executor(utils_1.noop, promiseReject);
        });
        this.ended = null;
        this.timedOut = false;
        this.cleared = false;
        this.duration = duration3;
        this.start = Math.trunc(performance.now());
        if (rejection == null && this.duration > 0) {
          this.id = (0, timers_1.setTimeout)(() => {
            this.ended = Math.trunc(performance.now());
            this.timedOut = true;
            reject(new TimeoutError(`Expired after ${duration3}ms`, { duration: duration3 }));
          }, this.duration);
          if (typeof this.id.unref === "function" && unref) {
            this.id.unref();
          }
        } else if (rejection != null) {
          this.ended = Math.trunc(performance.now());
          this.timedOut = true;
          reject(rejection);
        }
      }
      /**
       * Clears the underlying timeout. This method is idempotent
       */
      clear() {
        (0, timers_1.clearTimeout)(this.id);
        this.id = void 0;
        this.timedOut = false;
        this.cleared = true;
      }
      throwIfExpired() {
        if (this.timedOut) {
          this.then(void 0, utils_1.squashError);
          throw new TimeoutError("Timed out", { duration: this.duration });
        }
      }
      static expires(duration3, unref) {
        return new _Timeout(void 0, { duration: duration3, unref });
      }
      static reject(rejection) {
        return new _Timeout(void 0, { duration: 0, unref: true, rejection });
      }
    };
    exports2.Timeout = Timeout;
    function isLegacyTimeoutContextOptions(v) {
      return v != null && typeof v === "object" && "serverSelectionTimeoutMS" in v && typeof v.serverSelectionTimeoutMS === "number" && "waitQueueTimeoutMS" in v && typeof v.waitQueueTimeoutMS === "number";
    }
    function isCSOTTimeoutContextOptions(v) {
      return v != null && typeof v === "object" && "serverSelectionTimeoutMS" in v && typeof v.serverSelectionTimeoutMS === "number" && "timeoutMS" in v && typeof v.timeoutMS === "number";
    }
    var TimeoutContext = class {
      static create(options) {
        if (options.session?.timeoutContext != null)
          return options.session?.timeoutContext;
        if (isCSOTTimeoutContextOptions(options))
          return new CSOTTimeoutContext(options);
        else if (isLegacyTimeoutContextOptions(options))
          return new LegacyTimeoutContext(options);
        else
          throw new error_1.MongoRuntimeError("Unrecognized options");
      }
    };
    exports2.TimeoutContext = TimeoutContext;
    var CSOTTimeoutContext = class _CSOTTimeoutContext extends TimeoutContext {
      constructor(options) {
        super();
        this.minRoundTripTime = 0;
        this.start = Math.trunc(performance.now());
        this.timeoutMS = options.timeoutMS;
        this.serverSelectionTimeoutMS = options.serverSelectionTimeoutMS;
        this.socketTimeoutMS = options.socketTimeoutMS;
        this.clearServerSelectionTimeout = false;
      }
      get maxTimeMS() {
        return this.remainingTimeMS - this.minRoundTripTime;
      }
      get remainingTimeMS() {
        const timePassed = Math.trunc(performance.now()) - this.start;
        return this.timeoutMS <= 0 ? Infinity : this.timeoutMS - timePassed;
      }
      csotEnabled() {
        return true;
      }
      get serverSelectionTimeout() {
        if (typeof this._serverSelectionTimeout !== "object" || this._serverSelectionTimeout?.cleared) {
          const { remainingTimeMS, serverSelectionTimeoutMS } = this;
          if (remainingTimeMS <= 0)
            return Timeout.reject(new error_1.MongoOperationTimeoutError(`Timed out in server selection after ${this.timeoutMS}ms`));
          const usingServerSelectionTimeoutMS = serverSelectionTimeoutMS !== 0 && (0, utils_1.csotMin)(remainingTimeMS, serverSelectionTimeoutMS) === serverSelectionTimeoutMS;
          if (usingServerSelectionTimeoutMS) {
            this._serverSelectionTimeout = Timeout.expires(serverSelectionTimeoutMS);
          } else {
            if (remainingTimeMS > 0 && Number.isFinite(remainingTimeMS)) {
              this._serverSelectionTimeout = Timeout.expires(remainingTimeMS);
            } else {
              this._serverSelectionTimeout = null;
            }
          }
        }
        return this._serverSelectionTimeout;
      }
      get connectionCheckoutTimeout() {
        if (typeof this._connectionCheckoutTimeout !== "object" || this._connectionCheckoutTimeout?.cleared) {
          if (typeof this._serverSelectionTimeout === "object") {
            this._connectionCheckoutTimeout = this._serverSelectionTimeout;
          } else {
            throw new error_1.MongoRuntimeError("Unreachable. If you are seeing this error, please file a ticket on the NODE driver project on Jira");
          }
        }
        return this._connectionCheckoutTimeout;
      }
      get timeoutForSocketWrite() {
        const { remainingTimeMS } = this;
        if (!Number.isFinite(remainingTimeMS))
          return null;
        if (remainingTimeMS > 0)
          return Timeout.expires(remainingTimeMS);
        return Timeout.reject(new error_1.MongoOperationTimeoutError("Timed out before socket write"));
      }
      get timeoutForSocketRead() {
        const { remainingTimeMS } = this;
        if (!Number.isFinite(remainingTimeMS))
          return null;
        if (remainingTimeMS > 0)
          return Timeout.expires(remainingTimeMS);
        return Timeout.reject(new error_1.MongoOperationTimeoutError("Timed out before socket read"));
      }
      refresh() {
        this.start = Math.trunc(performance.now());
        this.minRoundTripTime = 0;
        this._serverSelectionTimeout?.clear();
        this._connectionCheckoutTimeout?.clear();
      }
      clear() {
        this._serverSelectionTimeout?.clear();
        this._connectionCheckoutTimeout?.clear();
      }
      /**
       * @internal
       * Throws a MongoOperationTimeoutError if the context has expired.
       * If the context has not expired, returns the `remainingTimeMS`
       **/
      getRemainingTimeMSOrThrow(message) {
        const { remainingTimeMS } = this;
        if (remainingTimeMS <= 0)
          throw new error_1.MongoOperationTimeoutError(message ?? `Expired after ${this.timeoutMS}ms`);
        return remainingTimeMS;
      }
      /**
       * @internal
       * This method is intended to be used in situations where concurrent operation are on the same deadline, but cannot share a single `TimeoutContext` instance.
       * Returns a new instance of `CSOTTimeoutContext` constructed with identical options, but setting the `start` property to `this.start`.
       */
      clone() {
        const timeoutContext = new _CSOTTimeoutContext({
          timeoutMS: this.timeoutMS,
          serverSelectionTimeoutMS: this.serverSelectionTimeoutMS
        });
        timeoutContext.start = this.start;
        return timeoutContext;
      }
      refreshed() {
        return new _CSOTTimeoutContext(this);
      }
      addMaxTimeMSToCommand(command, options) {
        if (options.omitMaxTimeMS)
          return;
        const maxTimeMS = this.remainingTimeMS - this.minRoundTripTime;
        if (maxTimeMS > 0 && Number.isFinite(maxTimeMS))
          command.maxTimeMS = maxTimeMS;
      }
      getSocketTimeoutMS() {
        return 0;
      }
    };
    exports2.CSOTTimeoutContext = CSOTTimeoutContext;
    var LegacyTimeoutContext = class _LegacyTimeoutContext extends TimeoutContext {
      constructor(options) {
        super();
        this.options = options;
        this.clearServerSelectionTimeout = true;
      }
      csotEnabled() {
        return false;
      }
      get serverSelectionTimeout() {
        if (this.options.serverSelectionTimeoutMS != null && this.options.serverSelectionTimeoutMS > 0)
          return Timeout.expires(this.options.serverSelectionTimeoutMS);
        return null;
      }
      get connectionCheckoutTimeout() {
        if (this.options.waitQueueTimeoutMS != null && this.options.waitQueueTimeoutMS > 0)
          return Timeout.expires(this.options.waitQueueTimeoutMS);
        return null;
      }
      get timeoutForSocketWrite() {
        return null;
      }
      get timeoutForSocketRead() {
        return null;
      }
      refresh() {
        return;
      }
      clear() {
        return;
      }
      get maxTimeMS() {
        return null;
      }
      refreshed() {
        return new _LegacyTimeoutContext(this.options);
      }
      addMaxTimeMSToCommand(_command, _options) {
      }
      getSocketTimeoutMS() {
        return this.options.socketTimeoutMS;
      }
    };
    exports2.LegacyTimeoutContext = LegacyTimeoutContext;
  }
});

// node_modules/mongodb/lib/explain.js
var require_explain = __commonJS({
  "node_modules/mongodb/lib/explain.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Explain = exports2.ExplainVerbosity = void 0;
    exports2.validateExplainTimeoutOptions = validateExplainTimeoutOptions;
    exports2.decorateWithExplain = decorateWithExplain;
    var error_1 = require_error();
    exports2.ExplainVerbosity = Object.freeze({
      queryPlanner: "queryPlanner",
      queryPlannerExtended: "queryPlannerExtended",
      executionStats: "executionStats",
      allPlansExecution: "allPlansExecution"
    });
    var Explain = class _Explain {
      constructor(verbosity, maxTimeMS) {
        if (typeof verbosity === "boolean") {
          this.verbosity = verbosity ? exports2.ExplainVerbosity.allPlansExecution : exports2.ExplainVerbosity.queryPlanner;
        } else {
          this.verbosity = verbosity;
        }
        this.maxTimeMS = maxTimeMS;
      }
      static fromOptions({ explain } = {}) {
        if (explain == null)
          return;
        if (typeof explain === "boolean" || typeof explain === "string") {
          return new _Explain(explain);
        }
        const { verbosity, maxTimeMS } = explain;
        return new _Explain(verbosity, maxTimeMS);
      }
    };
    exports2.Explain = Explain;
    function validateExplainTimeoutOptions(options, explain) {
      const { maxTimeMS, timeoutMS } = options;
      if (timeoutMS != null && (maxTimeMS != null || explain?.maxTimeMS != null)) {
        throw new error_1.MongoAPIError("Cannot use maxTimeMS with timeoutMS for explain commands.");
      }
    }
    function decorateWithExplain(command, explain) {
      const { verbosity, maxTimeMS } = explain;
      const baseCommand = { explain: command, verbosity };
      if (typeof maxTimeMS === "number") {
        baseCommand.maxTimeMS = maxTimeMS;
      }
      return baseCommand;
    }
  }
});

// node_modules/mongodb/lib/operations/operation.js
var require_operation = __commonJS({
  "node_modules/mongodb/lib/operations/operation.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AbstractOperation = exports2.Aspect = void 0;
    exports2.defineAspects = defineAspects;
    var bson_1 = require_bson2();
    var read_preference_1 = require_read_preference();
    exports2.Aspect = {
      READ_OPERATION: /* @__PURE__ */ Symbol("READ_OPERATION"),
      WRITE_OPERATION: /* @__PURE__ */ Symbol("WRITE_OPERATION"),
      RETRYABLE: /* @__PURE__ */ Symbol("RETRYABLE"),
      EXPLAINABLE: /* @__PURE__ */ Symbol("EXPLAINABLE"),
      SKIP_COLLATION: /* @__PURE__ */ Symbol("SKIP_COLLATION"),
      CURSOR_CREATING: /* @__PURE__ */ Symbol("CURSOR_CREATING"),
      MUST_SELECT_SAME_SERVER: /* @__PURE__ */ Symbol("MUST_SELECT_SAME_SERVER"),
      COMMAND_BATCHING: /* @__PURE__ */ Symbol("COMMAND_BATCHING"),
      SUPPORTS_RAW_DATA: /* @__PURE__ */ Symbol("SUPPORTS_RAW_DATA")
    };
    var AbstractOperation = class {
      constructor(options = {}) {
        this.readPreference = this.hasAspect(exports2.Aspect.WRITE_OPERATION) ? read_preference_1.ReadPreference.primary : read_preference_1.ReadPreference.fromOptions(options) ?? read_preference_1.ReadPreference.primary;
        this.bsonOptions = (0, bson_1.resolveBSONOptions)(options);
        this._session = options.session != null ? options.session : void 0;
        this.options = options;
        this.bypassPinningCheck = !!options.bypassPinningCheck;
        this.attemptsMade = 0;
      }
      hasAspect(aspect) {
        const ctor = this.constructor;
        if (ctor.aspects == null) {
          return false;
        }
        return ctor.aspects.has(aspect);
      }
      // Make sure the session is not writable from outside this class.
      get session() {
        return this._session;
      }
      set session(session) {
        this._session = session;
      }
      clearSession() {
        this._session = void 0;
      }
      resetBatch() {
        return true;
      }
      get canRetryRead() {
        return this.hasAspect(exports2.Aspect.RETRYABLE) && this.hasAspect(exports2.Aspect.READ_OPERATION);
      }
      get canRetryWrite() {
        return this.hasAspect(exports2.Aspect.RETRYABLE) && this.hasAspect(exports2.Aspect.WRITE_OPERATION);
      }
      /**
       * Given an instance of a MongoDBResponse, map the response to the correct result type.  For
       * example, a `CountOperation` might map the response as follows:
       *
       * ```typescript
       *  override handleOk(response: InstanceType<typeof this.SERVER_COMMAND_RESPONSE_TYPE>): TResult {
       *    return response.toObject(this.bsonOptions).n ?? 0;
       *  }
       *
       *  // or, with type safety:
       *  override handleOk(response: InstanceType<typeof this.SERVER_COMMAND_RESPONSE_TYPE>): TResult {
       *    return response.getNumber('n') ?? 0;
       *  }
       * ```
       */
      handleOk(response) {
        return response.toObject(this.bsonOptions);
      }
      /**
       * Optional.
       *
       * If the operation performs error handling, such as wrapping, renaming the error, or squashing errors
       * this method can be overridden.
       */
      handleError(error51) {
        throw error51;
      }
    };
    exports2.AbstractOperation = AbstractOperation;
    function defineAspects(operation, aspects) {
      if (!Array.isArray(aspects) && !(aspects instanceof Set)) {
        aspects = [aspects];
      }
      aspects = new Set(aspects);
      Object.defineProperty(operation, "aspects", {
        value: aspects,
        writable: false
      });
      return aspects;
    }
  }
});

// node_modules/mongodb/lib/operations/command.js
var require_command = __commonJS({
  "node_modules/mongodb/lib/operations/command.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CommandOperation = void 0;
    var constants_1 = require_constants();
    var error_1 = require_error();
    var explain_1 = require_explain();
    var read_concern_1 = require_read_concern();
    var utils_1 = require_utils();
    var write_concern_1 = require_write_concern();
    var operation_1 = require_operation();
    var CommandOperation = class extends operation_1.AbstractOperation {
      constructor(parent, options) {
        super(options);
        this.options = options ?? {};
        const dbNameOverride = options?.dbName || options?.authdb;
        if (dbNameOverride) {
          this.ns = new utils_1.MongoDBNamespace(dbNameOverride, "$cmd");
        } else {
          this.ns = parent ? parent.s.namespace.withCollection("$cmd") : new utils_1.MongoDBNamespace("admin", "$cmd");
        }
        this.readConcern = read_concern_1.ReadConcern.fromOptions(options);
        this.writeConcern = write_concern_1.WriteConcern.fromOptions(options);
        if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) {
          this.explain = explain_1.Explain.fromOptions(options);
          if (this.explain)
            (0, explain_1.validateExplainTimeoutOptions)(this.options, this.explain);
        } else if (options?.explain != null) {
          throw new error_1.MongoInvalidArgumentError(`Option "explain" is not supported on this command`);
        }
      }
      get canRetryWrite() {
        if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) {
          return this.explain == null;
        }
        return super.canRetryWrite;
      }
      buildOptions(timeoutContext) {
        return {
          ...this.options,
          ...this.bsonOptions,
          timeoutContext,
          readPreference: this.readPreference,
          session: this.session
        };
      }
      buildCommand(connection, session) {
        const command = this.buildCommandDocument(connection, session);
        const inTransaction = this.session && this.session.inTransaction();
        if (this.readConcern && (0, utils_1.commandSupportsReadConcern)(command) && !inTransaction) {
          Object.assign(command, { readConcern: this.readConcern });
        }
        if (this.writeConcern && this.hasAspect(operation_1.Aspect.WRITE_OPERATION) && !inTransaction) {
          write_concern_1.WriteConcern.apply(command, this.writeConcern);
        }
        if (this.options.collation && typeof this.options.collation === "object" && !this.hasAspect(operation_1.Aspect.SKIP_COLLATION)) {
          Object.assign(command, { collation: this.options.collation });
        }
        if (typeof this.options.maxTimeMS === "number") {
          command.maxTimeMS = this.options.maxTimeMS;
        }
        if (this.options.rawData != null && this.hasAspect(operation_1.Aspect.SUPPORTS_RAW_DATA) && (0, utils_1.maxWireVersion)(connection) >= constants_1.MIN_SUPPORTED_RAW_DATA_WIRE_VERSION) {
          command.rawData = this.options.rawData;
        }
        if (this.hasAspect(operation_1.Aspect.EXPLAINABLE) && this.explain) {
          return (0, explain_1.decorateWithExplain)(command, this.explain);
        }
        return command;
      }
    };
    exports2.CommandOperation = CommandOperation;
  }
});

// node_modules/mongodb/lib/operations/aggregate.js
var require_aggregate = __commonJS({
  "node_modules/mongodb/lib/operations/aggregate.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AggregateOperation = exports2.DB_AGGREGATE_COLLECTION = void 0;
    var responses_1 = require_responses();
    var error_1 = require_error();
    var write_concern_1 = require_write_concern();
    var command_1 = require_command();
    var operation_1 = require_operation();
    exports2.DB_AGGREGATE_COLLECTION = 1;
    var AggregateOperation = class extends command_1.CommandOperation {
      constructor(ns, pipeline2, options) {
        super(void 0, { ...options, dbName: ns.db });
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.CursorResponse;
        this.options = { ...options };
        this.target = ns.collection || exports2.DB_AGGREGATE_COLLECTION;
        this.pipeline = pipeline2;
        this.hasWriteStage = false;
        if (typeof options?.out === "string") {
          this.pipeline = this.pipeline.concat({ $out: options.out });
          this.hasWriteStage = true;
        } else if (pipeline2.length > 0) {
          const finalStage = pipeline2[pipeline2.length - 1];
          if (finalStage.$out || finalStage.$merge) {
            this.hasWriteStage = true;
          }
        }
        if (!this.hasWriteStage) {
          delete this.options.writeConcern;
        }
        if (options?.cursor != null && typeof options.cursor !== "object") {
          throw new error_1.MongoInvalidArgumentError("Cursor options must be an object");
        }
        this.SERVER_COMMAND_RESPONSE_TYPE = this.explain ? responses_1.ExplainedCursorResponse : responses_1.CursorResponse;
      }
      get commandName() {
        return "aggregate";
      }
      get canRetryRead() {
        return !this.hasWriteStage;
      }
      addToPipeline(stage) {
        this.pipeline.push(stage);
      }
      buildCommandDocument() {
        const options = this.options;
        const command = { aggregate: this.target, pipeline: this.pipeline };
        if (this.hasWriteStage && this.writeConcern) {
          write_concern_1.WriteConcern.apply(command, this.writeConcern);
        }
        if (options.bypassDocumentValidation === true) {
          command.bypassDocumentValidation = options.bypassDocumentValidation;
        }
        if (typeof options.allowDiskUse === "boolean") {
          command.allowDiskUse = options.allowDiskUse;
        }
        if (options.hint) {
          command.hint = options.hint;
        }
        if (options.let) {
          command.let = options.let;
        }
        if (options.comment !== void 0) {
          command.comment = options.comment;
        }
        command.cursor = options.cursor || {};
        if (options.batchSize && !this.hasWriteStage) {
          command.cursor.batchSize = options.batchSize;
        }
        return command;
      }
      handleOk(response) {
        return response;
      }
    };
    exports2.AggregateOperation = AggregateOperation;
    (0, operation_1.defineAspects)(AggregateOperation, [
      operation_1.Aspect.READ_OPERATION,
      operation_1.Aspect.RETRYABLE,
      operation_1.Aspect.EXPLAINABLE,
      operation_1.Aspect.CURSOR_CREATING,
      operation_1.Aspect.SUPPORTS_RAW_DATA
    ]);
  }
});

// node_modules/mongodb/lib/operations/run_command.js
var require_run_command = __commonJS({
  "node_modules/mongodb/lib/operations/run_command.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RunCursorCommandOperation = exports2.RunCommandOperation = void 0;
    var responses_1 = require_responses();
    var operation_1 = require_operation();
    var RunCommandOperation = class extends operation_1.AbstractOperation {
      constructor(namespace, command, options) {
        super(options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.command = command;
        this.options = options;
        this.ns = namespace.withCollection("$cmd");
      }
      get commandName() {
        return "runCommand";
      }
      buildCommand(_connection, _session) {
        return this.command;
      }
      buildOptions(timeoutContext) {
        return {
          ...this.options,
          session: this.session,
          timeoutContext,
          signal: this.options.signal,
          readPreference: this.options.readPreference
        };
      }
    };
    exports2.RunCommandOperation = RunCommandOperation;
    var RunCursorCommandOperation = class extends RunCommandOperation {
      constructor() {
        super(...arguments);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.CursorResponse;
      }
      handleOk(response) {
        return response;
      }
    };
    exports2.RunCursorCommandOperation = RunCursorCommandOperation;
  }
});

// node_modules/mongodb/lib/operations/execute_operation.js
var require_execute_operation = __commonJS({
  "node_modules/mongodb/lib/operations/execute_operation.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.executeOperation = executeOperation;
    exports2.autoConnect = autoConnect;
    var promises_1 = require("timers/promises");
    var constants_1 = require_constants();
    var error_1 = require_error();
    var read_preference_1 = require_read_preference();
    var common_1 = require_common();
    var server_selection_1 = require_server_selection();
    var timeout_1 = require_timeout();
    var utils_1 = require_utils();
    var aggregate_1 = require_aggregate();
    var operation_1 = require_operation();
    var run_command_1 = require_run_command();
    var MMAPv1_RETRY_WRITES_ERROR_CODE = error_1.MONGODB_ERROR_CODES.IllegalOperation;
    var MMAPv1_RETRY_WRITES_ERROR_MESSAGE = "This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.";
    async function executeOperation(client, operation, timeoutContext) {
      if (!(operation instanceof operation_1.AbstractOperation)) {
        throw new error_1.MongoRuntimeError("This method requires a valid operation instance");
      }
      const topology = client.topology == null ? await (0, utils_1.abortable)(autoConnect(client), operation.options) : client.topology;
      let session = operation.session;
      let owner;
      if (session == null) {
        owner = /* @__PURE__ */ Symbol();
        session = client.startSession({ owner, explicit: false });
      } else if (session.hasEnded) {
        throw new error_1.MongoExpiredSessionError("Use of expired sessions is not permitted");
      } else if (session.snapshotEnabled && (0, utils_1.maxWireVersion)(topology) < constants_1.MIN_SUPPORTED_SNAPSHOT_READS_WIRE_VERSION) {
        throw new error_1.MongoCompatibilityError("Snapshot reads require MongoDB 5.0 or later");
      } else if (session.client !== client) {
        throw new error_1.MongoInvalidArgumentError("ClientSession must be from the same MongoClient");
      }
      operation.session ??= session;
      const readPreference = operation.readPreference ?? read_preference_1.ReadPreference.primary;
      const inTransaction = !!session?.inTransaction();
      const hasReadAspect = operation.hasAspect(operation_1.Aspect.READ_OPERATION);
      if (inTransaction && !readPreference.equals(read_preference_1.ReadPreference.primary) && (hasReadAspect || operation.commandName === "runCommand")) {
        throw new error_1.MongoTransactionError(`Read preference in a transaction must be primary, not: ${readPreference.mode}`);
      }
      if (session?.isPinned && session.transaction.isCommitted && !operation.bypassPinningCheck) {
        session.unpin();
      }
      timeoutContext ??= timeout_1.TimeoutContext.create({
        session,
        serverSelectionTimeoutMS: client.s.options.serverSelectionTimeoutMS,
        waitQueueTimeoutMS: client.s.options.waitQueueTimeoutMS,
        timeoutMS: operation.options.timeoutMS
      });
      try {
        return await executeOperationWithRetries(operation, {
          topology,
          timeoutContext,
          session,
          readPreference
        });
      } finally {
        if (session?.owner != null && session.owner === owner) {
          await session.endSession();
        }
      }
    }
    async function autoConnect(client) {
      if (client.topology == null) {
        if (client.s.hasBeenClosed) {
          throw new error_1.MongoNotConnectedError("Client must be connected before running operations");
        }
        client.s.options.__skipPingOnConnect = true;
        try {
          await client.connect();
          if (client.topology == null) {
            throw new error_1.MongoRuntimeError("client.connect did not create a topology but also did not throw");
          }
          return client.topology;
        } finally {
          delete client.s.options.__skipPingOnConnect;
        }
      }
      return client.topology;
    }
    var BASE_BACKOFF_MS = 100;
    var MAX_BACKOFF_MS = 1e4;
    async function executeOperationWithRetries(operation, { topology, timeoutContext, session, readPreference }) {
      let selector;
      if (operation.hasAspect(operation_1.Aspect.MUST_SELECT_SAME_SERVER)) {
        selector = (0, server_selection_1.sameServerSelector)(operation.server?.description);
      } else if (operation instanceof aggregate_1.AggregateOperation && operation.hasWriteStage) {
        selector = (0, server_selection_1.secondaryWritableServerSelector)(topology.commonWireVersion, readPreference);
      } else {
        selector = readPreference;
      }
      let server = await topology.selectServer(selector, {
        session,
        operationName: operation.commandName,
        timeoutContext,
        signal: operation.options.signal,
        deprioritizedServers: new server_selection_1.DeprioritizedServers()
      });
      const hasReadAspect = operation.hasAspect(operation_1.Aspect.READ_OPERATION);
      const hasWriteAspect = operation.hasAspect(operation_1.Aspect.WRITE_OPERATION);
      const inTransaction = session?.inTransaction() ?? false;
      const willRetryRead = topology.s.options.retryReads && !inTransaction && operation.canRetryRead;
      const willRetryWrite = topology.s.options.retryWrites && !inTransaction && (0, utils_1.supportsRetryableWrites)(server) && operation.canRetryWrite;
      const willRetry = operation.hasAspect(operation_1.Aspect.RETRYABLE) && session != null && (hasReadAspect && willRetryRead || hasWriteAspect && willRetryWrite);
      if (hasWriteAspect && willRetryWrite && session != null) {
        operation.options.willRetryWrite = true;
        session.incrementTransactionNumber();
      }
      const deprioritizedServers = new server_selection_1.DeprioritizedServers();
      let maxAttempts = typeof operation.maxAttempts === "number" ? operation.maxAttempts : willRetry ? timeoutContext.csotEnabled() ? Infinity : 2 : 1;
      let error51 = null;
      for (let attempt = 0; attempt < maxAttempts; attempt++) {
        operation.attemptsMade = attempt + 1;
        operation.server = server;
        try {
          try {
            const result = await server.command(operation, timeoutContext);
            return operation.handleOk(result);
          } catch (error52) {
            return operation.handleError(error52);
          }
        } catch (operationError) {
          if (!(operationError instanceof error_1.MongoError))
            throw operationError;
          if (error51 == null) {
            error51 = operationError;
          } else {
            if (!operationError.hasErrorLabel(error_1.MongoErrorLabel.NoWritesPerformed)) {
              error51 = operationError;
            }
          }
          timeoutContext.clear();
          if (hasWriteAspect && operationError.code === MMAPv1_RETRY_WRITES_ERROR_CODE) {
            throw new error_1.MongoServerError({
              message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE,
              errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE,
              originalError: operationError
            });
          }
          if (!canRetry(operation, operationError)) {
            throw error51;
          }
          if (operationError.hasErrorLabel(error_1.MongoErrorLabel.SystemOverloadedError)) {
            const maxOverloadAttempts = topology.s.options.maxAdaptiveRetries + 1;
            maxAttempts = Math.min(maxOverloadAttempts, operation.maxAttempts ?? maxOverloadAttempts);
          }
          if (attempt + 1 >= maxAttempts) {
            throw error51;
          }
          if (operationError instanceof error_1.MongoNetworkError && operation.hasAspect(operation_1.Aspect.CURSOR_CREATING) && session != null && session.isPinned && !session.inTransaction()) {
            session.unpin({ force: true, forceClear: true });
          }
          if (operationError.hasErrorLabel(error_1.MongoErrorLabel.SystemOverloadedError) && operation.hasAspect(operation_1.Aspect.CURSOR_CREATING) && session != null && session.isPinned && !session.inTransaction()) {
            session.unpin({ force: true });
          }
          if (operationError.hasErrorLabel(error_1.MongoErrorLabel.SystemOverloadedError)) {
            const backoffMS = Math.random() * Math.min(MAX_BACKOFF_MS, BASE_BACKOFF_MS * 2 ** attempt);
            if (timeoutContext.csotEnabled() && backoffMS > timeoutContext.remainingTimeMS) {
              throw error51;
            }
            await (0, promises_1.setTimeout)(backoffMS);
          }
          if (topology.description.type === common_1.TopologyType.Sharded || operationError.hasErrorLabel(error_1.MongoErrorLabel.SystemOverloadedError) && topology.s.options.enableOverloadRetargeting) {
            deprioritizedServers.add(server.description);
          }
          server = await topology.selectServer(selector, {
            session,
            operationName: operation.commandName,
            deprioritizedServers,
            signal: operation.options.signal
          });
          if (hasWriteAspect && !(0, utils_1.supportsRetryableWrites)(server) && !operationError.hasErrorLabel(error_1.MongoErrorLabel.SystemOverloadedError)) {
            throw new error_1.MongoUnexpectedServerResponseError("Selected server does not support retryable writes");
          }
          if (operation.hasAspect(operation_1.Aspect.COMMAND_BATCHING)) {
            operation.resetBatch();
          }
        }
      }
      throw error51 ?? new error_1.MongoRuntimeError("Should never happen: operation execution loop terminated but no error was recorded.");
      function canRetry(operation2, error52) {
        if (error52.hasErrorLabel(error_1.MongoErrorLabel.SystemOverloadedError) && error52.hasErrorLabel(error_1.MongoErrorLabel.RetryableError)) {
          if (operation2 instanceof run_command_1.RunCommandOperation) {
            return topology.s.options.retryReads && topology.s.options.retryWrites;
          }
          if (operation2 instanceof aggregate_1.AggregateOperation && operation2.hasWriteStage) {
            return topology.s.options.retryWrites;
          }
          const canRetryAsRead = hasReadAspect && topology.s.options.retryReads;
          const canRetryAsWrite = hasWriteAspect && topology.s.options.retryWrites;
          return canRetryAsRead || canRetryAsWrite;
        }
        if (operation2 instanceof run_command_1.RunCommandOperation) {
          return false;
        }
        if (operation2.hasAspect(operation_1.Aspect.COMMAND_BATCHING)) {
          return operation2.canRetryWrite && (0, error_1.isRetryableWriteError)(error52);
        }
        return hasWriteAspect && willRetryWrite && (0, error_1.isRetryableWriteError)(error52) || hasReadAspect && willRetryRead && (0, error_1.isRetryableReadError)(error52);
      }
    }
  }
});

// node_modules/mongodb/lib/operations/list_databases.js
var require_list_databases = __commonJS({
  "node_modules/mongodb/lib/operations/list_databases.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ListDatabasesOperation = void 0;
    var responses_1 = require_responses();
    var utils_1 = require_utils();
    var command_1 = require_command();
    var operation_1 = require_operation();
    var ListDatabasesOperation = class extends command_1.CommandOperation {
      constructor(db, options) {
        super(db, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.options = options ?? {};
        this.ns = new utils_1.MongoDBNamespace("admin", "$cmd");
      }
      get commandName() {
        return "listDatabases";
      }
      buildCommandDocument(connection, _session) {
        const cmd = { listDatabases: 1 };
        if (typeof this.options.nameOnly === "boolean") {
          cmd.nameOnly = this.options.nameOnly;
        }
        if (this.options.filter) {
          cmd.filter = this.options.filter;
        }
        if (typeof this.options.authorizedDatabases === "boolean") {
          cmd.authorizedDatabases = this.options.authorizedDatabases;
        }
        if ((0, utils_1.maxWireVersion)(connection) >= 9 && this.options.comment !== void 0) {
          cmd.comment = this.options.comment;
        }
        return cmd;
      }
    };
    exports2.ListDatabasesOperation = ListDatabasesOperation;
    (0, operation_1.defineAspects)(ListDatabasesOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE]);
  }
});

// node_modules/mongodb/lib/operations/remove_user.js
var require_remove_user = __commonJS({
  "node_modules/mongodb/lib/operations/remove_user.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RemoveUserOperation = void 0;
    var responses_1 = require_responses();
    var command_1 = require_command();
    var operation_1 = require_operation();
    var RemoveUserOperation = class extends command_1.CommandOperation {
      constructor(db, username, options) {
        super(db, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.options = options;
        this.username = username;
      }
      get commandName() {
        return "dropUser";
      }
      buildCommandDocument(_connection) {
        return { dropUser: this.username };
      }
      handleOk(_response) {
        return true;
      }
    };
    exports2.RemoveUserOperation = RemoveUserOperation;
    (0, operation_1.defineAspects)(RemoveUserOperation, [operation_1.Aspect.WRITE_OPERATION]);
  }
});

// node_modules/mongodb/lib/operations/validate_collection.js
var require_validate_collection = __commonJS({
  "node_modules/mongodb/lib/operations/validate_collection.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ValidateCollectionOperation = void 0;
    var responses_1 = require_responses();
    var error_1 = require_error();
    var command_1 = require_command();
    var ValidateCollectionOperation = class extends command_1.CommandOperation {
      constructor(admin, collectionName, options) {
        super(admin.s.db, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.options = options;
        this.collectionName = collectionName;
      }
      get commandName() {
        return "validate";
      }
      buildCommandDocument(_connection, _session) {
        return {
          validate: this.collectionName,
          ...Object.fromEntries(Object.entries(this.options).filter((entry) => entry[0] !== "session"))
        };
      }
      handleOk(response) {
        const result = super.handleOk(response);
        if (result.result != null && typeof result.result !== "string")
          throw new error_1.MongoUnexpectedServerResponseError("Error with validation data");
        if (result.result != null && result.result.match(/exception|corrupt/) != null)
          throw new error_1.MongoUnexpectedServerResponseError(`Invalid collection ${this.collectionName}`);
        if (result.valid != null && !result.valid)
          throw new error_1.MongoUnexpectedServerResponseError(`Invalid collection ${this.collectionName}`);
        return response;
      }
    };
    exports2.ValidateCollectionOperation = ValidateCollectionOperation;
  }
});

// node_modules/mongodb/lib/admin.js
var require_admin = __commonJS({
  "node_modules/mongodb/lib/admin.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Admin = void 0;
    var bson_1 = require_bson2();
    var execute_operation_1 = require_execute_operation();
    var list_databases_1 = require_list_databases();
    var remove_user_1 = require_remove_user();
    var run_command_1 = require_run_command();
    var validate_collection_1 = require_validate_collection();
    var utils_1 = require_utils();
    var Admin = class {
      /**
       * Create a new Admin instance
       * @internal
       */
      constructor(db) {
        this.s = { db };
      }
      /**
       * Execute a command
       *
       * The driver will ensure the following fields are attached to the command sent to the server:
       * - `lsid` - sourced from an implicit session or options.session
       * - `$readPreference` - defaults to primary or can be configured by options.readPreference
       * - `$db` - sourced from the name of this database
       *
       * If the client has a serverApi setting:
       * - `apiVersion`
       * - `apiStrict`
       * - `apiDeprecationErrors`
       *
       * When in a transaction:
       * - `readConcern` - sourced from readConcern set on the TransactionOptions
       * - `writeConcern` - sourced from writeConcern set on the TransactionOptions
       *
       * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value.
       *
       * @param command - The command to execute
       * @param options - Optional settings for the command
       */
      async command(command, options) {
        return await (0, execute_operation_1.executeOperation)(this.s.db.client, new run_command_1.RunCommandOperation(new utils_1.MongoDBNamespace("admin"), command, {
          ...(0, bson_1.resolveBSONOptions)(options),
          session: options?.session,
          readPreference: options?.readPreference,
          timeoutMS: options?.timeoutMS ?? this.s.db.timeoutMS
        }));
      }
      /**
       * Retrieve the server build information
       *
       * @param options - Optional settings for the command
       */
      async buildInfo(options) {
        return await this.command({ buildinfo: 1 }, options);
      }
      /**
       * Retrieve the server build information
       *
       * @param options - Optional settings for the command
       */
      async serverInfo(options) {
        return await this.command({ buildinfo: 1 }, options);
      }
      /**
       * Retrieve this db's server status.
       *
       * @param options - Optional settings for the command
       */
      async serverStatus(options) {
        return await this.command({ serverStatus: 1 }, options);
      }
      /**
       * Ping the MongoDB server and retrieve results
       *
       * @param options - Optional settings for the command
       */
      async ping(options) {
        return await this.command({ ping: 1 }, options);
      }
      /**
       * Remove a user from a database
       *
       * @param username - The username to remove
       * @param options - Optional settings for the command
       */
      async removeUser(username, options) {
        return await (0, execute_operation_1.executeOperation)(this.s.db.client, new remove_user_1.RemoveUserOperation(this.s.db, username, { dbName: "admin", ...options }));
      }
      /**
       * Validate an existing collection
       *
       * @param collectionName - The name of the collection to validate.
       * @param options - Optional settings for the command
       */
      async validateCollection(collectionName, options = {}) {
        return await (0, execute_operation_1.executeOperation)(this.s.db.client, new validate_collection_1.ValidateCollectionOperation(this, collectionName, options));
      }
      /**
       * List the available databases
       *
       * @param options - Optional settings for the command
       */
      async listDatabases(options) {
        return await (0, execute_operation_1.executeOperation)(this.s.db.client, new list_databases_1.ListDatabasesOperation(this.s.db, { timeoutMS: this.s.db.timeoutMS, ...options }));
      }
      /**
       * Get ReplicaSet status
       *
       * @param options - Optional settings for the command
       */
      async replSetGetStatus(options) {
        return await this.command({ replSetGetStatus: 1 }, options);
      }
    };
    exports2.Admin = Admin;
  }
});

// node_modules/mongodb/lib/operations/delete.js
var require_delete = __commonJS({
  "node_modules/mongodb/lib/operations/delete.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DeleteManyOperation = exports2.DeleteOneOperation = exports2.DeleteOperation = void 0;
    exports2.makeDeleteStatement = makeDeleteStatement;
    var responses_1 = require_responses();
    var error_1 = require_error();
    var utils_1 = require_utils();
    var command_1 = require_command();
    var operation_1 = require_operation();
    var DeleteOperation = class extends command_1.CommandOperation {
      constructor(ns, statements, options) {
        super(void 0, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.options = options;
        this.ns = ns;
        this.statements = statements;
      }
      get commandName() {
        return "delete";
      }
      get canRetryWrite() {
        if (super.canRetryWrite === false) {
          return false;
        }
        return this.statements.every((op) => op.limit != null ? op.limit > 0 : true);
      }
      buildCommandDocument(connection, _session) {
        const options = this.options;
        const ordered = typeof options.ordered === "boolean" ? options.ordered : true;
        const command = {
          delete: this.ns.collection,
          deletes: this.statements,
          ordered
        };
        if (options.let) {
          command.let = options.let;
        }
        if (options.comment !== void 0) {
          command.comment = options.comment;
        }
        const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0;
        if (unacknowledgedWrite && (0, utils_1.maxWireVersion)(connection) < 9) {
          if (this.statements.find((o) => o.hint)) {
            throw new error_1.MongoCompatibilityError(`hint for the delete command is only supported on MongoDB 4.4+`);
          }
        }
        return command;
      }
    };
    exports2.DeleteOperation = DeleteOperation;
    var DeleteOneOperation = class extends DeleteOperation {
      constructor(ns, filter, options) {
        super(ns, [makeDeleteStatement(filter, { ...options, limit: 1 })], options);
      }
      handleOk(response) {
        const res = super.handleOk(response);
        if (this.explain)
          return res;
        if (res.code)
          throw new error_1.MongoServerError(res);
        if (res.writeErrors)
          throw new error_1.MongoServerError(res.writeErrors[0]);
        return {
          acknowledged: this.writeConcern?.w !== 0,
          deletedCount: res.n
        };
      }
    };
    exports2.DeleteOneOperation = DeleteOneOperation;
    var DeleteManyOperation = class extends DeleteOperation {
      constructor(ns, filter, options) {
        super(ns, [makeDeleteStatement(filter, options)], options);
      }
      handleOk(response) {
        const res = super.handleOk(response);
        if (this.explain)
          return res;
        if (res.code)
          throw new error_1.MongoServerError(res);
        if (res.writeErrors)
          throw new error_1.MongoServerError(res.writeErrors[0]);
        return {
          acknowledged: this.writeConcern?.w !== 0,
          deletedCount: res.n
        };
      }
    };
    exports2.DeleteManyOperation = DeleteManyOperation;
    function makeDeleteStatement(filter, options) {
      const op = {
        q: filter,
        limit: typeof options.limit === "number" ? options.limit : 0
      };
      if (options.collation) {
        op.collation = options.collation;
      }
      if (options.hint) {
        op.hint = options.hint;
      }
      return op;
    }
    (0, operation_1.defineAspects)(DeleteOperation, [
      operation_1.Aspect.RETRYABLE,
      operation_1.Aspect.WRITE_OPERATION,
      operation_1.Aspect.SUPPORTS_RAW_DATA
    ]);
    (0, operation_1.defineAspects)(DeleteOneOperation, [
      operation_1.Aspect.RETRYABLE,
      operation_1.Aspect.WRITE_OPERATION,
      operation_1.Aspect.EXPLAINABLE,
      operation_1.Aspect.SKIP_COLLATION,
      operation_1.Aspect.SUPPORTS_RAW_DATA
    ]);
    (0, operation_1.defineAspects)(DeleteManyOperation, [
      operation_1.Aspect.WRITE_OPERATION,
      operation_1.Aspect.EXPLAINABLE,
      operation_1.Aspect.SKIP_COLLATION,
      operation_1.Aspect.SUPPORTS_RAW_DATA
    ]);
  }
});

// node_modules/mongodb/lib/operations/insert.js
var require_insert = __commonJS({
  "node_modules/mongodb/lib/operations/insert.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.InsertOneOperation = exports2.InsertOperation = void 0;
    var responses_1 = require_responses();
    var error_1 = require_error();
    var utils_1 = require_utils();
    var command_1 = require_command();
    var operation_1 = require_operation();
    var InsertOperation = class extends command_1.CommandOperation {
      constructor(ns, documents, options) {
        super(void 0, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.options = { ...options, checkKeys: options.checkKeys ?? false };
        this.ns = ns;
        this.documents = documents;
      }
      get commandName() {
        return "insert";
      }
      buildCommandDocument(_connection, _session) {
        const options = this.options ?? {};
        const ordered = typeof options.ordered === "boolean" ? options.ordered : true;
        const command = {
          insert: this.ns.collection,
          documents: this.documents,
          ordered
        };
        if (typeof options.bypassDocumentValidation === "boolean") {
          command.bypassDocumentValidation = options.bypassDocumentValidation;
        }
        if (options.comment !== void 0) {
          command.comment = options.comment;
        }
        return command;
      }
    };
    exports2.InsertOperation = InsertOperation;
    var InsertOneOperation = class extends InsertOperation {
      constructor(collection, doc, options) {
        super(collection.s.namespace, [(0, utils_1.maybeAddIdToDocuments)(collection, doc, options)], options);
      }
      handleOk(response) {
        const res = super.handleOk(response);
        if (res.code)
          throw new error_1.MongoServerError(res);
        if (res.writeErrors) {
          throw new error_1.MongoServerError(res.writeErrors[0]);
        }
        return {
          acknowledged: this.writeConcern?.w !== 0,
          insertedId: this.documents[0]._id
        };
      }
    };
    exports2.InsertOneOperation = InsertOneOperation;
    (0, operation_1.defineAspects)(InsertOperation, [
      operation_1.Aspect.RETRYABLE,
      operation_1.Aspect.WRITE_OPERATION,
      operation_1.Aspect.SUPPORTS_RAW_DATA
    ]);
    (0, operation_1.defineAspects)(InsertOneOperation, [
      operation_1.Aspect.RETRYABLE,
      operation_1.Aspect.WRITE_OPERATION,
      operation_1.Aspect.SUPPORTS_RAW_DATA
    ]);
  }
});

// node_modules/mongodb/lib/sort.js
var require_sort = __commonJS({
  "node_modules/mongodb/lib/sort.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.formatSort = formatSort;
    var error_1 = require_error();
    function prepareDirection(direction = 1) {
      const value = `${direction}`.toLowerCase();
      if (isMeta(direction))
        return direction;
      switch (value) {
        case "ascending":
        case "asc":
        case "1":
          return 1;
        case "descending":
        case "desc":
        case "-1":
          return -1;
        default:
          throw new error_1.MongoInvalidArgumentError(`Invalid sort direction: ${JSON.stringify(direction)}`);
      }
    }
    function isMeta(t2) {
      return typeof t2 === "object" && t2 != null && "$meta" in t2 && typeof t2.$meta === "string";
    }
    function isPair(t2) {
      if (Array.isArray(t2) && t2.length === 2) {
        try {
          prepareDirection(t2[1]);
          return true;
        } catch {
          return false;
        }
      }
      return false;
    }
    function isDeep(t2) {
      return Array.isArray(t2) && Array.isArray(t2[0]);
    }
    function isMap(t2) {
      return t2 instanceof Map && t2.size > 0;
    }
    function isReadonlyArray(value) {
      return Array.isArray(value);
    }
    function pairToMap(v) {
      return /* @__PURE__ */ new Map([[`${v[0]}`, prepareDirection([v[1]])]]);
    }
    function deepToMap(t2) {
      const sortEntries = t2.map(([k, v]) => [`${k}`, prepareDirection(v)]);
      return new Map(sortEntries);
    }
    function stringsToMap(t2) {
      const sortEntries = t2.map((key) => [`${key}`, 1]);
      return new Map(sortEntries);
    }
    function objectToMap(t2) {
      const sortEntries = Object.entries(t2).map(([k, v]) => [
        `${k}`,
        prepareDirection(v)
      ]);
      return new Map(sortEntries);
    }
    function mapToMap(t2) {
      const sortEntries = Array.from(t2).map(([k, v]) => [
        `${k}`,
        prepareDirection(v)
      ]);
      return new Map(sortEntries);
    }
    function formatSort(sort, direction) {
      if (sort == null)
        return void 0;
      if (typeof sort === "string")
        return /* @__PURE__ */ new Map([[sort, prepareDirection(direction)]]);
      if (typeof sort !== "object") {
        throw new error_1.MongoInvalidArgumentError(`Invalid sort format: ${JSON.stringify(sort)} Sort must be a valid object`);
      }
      if (!isReadonlyArray(sort)) {
        if (isMap(sort))
          return mapToMap(sort);
        if (Object.keys(sort).length)
          return objectToMap(sort);
        return void 0;
      }
      if (!sort.length)
        return void 0;
      if (isDeep(sort))
        return deepToMap(sort);
      if (isPair(sort))
        return pairToMap(sort);
      return stringsToMap(sort);
    }
  }
});

// node_modules/mongodb/lib/operations/update.js
var require_update = __commonJS({
  "node_modules/mongodb/lib/operations/update.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ReplaceOneOperation = exports2.UpdateManyOperation = exports2.UpdateOneOperation = exports2.UpdateOperation = void 0;
    exports2.makeUpdateStatement = makeUpdateStatement;
    var responses_1 = require_responses();
    var error_1 = require_error();
    var sort_1 = require_sort();
    var utils_1 = require_utils();
    var command_1 = require_command();
    var operation_1 = require_operation();
    var UpdateOperation = class extends command_1.CommandOperation {
      constructor(ns, statements, options) {
        super(void 0, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.options = options;
        this.ns = ns;
        this.statements = statements;
      }
      get commandName() {
        return "update";
      }
      get canRetryWrite() {
        if (super.canRetryWrite === false) {
          return false;
        }
        return this.statements.every((op) => op.multi == null || op.multi === false);
      }
      buildCommandDocument(_connection, _session) {
        const options = this.options;
        const command = {
          update: this.ns.collection,
          updates: this.statements,
          ordered: options.ordered ?? true
        };
        if (typeof options.bypassDocumentValidation === "boolean") {
          command.bypassDocumentValidation = options.bypassDocumentValidation;
        }
        if (options.let) {
          command.let = options.let;
        }
        if (options.comment !== void 0) {
          command.comment = options.comment;
        }
        return command;
      }
    };
    exports2.UpdateOperation = UpdateOperation;
    var UpdateOneOperation = class extends UpdateOperation {
      constructor(ns, filter, update, options) {
        super(ns, [makeUpdateStatement(filter, update, { ...options, multi: false })], options);
        if (!(0, utils_1.hasAtomicOperators)(update, options)) {
          throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators");
        }
      }
      handleOk(response) {
        const res = super.handleOk(response);
        if (this.explain != null)
          return res;
        if (res.code)
          throw new error_1.MongoServerError(res);
        if (res.writeErrors)
          throw new error_1.MongoServerError(res.writeErrors[0]);
        return {
          acknowledged: this.writeConcern?.w !== 0,
          modifiedCount: res.nModified ?? res.n,
          upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null,
          upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0,
          matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n
        };
      }
    };
    exports2.UpdateOneOperation = UpdateOneOperation;
    var UpdateManyOperation = class extends UpdateOperation {
      constructor(ns, filter, update, options) {
        super(ns, [makeUpdateStatement(filter, update, { ...options, multi: true })], options);
        if (!(0, utils_1.hasAtomicOperators)(update, options)) {
          throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators");
        }
      }
      handleOk(response) {
        const res = super.handleOk(response);
        if (this.explain != null)
          return res;
        if (res.code)
          throw new error_1.MongoServerError(res);
        if (res.writeErrors)
          throw new error_1.MongoServerError(res.writeErrors[0]);
        return {
          acknowledged: this.writeConcern?.w !== 0,
          modifiedCount: res.nModified ?? res.n,
          upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null,
          upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0,
          matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n
        };
      }
    };
    exports2.UpdateManyOperation = UpdateManyOperation;
    var ReplaceOneOperation = class extends UpdateOperation {
      constructor(ns, filter, replacement, options) {
        super(ns, [makeUpdateStatement(filter, replacement, { ...options, multi: false })], options);
        if ((0, utils_1.hasAtomicOperators)(replacement)) {
          throw new error_1.MongoInvalidArgumentError("Replacement document must not contain atomic operators");
        }
      }
      handleOk(response) {
        const res = super.handleOk(response);
        if (this.explain != null)
          return res;
        if (res.code)
          throw new error_1.MongoServerError(res);
        if (res.writeErrors)
          throw new error_1.MongoServerError(res.writeErrors[0]);
        return {
          acknowledged: this.writeConcern?.w !== 0,
          modifiedCount: res.nModified ?? res.n,
          upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null,
          upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0,
          matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n
        };
      }
    };
    exports2.ReplaceOneOperation = ReplaceOneOperation;
    function makeUpdateStatement(filter, update, options) {
      if (filter == null || typeof filter !== "object") {
        throw new error_1.MongoInvalidArgumentError("Selector must be a valid JavaScript object");
      }
      if (update == null || typeof update !== "object") {
        throw new error_1.MongoInvalidArgumentError("Document must be a valid JavaScript object");
      }
      const op = { q: filter, u: update };
      if (typeof options.upsert === "boolean") {
        op.upsert = options.upsert;
      }
      if (options.multi) {
        op.multi = options.multi;
      }
      if (options.hint) {
        op.hint = options.hint;
      }
      if (options.arrayFilters) {
        op.arrayFilters = options.arrayFilters;
      }
      if (options.collation) {
        op.collation = options.collation;
      }
      if (!options.multi && options.sort != null) {
        op.sort = (0, sort_1.formatSort)(options.sort);
      }
      return op;
    }
    (0, operation_1.defineAspects)(UpdateOperation, [
      operation_1.Aspect.RETRYABLE,
      operation_1.Aspect.WRITE_OPERATION,
      operation_1.Aspect.SKIP_COLLATION,
      operation_1.Aspect.SUPPORTS_RAW_DATA
    ]);
    (0, operation_1.defineAspects)(UpdateOneOperation, [
      operation_1.Aspect.RETRYABLE,
      operation_1.Aspect.WRITE_OPERATION,
      operation_1.Aspect.EXPLAINABLE,
      operation_1.Aspect.SKIP_COLLATION,
      operation_1.Aspect.SUPPORTS_RAW_DATA
    ]);
    (0, operation_1.defineAspects)(UpdateManyOperation, [
      operation_1.Aspect.WRITE_OPERATION,
      operation_1.Aspect.EXPLAINABLE,
      operation_1.Aspect.SKIP_COLLATION,
      operation_1.Aspect.SUPPORTS_RAW_DATA
    ]);
    (0, operation_1.defineAspects)(ReplaceOneOperation, [
      operation_1.Aspect.RETRYABLE,
      operation_1.Aspect.WRITE_OPERATION,
      operation_1.Aspect.SKIP_COLLATION,
      operation_1.Aspect.SUPPORTS_RAW_DATA
    ]);
  }
});

// node_modules/mongodb/lib/bulk/common.js
var require_common2 = __commonJS({
  "node_modules/mongodb/lib/bulk/common.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BulkOperationBase = exports2.FindOperators = exports2.MongoBulkWriteError = exports2.WriteError = exports2.WriteConcernError = exports2.BulkWriteResult = exports2.Batch = exports2.BatchType = void 0;
    exports2.mergeBatchResults = mergeBatchResults;
    var bson_1 = require_bson2();
    var error_1 = require_error();
    var delete_1 = require_delete();
    var execute_operation_1 = require_execute_operation();
    var insert_1 = require_insert();
    var update_1 = require_update();
    var timeout_1 = require_timeout();
    var utils_1 = require_utils();
    var write_concern_1 = require_write_concern();
    exports2.BatchType = Object.freeze({
      INSERT: 1,
      UPDATE: 2,
      DELETE: 3
    });
    var Batch = class {
      constructor(batchType, originalZeroIndex) {
        this.originalZeroIndex = originalZeroIndex;
        this.currentIndex = 0;
        this.originalIndexes = [];
        this.batchType = batchType;
        this.operations = [];
        this.size = 0;
        this.sizeBytes = 0;
      }
    };
    exports2.Batch = Batch;
    var BulkWriteResult = class _BulkWriteResult {
      static generateIdMap(ids) {
        const idMap = {};
        for (const doc of ids) {
          idMap[doc.index] = doc._id;
        }
        return idMap;
      }
      /**
       * Create a new BulkWriteResult instance
       * @internal
       */
      constructor(bulkResult, isOrdered) {
        this.result = bulkResult;
        this.insertedCount = this.result.nInserted ?? 0;
        this.matchedCount = this.result.nMatched ?? 0;
        this.modifiedCount = this.result.nModified ?? 0;
        this.deletedCount = this.result.nRemoved ?? 0;
        this.upsertedCount = this.result.upserted.length ?? 0;
        this.upsertedIds = _BulkWriteResult.generateIdMap(this.result.upserted);
        this.insertedIds = _BulkWriteResult.generateIdMap(this.getSuccessfullyInsertedIds(bulkResult, isOrdered));
        Object.defineProperty(this, "result", { value: this.result, enumerable: false });
      }
      /** Evaluates to true if the bulk operation correctly executes */
      get ok() {
        return this.result.ok;
      }
      /**
       * Returns document_ids that were actually inserted
       * @internal
       */
      getSuccessfullyInsertedIds(bulkResult, isOrdered) {
        if (bulkResult.writeErrors.length === 0)
          return bulkResult.insertedIds;
        if (isOrdered) {
          return bulkResult.insertedIds.slice(0, bulkResult.writeErrors[0].index);
        }
        return bulkResult.insertedIds.filter(({ index }) => !bulkResult.writeErrors.some((writeError) => index === writeError.index));
      }
      /** Returns the upserted id at the given index */
      getUpsertedIdAt(index) {
        return this.result.upserted[index];
      }
      /** Returns raw internal result */
      getRawResponse() {
        return this.result;
      }
      /** Returns true if the bulk operation contains a write error */
      hasWriteErrors() {
        return this.result.writeErrors.length > 0;
      }
      /** Returns the number of write errors from the bulk operation */
      getWriteErrorCount() {
        return this.result.writeErrors.length;
      }
      /** Returns a specific write error object */
      getWriteErrorAt(index) {
        return index < this.result.writeErrors.length ? this.result.writeErrors[index] : void 0;
      }
      /** Retrieve all write errors */
      getWriteErrors() {
        return this.result.writeErrors;
      }
      /** Retrieve the write concern error if one exists */
      getWriteConcernError() {
        if (this.result.writeConcernErrors.length === 0) {
          return;
        } else if (this.result.writeConcernErrors.length === 1) {
          return this.result.writeConcernErrors[0];
        } else {
          let errmsg = "";
          for (let i2 = 0; i2 < this.result.writeConcernErrors.length; i2++) {
            const err = this.result.writeConcernErrors[i2];
            errmsg = errmsg + err.errmsg;
            if (i2 === 0)
              errmsg = errmsg + " and ";
          }
          return new WriteConcernError({ errmsg, code: error_1.MONGODB_ERROR_CODES.WriteConcernTimeout });
        }
      }
      toString() {
        return `BulkWriteResult(${bson_1.EJSON.stringify(this.result)})`;
      }
      isOk() {
        return this.result.ok === 1;
      }
    };
    exports2.BulkWriteResult = BulkWriteResult;
    var WriteConcernError = class {
      constructor(error51) {
        this.serverError = error51;
      }
      /** Write concern error code. */
      get code() {
        return this.serverError.code;
      }
      /** Write concern error message. */
      get errmsg() {
        return this.serverError.errmsg;
      }
      /** Write concern error info. */
      get errInfo() {
        return this.serverError.errInfo;
      }
      toJSON() {
        return this.serverError;
      }
      toString() {
        return `WriteConcernError(${this.errmsg})`;
      }
    };
    exports2.WriteConcernError = WriteConcernError;
    var WriteError = class {
      constructor(err) {
        this.err = err;
      }
      /** WriteError code. */
      get code() {
        return this.err.code;
      }
      /** WriteError original bulk operation index. */
      get index() {
        return this.err.index;
      }
      /** WriteError message. */
      get errmsg() {
        return this.err.errmsg;
      }
      /** WriteError details. */
      get errInfo() {
        return this.err.errInfo;
      }
      /** Returns the underlying operation that caused the error */
      getOperation() {
        return this.err.op;
      }
      toJSON() {
        return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op };
      }
      toString() {
        return `WriteError(${JSON.stringify(this.toJSON())})`;
      }
    };
    exports2.WriteError = WriteError;
    function mergeBatchResults(batch, bulkResult, err, result) {
      if (err) {
        result = err;
      } else if (result && result.result) {
        result = result.result;
      }
      if (result == null) {
        return;
      }
      if (result.ok === 0 && bulkResult.ok === 1) {
        bulkResult.ok = 0;
        const writeError = {
          index: 0,
          code: result.code || 0,
          errmsg: result.message,
          errInfo: result.errInfo,
          op: batch.operations[0]
        };
        bulkResult.writeErrors.push(new WriteError(writeError));
        return;
      } else if (result.ok === 0 && bulkResult.ok === 0) {
        return;
      }
      if (isInsertBatch(batch) && result.n) {
        bulkResult.nInserted = bulkResult.nInserted + result.n;
      }
      if (isDeleteBatch(batch) && result.n) {
        bulkResult.nRemoved = bulkResult.nRemoved + result.n;
      }
      let nUpserted = 0;
      if (Array.isArray(result.upserted)) {
        nUpserted = result.upserted.length;
        for (let i2 = 0; i2 < result.upserted.length; i2++) {
          bulkResult.upserted.push({
            index: result.upserted[i2].index + batch.originalZeroIndex,
            _id: result.upserted[i2]._id
          });
        }
      } else if (result.upserted) {
        nUpserted = 1;
        bulkResult.upserted.push({
          index: batch.originalZeroIndex,
          _id: result.upserted
        });
      }
      if (isUpdateBatch(batch) && result.n) {
        const nModified = result.nModified;
        bulkResult.nUpserted = bulkResult.nUpserted + nUpserted;
        bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted);
        if (typeof nModified === "number") {
          bulkResult.nModified = bulkResult.nModified + nModified;
        } else {
          bulkResult.nModified = 0;
        }
      }
      if (Array.isArray(result.writeErrors)) {
        for (let i2 = 0; i2 < result.writeErrors.length; i2++) {
          const writeError = {
            index: batch.originalIndexes[result.writeErrors[i2].index],
            code: result.writeErrors[i2].code,
            errmsg: result.writeErrors[i2].errmsg,
            errInfo: result.writeErrors[i2].errInfo,
            op: batch.operations[result.writeErrors[i2].index]
          };
          bulkResult.writeErrors.push(new WriteError(writeError));
        }
      }
      if (result.writeConcernError) {
        bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError));
      }
    }
    async function executeCommands(bulkOperation, options) {
      if (bulkOperation.s.batches.length === 0) {
        return new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered);
      }
      for (const batch of bulkOperation.s.batches) {
        const finalOptions = (0, utils_1.resolveOptions)(bulkOperation, {
          ...options,
          ordered: bulkOperation.isOrdered
        });
        if (finalOptions.bypassDocumentValidation !== true) {
          delete finalOptions.bypassDocumentValidation;
        }
        if (bulkOperation.s.bypassDocumentValidation === true) {
          finalOptions.bypassDocumentValidation = true;
        }
        if (bulkOperation.s.checkKeys === false) {
          finalOptions.checkKeys = false;
        }
        if (bulkOperation.retryWrites) {
          if (isUpdateBatch(batch)) {
            bulkOperation.retryWrites = bulkOperation.retryWrites && !batch.operations.some((op) => op.multi);
          }
          if (isDeleteBatch(batch)) {
            bulkOperation.retryWrites = bulkOperation.retryWrites && !batch.operations.some((op) => op.limit === 0);
          }
        }
        const operation = isInsertBatch(batch) ? new insert_1.InsertOperation(bulkOperation.s.namespace, batch.operations, finalOptions) : isUpdateBatch(batch) ? new update_1.UpdateOperation(bulkOperation.s.namespace, batch.operations, finalOptions) : isDeleteBatch(batch) ? new delete_1.DeleteOperation(bulkOperation.s.namespace, batch.operations, finalOptions) : null;
        if (operation == null)
          throw new error_1.MongoRuntimeError(`Unknown batchType: ${batch.batchType}`);
        let thrownError = null;
        let result;
        try {
          result = await (0, execute_operation_1.executeOperation)(bulkOperation.s.collection.client, operation, finalOptions.timeoutContext);
        } catch (error51) {
          thrownError = error51;
        }
        if (thrownError != null) {
          if (thrownError instanceof error_1.MongoWriteConcernError) {
            mergeBatchResults(batch, bulkOperation.s.bulkResult, thrownError, result);
            const writeResult3 = new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered);
            throw new MongoBulkWriteError({
              message: thrownError.result.writeConcernError.errmsg,
              code: thrownError.result.writeConcernError.code
            }, writeResult3);
          } else {
            throw new MongoBulkWriteError(thrownError, new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered));
          }
        }
        mergeBatchResults(batch, bulkOperation.s.bulkResult, thrownError, result);
        const writeResult2 = new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered);
        bulkOperation.handleWriteError(writeResult2);
      }
      bulkOperation.s.batches.length = 0;
      const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered);
      bulkOperation.handleWriteError(writeResult);
      return writeResult;
    }
    var MongoBulkWriteError = class extends error_1.MongoServerError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(error51, result) {
        super(error51);
        this.writeErrors = [];
        if (error51 instanceof WriteConcernError)
          this.err = error51;
        else if (!(error51 instanceof Error)) {
          this.message = error51.message;
          this.code = error51.code;
          this.writeErrors = error51.writeErrors ?? [];
        }
        this.result = result;
        Object.assign(this, error51);
      }
      get name() {
        return "MongoBulkWriteError";
      }
      /** Number of documents inserted. */
      get insertedCount() {
        return this.result.insertedCount;
      }
      /** Number of documents matched for update. */
      get matchedCount() {
        return this.result.matchedCount;
      }
      /** Number of documents modified. */
      get modifiedCount() {
        return this.result.modifiedCount;
      }
      /** Number of documents deleted. */
      get deletedCount() {
        return this.result.deletedCount;
      }
      /** Number of documents upserted. */
      get upsertedCount() {
        return this.result.upsertedCount;
      }
      /** Inserted document generated Id's, hash key is the index of the originating operation */
      get insertedIds() {
        return this.result.insertedIds;
      }
      /** Upserted document generated Id's, hash key is the index of the originating operation */
      get upsertedIds() {
        return this.result.upsertedIds;
      }
    };
    exports2.MongoBulkWriteError = MongoBulkWriteError;
    var FindOperators = class {
      /**
       * Creates a new FindOperators object.
       * @internal
       */
      constructor(bulkOperation) {
        this.bulkOperation = bulkOperation;
      }
      /** Add a multiple update operation to the bulk operation */
      update(updateDocument) {
        const currentOp = buildCurrentOp(this.bulkOperation);
        return this.bulkOperation.addToOperationsList(exports2.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, updateDocument, {
          ...currentOp,
          multi: true
        }));
      }
      /** Add a single update operation to the bulk operation */
      updateOne(updateDocument) {
        if (!(0, utils_1.hasAtomicOperators)(updateDocument, this.bulkOperation.bsonOptions)) {
          throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators");
        }
        const currentOp = buildCurrentOp(this.bulkOperation);
        return this.bulkOperation.addToOperationsList(exports2.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, updateDocument, { ...currentOp, multi: false }));
      }
      /** Add a replace one operation to the bulk operation */
      replaceOne(replacement) {
        if ((0, utils_1.hasAtomicOperators)(replacement)) {
          throw new error_1.MongoInvalidArgumentError("Replacement document must not use atomic operators");
        }
        const currentOp = buildCurrentOp(this.bulkOperation);
        return this.bulkOperation.addToOperationsList(exports2.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, replacement, { ...currentOp, multi: false }));
      }
      /** Add a delete one operation to the bulk operation */
      deleteOne() {
        const currentOp = buildCurrentOp(this.bulkOperation);
        return this.bulkOperation.addToOperationsList(exports2.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(currentOp.selector, { ...currentOp, limit: 1 }));
      }
      /** Add a delete many operation to the bulk operation */
      delete() {
        const currentOp = buildCurrentOp(this.bulkOperation);
        return this.bulkOperation.addToOperationsList(exports2.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(currentOp.selector, { ...currentOp, limit: 0 }));
      }
      /** Upsert modifier for update bulk operation, noting that this operation is an upsert. */
      upsert() {
        if (!this.bulkOperation.s.currentOp) {
          this.bulkOperation.s.currentOp = {};
        }
        this.bulkOperation.s.currentOp.upsert = true;
        return this;
      }
      /** Specifies the collation for the query condition. */
      collation(collation) {
        if (!this.bulkOperation.s.currentOp) {
          this.bulkOperation.s.currentOp = {};
        }
        this.bulkOperation.s.currentOp.collation = collation;
        return this;
      }
      /** Specifies arrayFilters for UpdateOne or UpdateMany bulk operations. */
      arrayFilters(arrayFilters) {
        if (!this.bulkOperation.s.currentOp) {
          this.bulkOperation.s.currentOp = {};
        }
        this.bulkOperation.s.currentOp.arrayFilters = arrayFilters;
        return this;
      }
      /** Specifies hint for the bulk operation. */
      hint(hint) {
        if (!this.bulkOperation.s.currentOp) {
          this.bulkOperation.s.currentOp = {};
        }
        this.bulkOperation.s.currentOp.hint = hint;
        return this;
      }
    };
    exports2.FindOperators = FindOperators;
    var BulkOperationBase = class {
      /**
       * Create a new OrderedBulkOperation or UnorderedBulkOperation instance
       * @internal
       */
      constructor(collection, options, isOrdered) {
        this.collection = collection;
        this.retryWrites = collection.db.options?.retryWrites;
        this.isOrdered = isOrdered;
        const topology = (0, utils_1.getTopology)(collection);
        options = options == null ? {} : options;
        const namespace = collection.s.namespace;
        const executed = false;
        const currentOp = void 0;
        const hello = topology.lastHello();
        const usingAutoEncryption = !!(topology.s.options && topology.s.options.autoEncrypter);
        const maxBsonObjectSize = hello && hello.maxBsonObjectSize ? hello.maxBsonObjectSize : 1024 * 1024 * 16;
        const maxBatchSizeBytes = usingAutoEncryption ? 1024 * 1024 * 2 : maxBsonObjectSize;
        const maxWriteBatchSize = hello && hello.maxWriteBatchSize ? hello.maxWriteBatchSize : 1e3;
        const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2;
        const bulkResult = {
          ok: 1,
          writeErrors: [],
          writeConcernErrors: [],
          insertedIds: [],
          nInserted: 0,
          nUpserted: 0,
          nMatched: 0,
          nModified: 0,
          nRemoved: 0,
          upserted: []
        };
        this.s = {
          // Final result
          bulkResult,
          // Current batch state
          currentBatch: void 0,
          currentIndex: 0,
          // ordered specific
          currentBatchSize: 0,
          currentBatchSizeBytes: 0,
          // unordered specific
          currentInsertBatch: void 0,
          currentUpdateBatch: void 0,
          currentRemoveBatch: void 0,
          batches: [],
          // Write concern
          writeConcern: write_concern_1.WriteConcern.fromOptions(options),
          // Max batch size options
          maxBsonObjectSize,
          maxBatchSizeBytes,
          maxWriteBatchSize,
          maxKeySize,
          // Namespace
          namespace,
          // Topology
          topology,
          // Options
          options,
          // BSON options
          bsonOptions: (0, bson_1.resolveBSONOptions)(options),
          // Current operation
          currentOp,
          // Executed
          executed,
          // Collection
          collection,
          // Fundamental error
          err: void 0,
          // check keys
          checkKeys: typeof options.checkKeys === "boolean" ? options.checkKeys : false
        };
        if (options.bypassDocumentValidation === true) {
          this.s.bypassDocumentValidation = true;
        }
      }
      /**
       * Add a single insert document to the bulk operation
       *
       * @example
       * ```ts
       * const bulkOp = collection.initializeOrderedBulkOp();
       *
       * // Adds three inserts to the bulkOp.
       * bulkOp
       *   .insert({ a: 1 })
       *   .insert({ b: 2 })
       *   .insert({ c: 3 });
       * await bulkOp.execute();
       * ```
       */
      insert(document2) {
        (0, utils_1.maybeAddIdToDocuments)(this.collection, document2, {
          forceServerObjectId: this.shouldForceServerObjectId()
        });
        return this.addToOperationsList(exports2.BatchType.INSERT, document2);
      }
      /**
       * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne.
       * Returns a builder object used to complete the definition of the operation.
       *
       * @example
       * ```ts
       * const bulkOp = collection.initializeOrderedBulkOp();
       *
       * // Add an updateOne to the bulkOp
       * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } });
       *
       * // Add an updateMany to the bulkOp
       * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } });
       *
       * // Add an upsert
       * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } });
       *
       * // Add a deletion
       * bulkOp.find({ g: 7 }).deleteOne();
       *
       * // Add a multi deletion
       * bulkOp.find({ h: 8 }).delete();
       *
       * // Add a replaceOne
       * bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }});
       *
       * // Update using a pipeline (requires Mongodb 4.2 or higher)
       * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([
       *   { $set: { total: { $sum: [ '$y', '$z' ] } } }
       * ]);
       *
       * // All of the ops will now be executed
       * await bulkOp.execute();
       * ```
       */
      find(selector) {
        if (!selector) {
          throw new error_1.MongoInvalidArgumentError("Bulk find operation must specify a selector");
        }
        this.s.currentOp = {
          selector
        };
        return new FindOperators(this);
      }
      /** Specifies a raw operation to perform in the bulk write. */
      raw(op) {
        if (op == null || typeof op !== "object") {
          throw new error_1.MongoInvalidArgumentError("Operation must be an object with an operation key");
        }
        if ("insertOne" in op) {
          const forceServerObjectId = this.shouldForceServerObjectId();
          const document2 = op.insertOne && op.insertOne.document == null ? (
            // TODO(NODE-6003): remove support for omitting the `documents` subdocument in bulk inserts
            op.insertOne
          ) : op.insertOne.document;
          (0, utils_1.maybeAddIdToDocuments)(this.collection, document2, { forceServerObjectId });
          return this.addToOperationsList(exports2.BatchType.INSERT, document2);
        }
        if ("replaceOne" in op || "updateOne" in op || "updateMany" in op) {
          if ("replaceOne" in op) {
            if ("q" in op.replaceOne) {
              throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed");
            }
            const updateStatement = (0, update_1.makeUpdateStatement)(op.replaceOne.filter, op.replaceOne.replacement, { ...op.replaceOne, multi: false });
            if ((0, utils_1.hasAtomicOperators)(updateStatement.u)) {
              throw new error_1.MongoInvalidArgumentError("Replacement document must not use atomic operators");
            }
            return this.addToOperationsList(exports2.BatchType.UPDATE, updateStatement);
          }
          if ("updateOne" in op) {
            if ("q" in op.updateOne) {
              throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed");
            }
            const updateStatement = (0, update_1.makeUpdateStatement)(op.updateOne.filter, op.updateOne.update, {
              ...op.updateOne,
              multi: false
            });
            if (!(0, utils_1.hasAtomicOperators)(updateStatement.u, this.bsonOptions)) {
              throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators");
            }
            return this.addToOperationsList(exports2.BatchType.UPDATE, updateStatement);
          }
          if ("updateMany" in op) {
            if ("q" in op.updateMany) {
              throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed");
            }
            const updateStatement = (0, update_1.makeUpdateStatement)(op.updateMany.filter, op.updateMany.update, {
              ...op.updateMany,
              multi: true
            });
            if (!(0, utils_1.hasAtomicOperators)(updateStatement.u, this.bsonOptions)) {
              throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators");
            }
            return this.addToOperationsList(exports2.BatchType.UPDATE, updateStatement);
          }
        }
        if ("deleteOne" in op) {
          if ("q" in op.deleteOne) {
            throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed");
          }
          return this.addToOperationsList(exports2.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(op.deleteOne.filter, { ...op.deleteOne, limit: 1 }));
        }
        if ("deleteMany" in op) {
          if ("q" in op.deleteMany) {
            throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed");
          }
          return this.addToOperationsList(exports2.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(op.deleteMany.filter, { ...op.deleteMany, limit: 0 }));
        }
        throw new error_1.MongoInvalidArgumentError("bulkWrite only supports insertOne, updateOne, updateMany, deleteOne, deleteMany");
      }
      get length() {
        return this.s.currentIndex;
      }
      get bsonOptions() {
        return this.s.bsonOptions;
      }
      get writeConcern() {
        return this.s.writeConcern;
      }
      get batches() {
        const batches = [...this.s.batches];
        if (this.isOrdered) {
          if (this.s.currentBatch)
            batches.push(this.s.currentBatch);
        } else {
          if (this.s.currentInsertBatch)
            batches.push(this.s.currentInsertBatch);
          if (this.s.currentUpdateBatch)
            batches.push(this.s.currentUpdateBatch);
          if (this.s.currentRemoveBatch)
            batches.push(this.s.currentRemoveBatch);
        }
        return batches;
      }
      async execute(options = {}) {
        if (this.s.executed) {
          throw new error_1.MongoBatchReExecutionError();
        }
        const writeConcern = write_concern_1.WriteConcern.fromOptions(options);
        if (writeConcern) {
          this.s.writeConcern = writeConcern;
        }
        if (this.isOrdered) {
          if (this.s.currentBatch)
            this.s.batches.push(this.s.currentBatch);
        } else {
          if (this.s.currentInsertBatch)
            this.s.batches.push(this.s.currentInsertBatch);
          if (this.s.currentUpdateBatch)
            this.s.batches.push(this.s.currentUpdateBatch);
          if (this.s.currentRemoveBatch)
            this.s.batches.push(this.s.currentRemoveBatch);
        }
        if (this.s.batches.length === 0) {
          throw new error_1.MongoInvalidArgumentError("Invalid BulkOperation, Batch cannot be empty");
        }
        this.s.executed = true;
        const finalOptions = (0, utils_1.resolveOptions)(this.collection, { ...this.s.options, ...options });
        finalOptions.timeoutContext ??= timeout_1.TimeoutContext.create({
          session: finalOptions.session,
          timeoutMS: finalOptions.timeoutMS,
          serverSelectionTimeoutMS: this.collection.client.s.options.serverSelectionTimeoutMS,
          waitQueueTimeoutMS: this.collection.client.s.options.waitQueueTimeoutMS
        });
        if (finalOptions.session == null) {
          return await this.collection.client.withSession({ explicit: false }, async (session) => {
            return await executeCommands(this, { ...finalOptions, session });
          });
        }
        return await executeCommands(this, { ...finalOptions });
      }
      /**
       * Handles the write error before executing commands
       * @internal
       */
      handleWriteError(writeResult) {
        if (this.s.bulkResult.writeErrors.length > 0) {
          const msg = this.s.bulkResult.writeErrors[0].errmsg ? this.s.bulkResult.writeErrors[0].errmsg : "write operation failed";
          throw new MongoBulkWriteError({
            message: msg,
            code: this.s.bulkResult.writeErrors[0].code,
            writeErrors: this.s.bulkResult.writeErrors
          }, writeResult);
        }
        const writeConcernError = writeResult.getWriteConcernError();
        if (writeConcernError) {
          throw new MongoBulkWriteError(writeConcernError, writeResult);
        }
      }
      shouldForceServerObjectId() {
        return this.s.options.forceServerObjectId === true || this.s.collection.db.options?.forceServerObjectId === true;
      }
    };
    exports2.BulkOperationBase = BulkOperationBase;
    function isInsertBatch(batch) {
      return batch.batchType === exports2.BatchType.INSERT;
    }
    function isUpdateBatch(batch) {
      return batch.batchType === exports2.BatchType.UPDATE;
    }
    function isDeleteBatch(batch) {
      return batch.batchType === exports2.BatchType.DELETE;
    }
    function buildCurrentOp(bulkOp) {
      let { currentOp } = bulkOp.s;
      bulkOp.s.currentOp = void 0;
      if (!currentOp)
        currentOp = {};
      return currentOp;
    }
  }
});

// node_modules/mongodb/lib/bulk/ordered.js
var require_ordered = __commonJS({
  "node_modules/mongodb/lib/bulk/ordered.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OrderedBulkOperation = void 0;
    var BSON = require_bson2();
    var error_1 = require_error();
    var common_1 = require_common2();
    var OrderedBulkOperation = class extends common_1.BulkOperationBase {
      /** @internal */
      constructor(collection, options) {
        super(collection, options, true);
      }
      addToOperationsList(batchType, document2) {
        const bsonSize = BSON.calculateObjectSize(document2, {
          checkKeys: false,
          // Since we don't know what the user selected for BSON options here,
          // err on the safe side, and check the size with ignoreUndefined: false.
          ignoreUndefined: false
        });
        if (bsonSize >= this.s.maxBsonObjectSize)
          throw new error_1.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`);
        if (this.s.currentBatch == null) {
          this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex);
        }
        const maxKeySize = this.s.maxKeySize;
        if (
          // New batch if we exceed the max batch op size
          this.s.currentBatchSize + 1 >= this.s.maxWriteBatchSize || // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc,
          // since we can't sent an empty batch
          this.s.currentBatchSize > 0 && this.s.currentBatchSizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes || // New batch if the new op does not have the same op type as the current batch
          this.s.currentBatch.batchType !== batchType
        ) {
          this.s.batches.push(this.s.currentBatch);
          this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex);
          this.s.currentBatchSize = 0;
          this.s.currentBatchSizeBytes = 0;
        }
        if (batchType === common_1.BatchType.INSERT) {
          this.s.bulkResult.insertedIds.push({
            index: this.s.currentIndex,
            _id: document2._id
          });
        }
        if (Array.isArray(document2)) {
          throw new error_1.MongoInvalidArgumentError("Operation passed in cannot be an Array");
        }
        this.s.currentBatch.originalIndexes.push(this.s.currentIndex);
        this.s.currentBatch.operations.push(document2);
        this.s.currentBatchSize += 1;
        this.s.currentBatchSizeBytes += maxKeySize + bsonSize;
        this.s.currentIndex += 1;
        return this;
      }
    };
    exports2.OrderedBulkOperation = OrderedBulkOperation;
  }
});

// node_modules/mongodb/lib/bulk/unordered.js
var require_unordered = __commonJS({
  "node_modules/mongodb/lib/bulk/unordered.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.UnorderedBulkOperation = void 0;
    var BSON = require_bson2();
    var error_1 = require_error();
    var common_1 = require_common2();
    var UnorderedBulkOperation = class extends common_1.BulkOperationBase {
      /** @internal */
      constructor(collection, options) {
        super(collection, options, false);
      }
      handleWriteError(writeResult) {
        if (this.s.batches.length) {
          return;
        }
        return super.handleWriteError(writeResult);
      }
      addToOperationsList(batchType, document2) {
        const bsonSize = BSON.calculateObjectSize(document2, {
          checkKeys: false,
          // Since we don't know what the user selected for BSON options here,
          // err on the safe side, and check the size with ignoreUndefined: false.
          ignoreUndefined: false
        });
        if (bsonSize >= this.s.maxBsonObjectSize) {
          throw new error_1.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`);
        }
        this.s.currentBatch = void 0;
        if (batchType === common_1.BatchType.INSERT) {
          this.s.currentBatch = this.s.currentInsertBatch;
        } else if (batchType === common_1.BatchType.UPDATE) {
          this.s.currentBatch = this.s.currentUpdateBatch;
        } else if (batchType === common_1.BatchType.DELETE) {
          this.s.currentBatch = this.s.currentRemoveBatch;
        }
        const maxKeySize = this.s.maxKeySize;
        if (this.s.currentBatch == null) {
          this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex);
        }
        if (
          // New batch if we exceed the max batch op size
          this.s.currentBatch.size + 1 >= this.s.maxWriteBatchSize || // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc,
          // since we can't sent an empty batch
          this.s.currentBatch.size > 0 && this.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes || // New batch if the new op does not have the same op type as the current batch
          this.s.currentBatch.batchType !== batchType
        ) {
          this.s.batches.push(this.s.currentBatch);
          this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex);
        }
        if (Array.isArray(document2)) {
          throw new error_1.MongoInvalidArgumentError("Operation passed in cannot be an Array");
        }
        this.s.currentBatch.operations.push(document2);
        this.s.currentBatch.originalIndexes.push(this.s.currentIndex);
        this.s.currentIndex = this.s.currentIndex + 1;
        if (batchType === common_1.BatchType.INSERT) {
          this.s.currentInsertBatch = this.s.currentBatch;
          this.s.bulkResult.insertedIds.push({
            index: this.s.bulkResult.insertedIds.length,
            _id: document2._id
          });
        } else if (batchType === common_1.BatchType.UPDATE) {
          this.s.currentUpdateBatch = this.s.currentBatch;
        } else if (batchType === common_1.BatchType.DELETE) {
          this.s.currentRemoveBatch = this.s.currentBatch;
        }
        this.s.currentBatch.size += 1;
        this.s.currentBatch.sizeBytes += maxKeySize + bsonSize;
        return this;
      }
    };
    exports2.UnorderedBulkOperation = UnorderedBulkOperation;
  }
});

// node_modules/mongodb/lib/mongo_logger.js
var require_mongo_logger = __commonJS({
  "node_modules/mongodb/lib/mongo_logger.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MongoLogger = exports2.MongoLoggableComponent = exports2.SEVERITY_LEVEL_MAP = exports2.DEFAULT_MAX_DOCUMENT_LENGTH = exports2.SeverityLevel = void 0;
    exports2.parseSeverityFromString = parseSeverityFromString;
    exports2.createStdioLogger = createStdioLogger;
    exports2.stringifyWithMaxLen = stringifyWithMaxLen;
    exports2.defaultLogTransform = defaultLogTransform;
    var process4 = require("process");
    var util_1 = require("util");
    var bson_1 = require_bson2();
    var constants_1 = require_constants2();
    var utils_1 = require_utils();
    exports2.SeverityLevel = Object.freeze({
      EMERGENCY: "emergency",
      ALERT: "alert",
      CRITICAL: "critical",
      ERROR: "error",
      WARNING: "warn",
      NOTICE: "notice",
      INFORMATIONAL: "info",
      DEBUG: "debug",
      TRACE: "trace",
      OFF: "off"
    });
    exports2.DEFAULT_MAX_DOCUMENT_LENGTH = 1e3;
    var SeverityLevelMap = class extends Map {
      constructor(entries) {
        const newEntries = [];
        for (const [level, value] of entries) {
          newEntries.push([value, level]);
        }
        newEntries.push(...entries);
        super(newEntries);
      }
      getNumericSeverityLevel(severity) {
        return this.get(severity);
      }
      getSeverityLevelName(level) {
        return this.get(level);
      }
    };
    exports2.SEVERITY_LEVEL_MAP = new SeverityLevelMap([
      [exports2.SeverityLevel.OFF, -Infinity],
      [exports2.SeverityLevel.EMERGENCY, 0],
      [exports2.SeverityLevel.ALERT, 1],
      [exports2.SeverityLevel.CRITICAL, 2],
      [exports2.SeverityLevel.ERROR, 3],
      [exports2.SeverityLevel.WARNING, 4],
      [exports2.SeverityLevel.NOTICE, 5],
      [exports2.SeverityLevel.INFORMATIONAL, 6],
      [exports2.SeverityLevel.DEBUG, 7],
      [exports2.SeverityLevel.TRACE, 8]
    ]);
    exports2.MongoLoggableComponent = Object.freeze({
      COMMAND: "command",
      TOPOLOGY: "topology",
      SERVER_SELECTION: "serverSelection",
      CONNECTION: "connection",
      CLIENT: "client"
    });
    function parseSeverityFromString(s2) {
      const validSeverities = Object.values(exports2.SeverityLevel);
      const lowerSeverity = s2?.toLowerCase();
      if (lowerSeverity != null && validSeverities.includes(lowerSeverity)) {
        return lowerSeverity;
      }
      return null;
    }
    function createStdioLogger(stream) {
      return {
        write: (log) => {
          return new Promise((resolve2, reject) => {
            const logLine = (0, util_1.inspect)(log, { compact: true, breakLength: Infinity });
            stream.write(`${logLine}
`, "utf-8", (error51) => {
              if (error51)
                return reject(error51);
              resolve2(true);
            });
          });
        }
      };
    }
    function resolveLogPath({ MONGODB_LOG_PATH }, { mongodbLogPath }) {
      if (typeof mongodbLogPath === "string" && /^stderr$/i.test(mongodbLogPath)) {
        return { mongodbLogPath: createStdioLogger(process4.stderr), mongodbLogPathIsStdErr: true };
      }
      if (typeof mongodbLogPath === "string" && /^stdout$/i.test(mongodbLogPath)) {
        return { mongodbLogPath: createStdioLogger(process4.stdout), mongodbLogPathIsStdErr: false };
      }
      if (typeof mongodbLogPath === "object" && typeof mongodbLogPath?.write === "function") {
        return { mongodbLogPath, mongodbLogPathIsStdErr: false };
      }
      if (MONGODB_LOG_PATH && /^stderr$/i.test(MONGODB_LOG_PATH)) {
        return { mongodbLogPath: createStdioLogger(process4.stderr), mongodbLogPathIsStdErr: true };
      }
      if (MONGODB_LOG_PATH && /^stdout$/i.test(MONGODB_LOG_PATH)) {
        return { mongodbLogPath: createStdioLogger(process4.stdout), mongodbLogPathIsStdErr: false };
      }
      return { mongodbLogPath: createStdioLogger(process4.stderr), mongodbLogPathIsStdErr: true };
    }
    function resolveSeverityConfiguration(clientOption, environmentOption, defaultSeverity) {
      return parseSeverityFromString(clientOption) ?? parseSeverityFromString(environmentOption) ?? defaultSeverity;
    }
    function compareSeverity(s0, s1) {
      const s0Num = exports2.SEVERITY_LEVEL_MAP.getNumericSeverityLevel(s0);
      const s1Num = exports2.SEVERITY_LEVEL_MAP.getNumericSeverityLevel(s1);
      return s0Num < s1Num ? -1 : s0Num > s1Num ? 1 : 0;
    }
    function stringifyWithMaxLen(value, maxDocumentLength, options = {}) {
      let strToTruncate = "";
      let currentLength = 0;
      const maxDocumentLengthEnsurer = function maxDocumentLengthEnsurer2(key, value2) {
        if (currentLength >= maxDocumentLength) {
          return void 0;
        }
        if (key === "") {
          currentLength += 1;
          return value2;
        }
        currentLength += key.length + 4;
        if (value2 == null)
          return value2;
        switch (typeof value2) {
          case "string":
            currentLength += value2.length + 2;
            break;
          case "number":
          case "bigint":
            currentLength += String(value2).length;
            break;
          case "boolean":
            currentLength += value2 ? 4 : 5;
            break;
          case "object":
            if ((0, utils_1.isUint8Array)(value2)) {
              currentLength += 22 + value2.byteLength + value2.byteLength * 0.33 + 18 | 0;
            } else if ("_bsontype" in value2) {
              const v = value2;
              switch (v._bsontype) {
                case "Int32":
                  currentLength += String(v.value).length;
                  break;
                case "Double":
                  currentLength += (v.value | 0) === v.value ? String(v.value).length + 2 : String(v.value).length;
                  break;
                case "Long":
                  currentLength += v.toString().length;
                  break;
                case "ObjectId":
                  currentLength += 35;
                  break;
                case "MaxKey":
                case "MinKey":
                  currentLength += 13;
                  break;
                case "Binary":
                  currentLength += 22 + value2.position + value2.position * 0.33 + 18 | 0;
                  break;
                case "Timestamp":
                  currentLength += 19 + String(v.t).length + 5 + String(v.i).length + 2;
                  break;
                case "Code":
                  if (v.scope == null) {
                    currentLength += v.code.length + 10 + 2;
                  } else {
                    currentLength += v.code.length + 10 + 11;
                  }
                  break;
                case "BSONRegExp":
                  currentLength += 34 + v.pattern.length + 13 + v.options.length + 3;
                  break;
              }
            }
        }
        return value2;
      };
      if (typeof value === "string") {
        strToTruncate = value;
      } else if (typeof value === "function") {
        strToTruncate = value.name;
      } else {
        try {
          if (maxDocumentLength !== 0) {
            strToTruncate = bson_1.EJSON.stringify(value, maxDocumentLengthEnsurer, 0, options);
          } else {
            strToTruncate = bson_1.EJSON.stringify(value, options);
          }
        } catch (e2) {
          strToTruncate = `Extended JSON serialization failed with: ${e2.message}`;
        }
      }
      if (maxDocumentLength !== 0 && strToTruncate.length > maxDocumentLength && strToTruncate.charCodeAt(maxDocumentLength - 1) !== strToTruncate.codePointAt(maxDocumentLength - 1)) {
        maxDocumentLength--;
        if (maxDocumentLength === 0) {
          return "";
        }
      }
      return maxDocumentLength !== 0 && strToTruncate.length > maxDocumentLength ? `${strToTruncate.slice(0, maxDocumentLength)}...` : strToTruncate;
    }
    function isLogConvertible(obj) {
      const objAsLogConvertible = obj;
      return objAsLogConvertible.toLog !== void 0 && typeof objAsLogConvertible.toLog === "function";
    }
    function attachServerSelectionFields(log, serverSelectionEvent, maxDocumentLength = exports2.DEFAULT_MAX_DOCUMENT_LENGTH) {
      const { selector, operation, topologyDescription, message } = serverSelectionEvent;
      log.selector = stringifyWithMaxLen(selector, maxDocumentLength);
      log.operation = operation;
      log.topologyDescription = stringifyWithMaxLen(topologyDescription, maxDocumentLength);
      log.message = message;
      return log;
    }
    function attachCommandFields(log, commandEvent) {
      log.commandName = commandEvent.commandName;
      log.requestId = commandEvent.requestId;
      log.driverConnectionId = commandEvent.connectionId;
      const { host, port } = utils_1.HostAddress.fromString(commandEvent.address).toHostPort();
      log.serverHost = host;
      log.serverPort = port;
      if (commandEvent?.serviceId) {
        log.serviceId = commandEvent.serviceId.toHexString();
      }
      log.databaseName = commandEvent.databaseName;
      log.serverConnectionId = commandEvent.serverConnectionId;
      return log;
    }
    function attachConnectionFields(log, event) {
      const { host, port } = utils_1.HostAddress.fromString(event.address).toHostPort();
      log.serverHost = host;
      log.serverPort = port;
      return log;
    }
    function attachSDAMFields(log, sdamEvent) {
      log.topologyId = sdamEvent.topologyId;
      return log;
    }
    function attachServerHeartbeatFields(log, serverHeartbeatEvent) {
      const { awaited, connectionId } = serverHeartbeatEvent;
      log.awaited = awaited;
      log.driverConnectionId = serverHeartbeatEvent.connectionId;
      const { host, port } = utils_1.HostAddress.fromString(connectionId).toHostPort();
      log.serverHost = host;
      log.serverPort = port;
      return log;
    }
    function defaultLogTransform(logObject, maxDocumentLength = exports2.DEFAULT_MAX_DOCUMENT_LENGTH) {
      let log = /* @__PURE__ */ Object.create(null);
      switch (logObject.name) {
        case constants_1.SERVER_SELECTION_STARTED:
          log = attachServerSelectionFields(log, logObject, maxDocumentLength);
          return log;
        case constants_1.SERVER_SELECTION_FAILED:
          log = attachServerSelectionFields(log, logObject, maxDocumentLength);
          log.failure = logObject.failure?.message;
          return log;
        case constants_1.SERVER_SELECTION_SUCCEEDED:
          log = attachServerSelectionFields(log, logObject, maxDocumentLength);
          log.serverHost = logObject.serverHost;
          log.serverPort = logObject.serverPort;
          return log;
        case constants_1.WAITING_FOR_SUITABLE_SERVER:
          log = attachServerSelectionFields(log, logObject, maxDocumentLength);
          log.remainingTimeMS = logObject.remainingTimeMS;
          return log;
        case constants_1.COMMAND_STARTED:
          log = attachCommandFields(log, logObject);
          log.message = "Command started";
          log.command = stringifyWithMaxLen(logObject.command, maxDocumentLength, { relaxed: true });
          log.databaseName = logObject.databaseName;
          return log;
        case constants_1.COMMAND_SUCCEEDED:
          log = attachCommandFields(log, logObject);
          log.message = "Command succeeded";
          log.durationMS = logObject.duration;
          log.reply = stringifyWithMaxLen(logObject.reply, maxDocumentLength, { relaxed: true });
          return log;
        case constants_1.COMMAND_FAILED:
          log = attachCommandFields(log, logObject);
          log.message = "Command failed";
          log.durationMS = logObject.duration;
          log.failure = logObject.failure?.message ?? "(redacted)";
          return log;
        case constants_1.CONNECTION_POOL_CREATED:
          log = attachConnectionFields(log, logObject);
          log.message = "Connection pool created";
          if (logObject.options) {
            const { maxIdleTimeMS, minPoolSize, maxPoolSize, maxConnecting, waitQueueTimeoutMS } = logObject.options;
            log = {
              ...log,
              maxIdleTimeMS,
              minPoolSize,
              maxPoolSize,
              maxConnecting,
              waitQueueTimeoutMS
            };
          }
          return log;
        case constants_1.CONNECTION_POOL_READY:
          log = attachConnectionFields(log, logObject);
          log.message = "Connection pool ready";
          return log;
        case constants_1.CONNECTION_POOL_CLEARED:
          log = attachConnectionFields(log, logObject);
          log.message = "Connection pool cleared";
          if (logObject.serviceId?._bsontype === "ObjectId") {
            log.serviceId = logObject.serviceId?.toHexString();
          }
          return log;
        case constants_1.CONNECTION_POOL_CLOSED:
          log = attachConnectionFields(log, logObject);
          log.message = "Connection pool closed";
          return log;
        case constants_1.CONNECTION_CREATED:
          log = attachConnectionFields(log, logObject);
          log.message = "Connection created";
          log.driverConnectionId = logObject.connectionId;
          return log;
        case constants_1.CONNECTION_READY:
          log = attachConnectionFields(log, logObject);
          log.message = "Connection ready";
          log.driverConnectionId = logObject.connectionId;
          log.durationMS = logObject.durationMS;
          return log;
        case constants_1.CONNECTION_CLOSED:
          log = attachConnectionFields(log, logObject);
          log.message = "Connection closed";
          log.driverConnectionId = logObject.connectionId;
          switch (logObject.reason) {
            case "stale":
              log.reason = "Connection became stale because the pool was cleared";
              break;
            case "idle":
              log.reason = "Connection has been available but unused for longer than the configured max idle time";
              break;
            case "error":
              log.reason = "An error occurred while using the connection";
              if (logObject.error) {
                log.error = logObject.error;
              }
              break;
            case "poolClosed":
              log.reason = "Connection pool was closed";
              break;
            default:
              log.reason = `Unknown close reason: ${logObject.reason}`;
          }
          return log;
        case constants_1.CONNECTION_CHECK_OUT_STARTED:
          log = attachConnectionFields(log, logObject);
          log.message = "Connection checkout started";
          return log;
        case constants_1.CONNECTION_CHECK_OUT_FAILED:
          log = attachConnectionFields(log, logObject);
          log.message = "Connection checkout failed";
          switch (logObject.reason) {
            case "poolClosed":
              log.reason = "Connection pool was closed";
              break;
            case "timeout":
              log.reason = "Wait queue timeout elapsed without a connection becoming available";
              break;
            case "connectionError":
              log.reason = "An error occurred while trying to establish a new connection";
              if (logObject.error) {
                log.error = logObject.error;
              }
              break;
            default:
              log.reason = `Unknown close reason: ${logObject.reason}`;
          }
          log.durationMS = logObject.durationMS;
          return log;
        case constants_1.CONNECTION_CHECKED_OUT:
          log = attachConnectionFields(log, logObject);
          log.message = "Connection checked out";
          log.driverConnectionId = logObject.connectionId;
          log.durationMS = logObject.durationMS;
          return log;
        case constants_1.CONNECTION_CHECKED_IN:
          log = attachConnectionFields(log, logObject);
          log.message = "Connection checked in";
          log.driverConnectionId = logObject.connectionId;
          return log;
        case constants_1.SERVER_OPENING:
          log = attachSDAMFields(log, logObject);
          log = attachConnectionFields(log, logObject);
          log.message = "Starting server monitoring";
          return log;
        case constants_1.SERVER_CLOSED:
          log = attachSDAMFields(log, logObject);
          log = attachConnectionFields(log, logObject);
          log.message = "Stopped server monitoring";
          return log;
        case constants_1.SERVER_HEARTBEAT_STARTED:
          log = attachSDAMFields(log, logObject);
          log = attachServerHeartbeatFields(log, logObject);
          log.message = "Server heartbeat started";
          return log;
        case constants_1.SERVER_HEARTBEAT_SUCCEEDED:
          log = attachSDAMFields(log, logObject);
          log = attachServerHeartbeatFields(log, logObject);
          log.message = "Server heartbeat succeeded";
          log.durationMS = logObject.duration;
          log.serverConnectionId = logObject.serverConnectionId;
          log.reply = stringifyWithMaxLen(logObject.reply, maxDocumentLength, { relaxed: true });
          return log;
        case constants_1.SERVER_HEARTBEAT_FAILED:
          log = attachSDAMFields(log, logObject);
          log = attachServerHeartbeatFields(log, logObject);
          log.message = "Server heartbeat failed";
          log.durationMS = logObject.duration;
          log.failure = logObject.failure?.message;
          return log;
        case constants_1.TOPOLOGY_OPENING:
          log = attachSDAMFields(log, logObject);
          log.message = "Starting topology monitoring";
          return log;
        case constants_1.TOPOLOGY_CLOSED:
          log = attachSDAMFields(log, logObject);
          log.message = "Stopped topology monitoring";
          return log;
        case constants_1.TOPOLOGY_DESCRIPTION_CHANGED:
          log = attachSDAMFields(log, logObject);
          log.message = "Topology description changed";
          log.previousDescription = log.reply = stringifyWithMaxLen(logObject.previousDescription, maxDocumentLength);
          log.newDescription = log.reply = stringifyWithMaxLen(logObject.newDescription, maxDocumentLength);
          return log;
        default:
          for (const [key, value] of Object.entries(logObject)) {
            if (value != null)
              log[key] = value;
          }
      }
      return log;
    }
    var MongoLogger = class {
      constructor(options) {
        this.pendingLog = null;
        this.error = this.log.bind(this, "error");
        this.warn = this.log.bind(this, "warn");
        this.info = this.log.bind(this, "info");
        this.debug = this.log.bind(this, "debug");
        this.trace = this.log.bind(this, "trace");
        this.componentSeverities = options.componentSeverities;
        this.maxDocumentLength = options.maxDocumentLength;
        this.logDestination = options.logDestination;
        this.logDestinationIsStdErr = options.logDestinationIsStdErr;
        this.severities = this.createLoggingSeverities();
      }
      createLoggingSeverities() {
        const severities = Object();
        for (const component of Object.values(exports2.MongoLoggableComponent)) {
          severities[component] = {};
          for (const severityLevel of Object.values(exports2.SeverityLevel)) {
            severities[component][severityLevel] = compareSeverity(severityLevel, this.componentSeverities[component]) <= 0;
          }
        }
        return severities;
      }
      turnOffSeverities() {
        for (const component of Object.values(exports2.MongoLoggableComponent)) {
          this.componentSeverities[component] = exports2.SeverityLevel.OFF;
          for (const severityLevel of Object.values(exports2.SeverityLevel)) {
            this.severities[component][severityLevel] = false;
          }
        }
      }
      logWriteFailureHandler(error51) {
        if (this.logDestinationIsStdErr) {
          this.turnOffSeverities();
          this.clearPendingLog();
          return;
        }
        this.logDestination = createStdioLogger(process4.stderr);
        this.logDestinationIsStdErr = true;
        this.clearPendingLog();
        this.error(exports2.MongoLoggableComponent.CLIENT, {
          toLog: function() {
            return {
              message: "User input for mongodbLogPath is now invalid. Logging is halted.",
              error: error51.message
            };
          }
        });
        this.turnOffSeverities();
        this.clearPendingLog();
      }
      clearPendingLog() {
        this.pendingLog = null;
      }
      willLog(component, severity) {
        if (severity === exports2.SeverityLevel.OFF)
          return false;
        return this.severities[component][severity];
      }
      log(severity, component, message) {
        if (!this.willLog(component, severity))
          return;
        let logMessage = { t: /* @__PURE__ */ new Date(), c: component, s: severity };
        if (typeof message === "string") {
          logMessage.message = message;
        } else if (typeof message === "object") {
          if (isLogConvertible(message)) {
            logMessage = { ...logMessage, ...message.toLog() };
          } else {
            logMessage = { ...logMessage, ...defaultLogTransform(message, this.maxDocumentLength) };
          }
        }
        if ((0, utils_1.isPromiseLike)(this.pendingLog)) {
          this.pendingLog = this.pendingLog.then(() => this.logDestination.write(logMessage)).then(this.clearPendingLog.bind(this), this.logWriteFailureHandler.bind(this));
          return;
        }
        try {
          const logResult = this.logDestination.write(logMessage);
          if ((0, utils_1.isPromiseLike)(logResult)) {
            this.pendingLog = logResult.then(this.clearPendingLog.bind(this), this.logWriteFailureHandler.bind(this));
          }
        } catch (error51) {
          this.logWriteFailureHandler(error51);
        }
      }
      /**
       * Merges options set through environment variables and the MongoClient, preferring environment
       * variables when both are set, and substituting defaults for values not set. Options set in
       * constructor take precedence over both environment variables and MongoClient options.
       *
       * @remarks
       * When parsing component severity levels, invalid values are treated as unset and replaced with
       * the default severity.
       *
       * @param envOptions - options set for the logger from the environment
       * @param clientOptions - options set for the logger in the MongoClient options
       * @returns a MongoLoggerOptions object to be used when instantiating a new MongoLogger
       */
      static resolveOptions(envOptions, clientOptions) {
        const resolvedLogPath = resolveLogPath(envOptions, clientOptions);
        const combinedOptions = {
          ...envOptions,
          ...clientOptions,
          mongodbLogPath: resolvedLogPath.mongodbLogPath,
          mongodbLogPathIsStdErr: resolvedLogPath.mongodbLogPathIsStdErr
        };
        const defaultSeverity = resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.default, combinedOptions.MONGODB_LOG_ALL, exports2.SeverityLevel.OFF);
        return {
          componentSeverities: {
            command: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.command, combinedOptions.MONGODB_LOG_COMMAND, defaultSeverity),
            topology: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.topology, combinedOptions.MONGODB_LOG_TOPOLOGY, defaultSeverity),
            serverSelection: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.serverSelection, combinedOptions.MONGODB_LOG_SERVER_SELECTION, defaultSeverity),
            connection: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.connection, combinedOptions.MONGODB_LOG_CONNECTION, defaultSeverity),
            client: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.client, combinedOptions.MONGODB_LOG_CLIENT, defaultSeverity),
            default: defaultSeverity
          },
          maxDocumentLength: combinedOptions.mongodbLogMaxDocumentLength ?? (0, utils_1.parseUnsignedInteger)(combinedOptions.MONGODB_LOG_MAX_DOCUMENT_LENGTH) ?? 1e3,
          logDestination: combinedOptions.mongodbLogPath,
          logDestinationIsStdErr: combinedOptions.mongodbLogPathIsStdErr
        };
      }
    };
    exports2.MongoLogger = MongoLogger;
  }
});

// node_modules/mongodb/lib/mongo_types.js
var require_mongo_types = __commonJS({
  "node_modules/mongodb/lib/mongo_types.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CancellationToken = exports2.TypedEventEmitter = void 0;
    var events_1 = require("events");
    var mongo_logger_1 = require_mongo_logger();
    var utils_1 = require_utils();
    var TypedEventEmitter = class extends events_1.EventEmitter {
      /** @internal */
      emitAndLog(event, ...args) {
        this.emit(event, ...args);
        if (this.component)
          this.mongoLogger?.debug(this.component, args[0]);
      }
      /** @internal */
      emitAndLogHeartbeat(event, topologyId, serverConnectionId, ...args) {
        this.emit(event, ...args);
        if (this.component) {
          const loggableHeartbeatEvent = {
            topologyId,
            serverConnectionId: serverConnectionId ?? null,
            ...args[0]
          };
          this.mongoLogger?.debug(this.component, loggableHeartbeatEvent);
        }
      }
      /** @internal */
      emitAndLogCommand(monitorCommands, event, databaseName, connectionEstablished, ...args) {
        if (monitorCommands) {
          this.emit(event, ...args);
        }
        if (connectionEstablished) {
          const loggableCommandEvent = {
            databaseName,
            ...args[0]
          };
          this.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.COMMAND, loggableCommandEvent);
        }
      }
    };
    exports2.TypedEventEmitter = TypedEventEmitter;
    var CancellationToken = class extends TypedEventEmitter {
      constructor(...args) {
        super(...args);
        this.on("error", utils_1.noop);
      }
    };
    exports2.CancellationToken = CancellationToken;
  }
});

// node_modules/mongodb/lib/operations/get_more.js
var require_get_more = __commonJS({
  "node_modules/mongodb/lib/operations/get_more.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.GetMoreOperation = void 0;
    var responses_1 = require_responses();
    var error_1 = require_error();
    var utils_1 = require_utils();
    var operation_1 = require_operation();
    var GetMoreOperation = class extends operation_1.AbstractOperation {
      constructor(ns, cursorId, server, options) {
        super(options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.CursorResponse;
        this.options = options;
        this.ns = ns;
        this.cursorId = cursorId;
        this.server = server;
      }
      get commandName() {
        return "getMore";
      }
      buildCommand(connection) {
        if (this.cursorId == null || this.cursorId.isZero()) {
          throw new error_1.MongoRuntimeError("Unable to iterate cursor with no id");
        }
        const collection = this.ns.collection;
        if (collection == null) {
          throw new error_1.MongoRuntimeError("A collection name must be determined before getMore");
        }
        const getMoreCmd = {
          getMore: this.cursorId,
          collection
        };
        if (typeof this.options.batchSize === "number") {
          getMoreCmd.batchSize = Math.abs(this.options.batchSize);
        }
        if (typeof this.options.maxAwaitTimeMS === "number") {
          getMoreCmd.maxTimeMS = this.options.maxAwaitTimeMS;
        }
        if (this.options.comment !== void 0 && (0, utils_1.maxWireVersion)(connection) >= 9) {
          getMoreCmd.comment = this.options.comment;
        }
        return getMoreCmd;
      }
      buildOptions(timeoutContext) {
        return {
          returnFieldSelector: null,
          documentsReturnedIn: "nextBatch",
          timeoutContext,
          ...this.options
        };
      }
      handleOk(response) {
        return response;
      }
    };
    exports2.GetMoreOperation = GetMoreOperation;
    (0, operation_1.defineAspects)(GetMoreOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.MUST_SELECT_SAME_SERVER]);
  }
});

// node_modules/mongodb/lib/operations/kill_cursors.js
var require_kill_cursors = __commonJS({
  "node_modules/mongodb/lib/operations/kill_cursors.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.KillCursorsOperation = void 0;
    var responses_1 = require_responses();
    var error_1 = require_error();
    var operation_1 = require_operation();
    var KillCursorsOperation = class extends operation_1.AbstractOperation {
      constructor(cursorId, ns, server, options) {
        super(options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.ns = ns;
        this.cursorId = cursorId;
        this.server = server;
      }
      get commandName() {
        return "killCursors";
      }
      buildCommand(_connection, _session) {
        const killCursors = this.ns.collection;
        if (killCursors == null) {
          throw new error_1.MongoRuntimeError("A collection name must be determined before killCursors");
        }
        const killCursorsCommand = {
          killCursors,
          cursors: [this.cursorId]
        };
        return killCursorsCommand;
      }
      buildOptions(timeoutContext) {
        return {
          session: this.session,
          timeoutContext
        };
      }
      handleError(_error) {
      }
    };
    exports2.KillCursorsOperation = KillCursorsOperation;
    (0, operation_1.defineAspects)(KillCursorsOperation, [operation_1.Aspect.MUST_SELECT_SAME_SERVER]);
  }
});

// node_modules/mongodb/lib/cmap/metrics.js
var require_metrics = __commonJS({
  "node_modules/mongodb/lib/cmap/metrics.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ConnectionPoolMetrics = void 0;
    var ConnectionPoolMetrics = class _ConnectionPoolMetrics {
      constructor() {
        this.txnConnections = 0;
        this.cursorConnections = 0;
        this.otherConnections = 0;
      }
      static {
        this.TXN = "txn";
      }
      static {
        this.CURSOR = "cursor";
      }
      static {
        this.OTHER = "other";
      }
      /**
       * Mark a connection as pinned for a specific operation.
       */
      markPinned(pinType) {
        if (pinType === _ConnectionPoolMetrics.TXN) {
          this.txnConnections += 1;
        } else if (pinType === _ConnectionPoolMetrics.CURSOR) {
          this.cursorConnections += 1;
        } else {
          this.otherConnections += 1;
        }
      }
      /**
       * Unmark a connection as pinned for an operation.
       */
      markUnpinned(pinType) {
        if (pinType === _ConnectionPoolMetrics.TXN) {
          this.txnConnections -= 1;
        } else if (pinType === _ConnectionPoolMetrics.CURSOR) {
          this.cursorConnections -= 1;
        } else {
          this.otherConnections -= 1;
        }
      }
      /**
       * Return information about the cmap metrics as a string.
       */
      info(maxPoolSize) {
        return `Timed out while checking out a connection from connection pool: maxPoolSize: ${maxPoolSize}, connections in use by cursors: ${this.cursorConnections}, connections in use by transactions: ${this.txnConnections}, connections in use by other operations: ${this.otherConnections}`;
      }
      /**
       * Reset the metrics to the initial values.
       */
      reset() {
        this.txnConnections = 0;
        this.cursorConnections = 0;
        this.otherConnections = 0;
      }
    };
    exports2.ConnectionPoolMetrics = ConnectionPoolMetrics;
  }
});

// node_modules/mongodb/lib/transactions.js
var require_transactions = __commonJS({
  "node_modules/mongodb/lib/transactions.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Transaction = exports2.TxnState = void 0;
    exports2.isTransactionCommand = isTransactionCommand;
    var error_1 = require_error();
    var read_concern_1 = require_read_concern();
    var read_preference_1 = require_read_preference();
    var write_concern_1 = require_write_concern();
    exports2.TxnState = Object.freeze({
      NO_TRANSACTION: "NO_TRANSACTION",
      STARTING_TRANSACTION: "STARTING_TRANSACTION",
      TRANSACTION_IN_PROGRESS: "TRANSACTION_IN_PROGRESS",
      TRANSACTION_COMMITTED: "TRANSACTION_COMMITTED",
      TRANSACTION_COMMITTED_EMPTY: "TRANSACTION_COMMITTED_EMPTY",
      TRANSACTION_ABORTED: "TRANSACTION_ABORTED"
    });
    var stateMachine = {
      [exports2.TxnState.NO_TRANSACTION]: [exports2.TxnState.NO_TRANSACTION, exports2.TxnState.STARTING_TRANSACTION],
      [exports2.TxnState.STARTING_TRANSACTION]: [
        exports2.TxnState.TRANSACTION_IN_PROGRESS,
        exports2.TxnState.TRANSACTION_COMMITTED,
        exports2.TxnState.TRANSACTION_COMMITTED_EMPTY,
        exports2.TxnState.TRANSACTION_ABORTED
      ],
      [exports2.TxnState.TRANSACTION_IN_PROGRESS]: [
        exports2.TxnState.TRANSACTION_IN_PROGRESS,
        exports2.TxnState.TRANSACTION_COMMITTED,
        exports2.TxnState.TRANSACTION_ABORTED
      ],
      [exports2.TxnState.TRANSACTION_COMMITTED]: [
        exports2.TxnState.TRANSACTION_COMMITTED,
        exports2.TxnState.TRANSACTION_COMMITTED_EMPTY,
        exports2.TxnState.STARTING_TRANSACTION,
        exports2.TxnState.NO_TRANSACTION
      ],
      [exports2.TxnState.TRANSACTION_ABORTED]: [exports2.TxnState.STARTING_TRANSACTION, exports2.TxnState.NO_TRANSACTION],
      [exports2.TxnState.TRANSACTION_COMMITTED_EMPTY]: [
        exports2.TxnState.TRANSACTION_COMMITTED_EMPTY,
        exports2.TxnState.NO_TRANSACTION
      ]
    };
    var ACTIVE_STATES = /* @__PURE__ */ new Set([
      exports2.TxnState.STARTING_TRANSACTION,
      exports2.TxnState.TRANSACTION_IN_PROGRESS
    ]);
    var COMMITTED_STATES = /* @__PURE__ */ new Set([
      exports2.TxnState.TRANSACTION_COMMITTED,
      exports2.TxnState.TRANSACTION_COMMITTED_EMPTY,
      exports2.TxnState.TRANSACTION_ABORTED
    ]);
    var Transaction = class {
      /** Create a transaction */
      constructor(options) {
        options = options ?? {};
        this.state = exports2.TxnState.NO_TRANSACTION;
        this.options = {};
        const writeConcern = write_concern_1.WriteConcern.fromOptions(options);
        if (writeConcern) {
          if (writeConcern.w === 0) {
            throw new error_1.MongoTransactionError("Transactions do not support unacknowledged write concern");
          }
          this.options.writeConcern = writeConcern;
        }
        if (options.readConcern) {
          this.options.readConcern = read_concern_1.ReadConcern.fromOptions(options);
        }
        if (options.readPreference) {
          this.options.readPreference = read_preference_1.ReadPreference.fromOptions(options);
        }
        if (options.maxCommitTimeMS) {
          this.options.maxTimeMS = options.maxCommitTimeMS;
        }
        this._pinnedServer = void 0;
        this._recoveryToken = void 0;
      }
      get server() {
        return this._pinnedServer;
      }
      get recoveryToken() {
        return this._recoveryToken;
      }
      get isPinned() {
        return !!this.server;
      }
      /**
       * @returns Whether the transaction has started
       */
      get isStarting() {
        return this.state === exports2.TxnState.STARTING_TRANSACTION;
      }
      /**
       * @returns Whether this session is presently in a transaction
       */
      get isActive() {
        return ACTIVE_STATES.has(this.state);
      }
      get isCommitted() {
        return COMMITTED_STATES.has(this.state);
      }
      /**
       * Transition the transaction in the state machine
       * @param nextState - The new state to transition to
       */
      transition(nextState) {
        const nextStates = stateMachine[this.state];
        if (nextStates && nextStates.includes(nextState)) {
          this.state = nextState;
          if (this.state === exports2.TxnState.NO_TRANSACTION || this.state === exports2.TxnState.STARTING_TRANSACTION || this.state === exports2.TxnState.TRANSACTION_ABORTED) {
            this.unpinServer();
          }
          return;
        }
        throw new error_1.MongoRuntimeError(`Attempted illegal state transition from [${this.state}] to [${nextState}]`);
      }
      pinServer(server) {
        if (this.isActive) {
          this._pinnedServer = server;
        }
      }
      unpinServer() {
        this._pinnedServer = void 0;
      }
    };
    exports2.Transaction = Transaction;
    function isTransactionCommand(command) {
      return !!(command.commitTransaction || command.abortTransaction);
    }
  }
});

// node_modules/mongodb/lib/sessions.js
var require_sessions = __commonJS({
  "node_modules/mongodb/lib/sessions.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ServerSessionPool = exports2.ServerSession = exports2.ClientSession = void 0;
    exports2.maybeClearPinnedConnection = maybeClearPinnedConnection;
    exports2.applySession = applySession;
    exports2.updateSessionFromResponse = updateSessionFromResponse;
    var promises_1 = require("timers/promises");
    var bson_1 = require_bson2();
    var metrics_1 = require_metrics();
    var constants_1 = require_constants2();
    var error_1 = require_error();
    var mongo_types_1 = require_mongo_types();
    var execute_operation_1 = require_execute_operation();
    var run_command_1 = require_run_command();
    var read_concern_1 = require_read_concern();
    var read_preference_1 = require_read_preference();
    var common_1 = require_common();
    var timeout_1 = require_timeout();
    var transactions_1 = require_transactions();
    var utils_1 = require_utils();
    var write_concern_1 = require_write_concern();
    var ClientSession = class _ClientSession extends mongo_types_1.TypedEventEmitter {
      /**
       * Create a client session.
       * @internal
       * @param client - The current client
       * @param sessionPool - The server session pool (Internal Class)
       * @param options - Optional settings
       * @param clientOptions - Optional settings provided when creating a MongoClient
       */
      constructor(client, sessionPool, options, clientOptions) {
        super();
        this.timeoutContext = null;
        this.on("error", utils_1.noop);
        if (client == null) {
          throw new error_1.MongoRuntimeError("ClientSession requires a MongoClient");
        }
        if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) {
          throw new error_1.MongoRuntimeError("ClientSession requires a ServerSessionPool");
        }
        options = options ?? {};
        this.snapshotEnabled = options.snapshot === true;
        if (options.causalConsistency === true && this.snapshotEnabled) {
          throw new error_1.MongoInvalidArgumentError('Properties "causalConsistency" and "snapshot" are mutually exclusive');
        }
        this.client = client;
        this.sessionPool = sessionPool;
        this.hasEnded = false;
        this.clientOptions = clientOptions;
        this.timeoutMS = options.defaultTimeoutMS ?? client.s.options?.timeoutMS;
        this.explicit = !!options.explicit;
        this._serverSession = this.explicit ? this.sessionPool.acquire() : null;
        this.txnNumberIncrement = 0;
        const defaultCausalConsistencyValue = this.explicit && options.snapshot !== true;
        this.supports = {
          // if we can enable causal consistency, do so by default
          causalConsistency: options.causalConsistency ?? defaultCausalConsistencyValue
        };
        this.clusterTime = options.initialClusterTime;
        this.operationTime = void 0;
        this.owner = options.owner;
        this.defaultTransactionOptions = { ...options.defaultTransactionOptions };
        this.transaction = new transactions_1.Transaction();
      }
      /** The server id associated with this session */
      get id() {
        return this.serverSession?.id;
      }
      get serverSession() {
        let serverSession = this._serverSession;
        if (serverSession == null) {
          if (this.explicit) {
            throw new error_1.MongoRuntimeError("Unexpected null serverSession for an explicit session");
          }
          if (this.hasEnded) {
            throw new error_1.MongoRuntimeError("Unexpected null serverSession for an ended implicit session");
          }
          serverSession = this.sessionPool.acquire();
          this._serverSession = serverSession;
        }
        return serverSession;
      }
      get loadBalanced() {
        return this.client.topology?.description.type === common_1.TopologyType.LoadBalanced;
      }
      /** @internal */
      pin(conn) {
        if (this.pinnedConnection) {
          throw TypeError("Cannot pin multiple connections to the same session");
        }
        this.pinnedConnection = conn;
        conn.emit(constants_1.PINNED, this.inTransaction() ? metrics_1.ConnectionPoolMetrics.TXN : metrics_1.ConnectionPoolMetrics.CURSOR);
      }
      /** @internal */
      unpin(options) {
        if (this.loadBalanced) {
          return maybeClearPinnedConnection(this, options);
        }
        this.transaction.unpinServer();
      }
      get isPinned() {
        return this.loadBalanced ? !!this.pinnedConnection : this.transaction.isPinned;
      }
      /**
       * Frees any client-side resources held by the current session.  If a session is in a transaction,
       * the transaction is aborted.
       *
       * Does not end the session on the server.
       *
       * @param options - Optional settings. Currently reserved for future use
       */
      async endSession(options) {
        try {
          if (this.inTransaction()) {
            await this.abortTransaction({ ...options, throwTimeout: true });
          }
        } catch (error51) {
          if (error51.name === "MongoOperationTimeoutError")
            throw error51;
          (0, utils_1.squashError)(error51);
        } finally {
          if (!this.hasEnded) {
            const serverSession = this.serverSession;
            if (serverSession != null) {
              this.sessionPool.release(serverSession);
              this._serverSession = new ServerSession(serverSession);
            }
            this.hasEnded = true;
            this.emit("ended", this);
          }
          maybeClearPinnedConnection(this, { force: true, ...options });
        }
      }
      /**
       * An alias for {@link ClientSession.endSession|ClientSession.endSession()}.
       */
      async [Symbol.asyncDispose]() {
        await this.endSession({ force: true });
      }
      /**
       * Advances the operationTime for a ClientSession.
       *
       * @param operationTime - the `BSON.Timestamp` of the operation type it is desired to advance to
       */
      advanceOperationTime(operationTime) {
        if (this.operationTime == null) {
          this.operationTime = operationTime;
          return;
        }
        if (operationTime.greaterThan(this.operationTime)) {
          this.operationTime = operationTime;
        }
      }
      /**
       * Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession
       *
       * @param clusterTime - the $clusterTime returned by the server from another session in the form of a document containing the `BSON.Timestamp` clusterTime and signature
       */
      advanceClusterTime(clusterTime) {
        if (!clusterTime || typeof clusterTime !== "object") {
          throw new error_1.MongoInvalidArgumentError("input cluster time must be an object");
        }
        if (!clusterTime.clusterTime || clusterTime.clusterTime._bsontype !== "Timestamp") {
          throw new error_1.MongoInvalidArgumentError('input cluster time "clusterTime" property must be a valid BSON Timestamp');
        }
        if (!clusterTime.signature || clusterTime.signature.hash?._bsontype !== "Binary" || typeof clusterTime.signature.keyId !== "bigint" && typeof clusterTime.signature.keyId !== "number" && clusterTime.signature.keyId?._bsontype !== "Long") {
          throw new error_1.MongoInvalidArgumentError('input cluster time must have a valid "signature" property with BSON Binary hash and BSON Long keyId');
        }
        (0, common_1._advanceClusterTime)(this, clusterTime);
      }
      /**
       * Used to determine if this session equals another
       *
       * @param session - The session to compare to
       */
      equals(session) {
        if (!(session instanceof _ClientSession)) {
          return false;
        }
        if (this.id == null || session.id == null) {
          return false;
        }
        return bson_1.ByteUtils.equals(this.id.id.buffer, session.id.id.buffer);
      }
      /**
       * Increment the transaction number on the internal ServerSession
       *
       * @privateRemarks
       * This helper increments a value stored on the client session that will be
       * added to the serverSession's txnNumber upon applying it to a command.
       * This is because the serverSession is lazily acquired after a connection is obtained
       */
      incrementTransactionNumber() {
        this.txnNumberIncrement += 1;
      }
      /** @returns whether this session is currently in a transaction or not */
      inTransaction() {
        return this.transaction.isActive;
      }
      /**
       * Starts a new transaction with the given options.
       *
       * @remarks
       * **IMPORTANT**: Running operations in parallel is not supported during a transaction. The use of `Promise.all`,
       * `Promise.allSettled`, `Promise.race`, etc to parallelize operations inside a transaction is
       * undefined behaviour.
       *
       * @param options - Options for the transaction
       */
      startTransaction(options) {
        if (this.snapshotEnabled) {
          throw new error_1.MongoCompatibilityError("Transactions are not supported in snapshot sessions");
        }
        if (this.inTransaction()) {
          throw new error_1.MongoTransactionError("Transaction already in progress");
        }
        if (this.isPinned && this.transaction.isCommitted) {
          this.unpin();
        }
        this.commitAttempted = false;
        this.incrementTransactionNumber();
        this.transaction = new transactions_1.Transaction({
          readConcern: options?.readConcern ?? this.defaultTransactionOptions.readConcern ?? this.clientOptions?.readConcern,
          writeConcern: options?.writeConcern ?? this.defaultTransactionOptions.writeConcern ?? this.clientOptions?.writeConcern,
          readPreference: options?.readPreference ?? this.defaultTransactionOptions.readPreference ?? this.clientOptions?.readPreference,
          maxCommitTimeMS: options?.maxCommitTimeMS ?? this.defaultTransactionOptions.maxCommitTimeMS
        });
        this.transaction.transition(transactions_1.TxnState.STARTING_TRANSACTION);
      }
      /**
       * Commits the currently active transaction in this session.
       *
       * @param options - Optional options, can be used to override `defaultTimeoutMS`.
       */
      async commitTransaction(options) {
        if (this.transaction.state === transactions_1.TxnState.NO_TRANSACTION) {
          throw new error_1.MongoTransactionError("No transaction started");
        }
        if (this.transaction.state === transactions_1.TxnState.STARTING_TRANSACTION || this.transaction.state === transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY) {
          this.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY);
          return;
        }
        if (this.transaction.state === transactions_1.TxnState.TRANSACTION_ABORTED) {
          throw new error_1.MongoTransactionError("Cannot call commitTransaction after calling abortTransaction");
        }
        const command = { commitTransaction: 1 };
        const timeoutMS = typeof options?.timeoutMS === "number" ? options.timeoutMS : typeof this.timeoutMS === "number" ? this.timeoutMS : null;
        const wc = this.transaction.options.writeConcern ?? this.clientOptions?.writeConcern;
        if (wc != null) {
          if (timeoutMS == null && this.timeoutContext == null) {
            write_concern_1.WriteConcern.apply(command, { wtimeoutMS: 1e4, w: "majority", ...wc });
          } else {
            const wcKeys = Object.keys(wc);
            if (wcKeys.length > 2 || !wcKeys.includes("wtimeoutMS") && !wcKeys.includes("wTimeoutMS"))
              write_concern_1.WriteConcern.apply(command, { ...wc, wtimeoutMS: void 0 });
          }
        }
        if (this.transaction.state === transactions_1.TxnState.TRANSACTION_COMMITTED || this.commitAttempted) {
          if (timeoutMS == null && this.timeoutContext == null) {
            write_concern_1.WriteConcern.apply(command, { wtimeoutMS: 1e4, ...wc, w: "majority" });
          } else {
            write_concern_1.WriteConcern.apply(command, { w: "majority", ...wc, wtimeoutMS: void 0 });
          }
        }
        if (typeof this.transaction.options.maxTimeMS === "number") {
          command.maxTimeMS = this.transaction.options.maxTimeMS;
        }
        if (this.transaction.recoveryToken) {
          command.recoveryToken = this.transaction.recoveryToken;
        }
        const operation = new run_command_1.RunCommandOperation(new utils_1.MongoDBNamespace("admin"), command, {
          session: this,
          readPreference: read_preference_1.ReadPreference.primary,
          bypassPinningCheck: true
        });
        operation.maxAttempts = this.clientOptions.maxAdaptiveRetries + 1;
        const timeoutContext = this.timeoutContext ?? (typeof timeoutMS === "number" ? timeout_1.TimeoutContext.create({
          serverSelectionTimeoutMS: this.clientOptions.serverSelectionTimeoutMS,
          socketTimeoutMS: this.clientOptions.socketTimeoutMS,
          timeoutMS
        }) : null);
        try {
          await (0, execute_operation_1.executeOperation)(this.client, operation, timeoutContext);
          this.commitAttempted = void 0;
          return;
        } catch (firstCommitError) {
          this.commitAttempted = true;
          const remainingAttempts = this.clientOptions.maxAdaptiveRetries + 1 - operation.attemptsMade;
          if (remainingAttempts <= 0) {
            throw firstCommitError;
          }
          if (firstCommitError instanceof error_1.MongoError && (0, error_1.isRetryableWriteError)(firstCommitError)) {
            write_concern_1.WriteConcern.apply(command, { wtimeoutMS: 1e4, ...wc, w: "majority" });
            this.unpin({ force: true });
            try {
              const op = new run_command_1.RunCommandOperation(new utils_1.MongoDBNamespace("admin"), command, {
                session: this,
                readPreference: read_preference_1.ReadPreference.primary,
                bypassPinningCheck: true
              });
              op.maxAttempts = remainingAttempts;
              await (0, execute_operation_1.executeOperation)(this.client, op, timeoutContext);
              return;
            } catch (retryCommitError) {
              if (shouldAddUnknownTransactionCommitResultLabel(retryCommitError)) {
                retryCommitError.addErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult);
              }
              if (shouldUnpinAfterCommitError(retryCommitError)) {
                this.unpin({ error: retryCommitError });
              }
              throw retryCommitError;
            }
          }
          if (shouldAddUnknownTransactionCommitResultLabel(firstCommitError)) {
            firstCommitError.addErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult);
          }
          if (shouldUnpinAfterCommitError(firstCommitError)) {
            this.unpin({ error: firstCommitError });
          }
          throw firstCommitError;
        } finally {
          this.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED);
        }
      }
      async abortTransaction(options) {
        if (this.transaction.state === transactions_1.TxnState.NO_TRANSACTION) {
          throw new error_1.MongoTransactionError("No transaction started");
        }
        if (this.transaction.state === transactions_1.TxnState.STARTING_TRANSACTION) {
          this.transaction.transition(transactions_1.TxnState.TRANSACTION_ABORTED);
          return;
        }
        if (this.transaction.state === transactions_1.TxnState.TRANSACTION_ABORTED) {
          throw new error_1.MongoTransactionError("Cannot call abortTransaction twice");
        }
        if (this.transaction.state === transactions_1.TxnState.TRANSACTION_COMMITTED || this.transaction.state === transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY) {
          throw new error_1.MongoTransactionError("Cannot call abortTransaction after calling commitTransaction");
        }
        const command = { abortTransaction: 1 };
        const timeoutMS = typeof options?.timeoutMS === "number" ? options.timeoutMS : this.timeoutContext?.csotEnabled() ? this.timeoutContext.timeoutMS : typeof this.timeoutMS === "number" ? this.timeoutMS : null;
        const timeoutContext = timeoutMS != null ? timeout_1.TimeoutContext.create({
          timeoutMS,
          serverSelectionTimeoutMS: this.clientOptions.serverSelectionTimeoutMS,
          socketTimeoutMS: this.clientOptions.socketTimeoutMS
        }) : null;
        const wc = this.transaction.options.writeConcern ?? this.clientOptions?.writeConcern;
        if (wc != null && timeoutMS == null) {
          write_concern_1.WriteConcern.apply(command, { wtimeoutMS: 1e4, w: "majority", ...wc });
        }
        if (this.transaction.recoveryToken) {
          command.recoveryToken = this.transaction.recoveryToken;
        }
        const operation = new run_command_1.RunCommandOperation(new utils_1.MongoDBNamespace("admin"), command, {
          session: this,
          readPreference: read_preference_1.ReadPreference.primary,
          bypassPinningCheck: true
        });
        try {
          await (0, execute_operation_1.executeOperation)(this.client, operation, timeoutContext);
          this.unpin();
          return;
        } catch (firstAbortError) {
          this.unpin();
          if (firstAbortError.name === "MongoRuntimeError")
            throw firstAbortError;
          if (options?.throwTimeout && firstAbortError.name === "MongoOperationTimeoutError") {
            throw firstAbortError;
          }
          if (firstAbortError instanceof error_1.MongoError && (0, error_1.isRetryableWriteError)(firstAbortError)) {
            try {
              await (0, execute_operation_1.executeOperation)(this.client, operation, timeoutContext);
              return;
            } catch (secondAbortError) {
              if (secondAbortError.name === "MongoRuntimeError")
                throw secondAbortError;
              if (options?.throwTimeout && secondAbortError.name === "MongoOperationTimeoutError") {
                throw secondAbortError;
              }
            }
          }
        } finally {
          this.transaction.transition(transactions_1.TxnState.TRANSACTION_ABORTED);
          if (this.loadBalanced) {
            maybeClearPinnedConnection(this, { force: false });
          }
        }
      }
      /**
       * This is here to ensure that ClientSession is never serialized to BSON.
       */
      toBSON() {
        throw new error_1.MongoRuntimeError("ClientSession cannot be serialized to BSON.");
      }
      /**
       * Starts a transaction and runs a provided function, ensuring the commitTransaction is always attempted when all operations run in the function have completed.
       *
       * **IMPORTANT:** This method requires the function passed in to return a Promise. That promise must be made by `await`-ing all operations in such a way that rejections are propagated to the returned promise.
       *
       * **IMPORTANT:** Running operations in parallel is not supported during a transaction. The use of `Promise.all`,
       * `Promise.allSettled`, `Promise.race`, etc to parallelize operations inside a transaction is
       * undefined behaviour.
       *
       * **IMPORTANT:** When running an operation inside a `withTransaction` callback, if it is not
       * provided the explicit session in its options, it will not be part of the transaction and it will not respect timeoutMS.
       *
       *
       * @remarks
       * - If all operations successfully complete and the `commitTransaction` operation is successful, then the provided function will return the result of the provided function.
       * - If the transaction is unable to complete or an error is thrown from within the provided function, then the provided function will throw an error.
       *   - If the transaction is manually aborted within the provided function it will not throw.
       * - If the driver needs to attempt to retry the operations, the provided function may be called multiple times.
       *
       * Checkout a descriptive example here:
       * @see https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-implement-transactions
       *
       * If a command inside withTransaction fails:
       * - It may cause the transaction on the server to be aborted.
       * - This situation is normally handled transparently by the driver.
       * - However, if the application catches such an error and does not rethrow it, the driver will not be able to determine whether the transaction was aborted or not.
       * - The driver will then retry the transaction indefinitely.
       *
       * To avoid this situation, the application must not silently handle errors within the provided function.
       * If the application needs to handle errors within, it must await all operations such that if an operation is rejected it becomes the rejection of the callback function passed into withTransaction.
       *
       * @param fn - callback to run within a transaction
       * @param options - optional settings for the transaction
       * @returns A raw command response or undefined
       */
      async withTransaction(fn, options) {
        const MAX_TIMEOUT = 12e4;
        const timeoutMS = options?.timeoutMS ?? this.timeoutMS ?? null;
        this.timeoutContext = timeoutMS != null ? timeout_1.TimeoutContext.create({
          timeoutMS,
          serverSelectionTimeoutMS: this.clientOptions.serverSelectionTimeoutMS,
          socketTimeoutMS: this.clientOptions.socketTimeoutMS
        }) : null;
        const csotEnabled = !!this.timeoutContext?.csotEnabled();
        const remainingTimeMS = this.timeoutContext?.csotEnabled() ? this.timeoutContext.remainingTimeMS : MAX_TIMEOUT;
        const deadline = (0, utils_1.processTimeMS)() + remainingTimeMS;
        let committed = false;
        let result;
        let lastError = null;
        try {
          retryTransaction: for (let transactionAttempt = 0, isRetry = false; !committed; ++transactionAttempt, isRetry = transactionAttempt > 0) {
            if (isRetry) {
              const BACKOFF_INITIAL_MS = 5;
              const BACKOFF_MAX_MS = 500;
              const BACKOFF_GROWTH = 1.5;
              const jitter = Math.random();
              const backoffMS = jitter * Math.min(BACKOFF_INITIAL_MS * BACKOFF_GROWTH ** (transactionAttempt - 1), BACKOFF_MAX_MS);
              if ((0, utils_1.processTimeMS)() + backoffMS >= deadline) {
                throw makeTimeoutError(lastError ?? new error_1.MongoRuntimeError(`Transaction retry did not record an error: should never occur. Please file a bug.`), csotEnabled);
              }
              await (0, promises_1.setTimeout)(backoffMS);
            }
            this.startTransaction(options);
            try {
              const promise2 = fn(this);
              if (!(0, utils_1.isPromiseLike)(promise2)) {
                throw new error_1.MongoInvalidArgumentError("Function provided to `withTransaction` must return a Promise");
              }
              result = await promise2;
              if (this.transaction.state === transactions_1.TxnState.NO_TRANSACTION || this.transaction.state === transactions_1.TxnState.TRANSACTION_COMMITTED || this.transaction.state === transactions_1.TxnState.TRANSACTION_ABORTED) {
                return result;
              }
            } catch (fnError) {
              if (!(fnError instanceof error_1.MongoError) || fnError instanceof error_1.MongoInvalidArgumentError) {
                await this.abortTransaction();
                throw fnError;
              }
              lastError = fnError;
              if (this.transaction.state === transactions_1.TxnState.STARTING_TRANSACTION || this.transaction.state === transactions_1.TxnState.TRANSACTION_IN_PROGRESS) {
                await this.abortTransaction();
              }
              if (fnError.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) {
                if ((0, utils_1.processTimeMS)() >= deadline) {
                  throw makeTimeoutError(lastError, csotEnabled);
                }
                continue retryTransaction;
              }
              throw fnError;
            }
            retryCommit: while (!committed) {
              try {
                await this.commitTransaction();
                committed = true;
              } catch (commitError) {
                lastError = commitError;
                if (commitError.hasErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult) && !isMaxTimeMSExpiredError(commitError)) {
                  if ((0, utils_1.processTimeMS)() >= deadline) {
                    throw makeTimeoutError(commitError, csotEnabled);
                  }
                  continue retryCommit;
                }
                if (commitError.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) {
                  continue retryTransaction;
                }
                throw commitError;
              }
            }
          }
          return result;
        } finally {
          this.timeoutContext = null;
        }
      }
    };
    exports2.ClientSession = ClientSession;
    function makeTimeoutError(cause, csotEnabled) {
      if (cause instanceof error_1.MongoOperationTimeoutError) {
        return cause;
      }
      if (csotEnabled) {
        const timeoutError = new error_1.MongoOperationTimeoutError("Timed out during withTransaction", {
          cause
        });
        if (cause instanceof error_1.MongoError) {
          for (const label of cause.errorLabels) {
            timeoutError.addErrorLabel(label);
          }
        }
        return timeoutError;
      }
      return cause;
    }
    var NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = /* @__PURE__ */ new Set([
      "CannotSatisfyWriteConcern",
      "UnknownReplWriteConcern",
      "UnsatisfiableWriteConcern"
    ]);
    function shouldUnpinAfterCommitError(commitError) {
      if (commitError instanceof error_1.MongoError) {
        if ((0, error_1.isRetryableWriteError)(commitError) || commitError instanceof error_1.MongoWriteConcernError || isMaxTimeMSExpiredError(commitError)) {
          if (isUnknownTransactionCommitResult(commitError)) {
            return true;
          }
        } else if (commitError.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) {
          return true;
        }
      }
      return false;
    }
    function shouldAddUnknownTransactionCommitResultLabel(commitError) {
      let ok = (0, error_1.isRetryableWriteError)(commitError);
      ok ||= commitError instanceof error_1.MongoWriteConcernError;
      ok ||= isMaxTimeMSExpiredError(commitError);
      ok &&= isUnknownTransactionCommitResult(commitError);
      return ok;
    }
    function isUnknownTransactionCommitResult(err) {
      const isNonDeterministicWriteConcernError = err instanceof error_1.MongoServerError && err.codeName && NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName);
      return isMaxTimeMSExpiredError(err) || !isNonDeterministicWriteConcernError && err.code !== error_1.MONGODB_ERROR_CODES.UnsatisfiableWriteConcern && err.code !== error_1.MONGODB_ERROR_CODES.UnknownReplWriteConcern;
    }
    function maybeClearPinnedConnection(session, options) {
      const conn = session.pinnedConnection;
      const error51 = options?.error;
      if (session.inTransaction() && error51 && error51 instanceof error_1.MongoError && error51.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) {
        return;
      }
      const topology = session.client.topology;
      if (conn && topology != null) {
        const servers = Array.from(topology.s.servers.values());
        const loadBalancer = servers[0];
        if (options?.error == null || options?.force) {
          loadBalancer.pool.checkIn(conn);
          session.pinnedConnection = void 0;
          conn.emit(constants_1.UNPINNED, session.transaction.state !== transactions_1.TxnState.NO_TRANSACTION ? metrics_1.ConnectionPoolMetrics.TXN : metrics_1.ConnectionPoolMetrics.CURSOR);
          if (options?.forceClear) {
            loadBalancer.pool.clear({ serviceId: conn.serviceId });
          }
        }
      }
    }
    function isMaxTimeMSExpiredError(err) {
      if (err == null || !(err instanceof error_1.MongoServerError)) {
        return false;
      }
      return err.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired || err.writeConcernError?.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired;
    }
    var ServerSession = class {
      /** @internal */
      constructor(cloned) {
        if (cloned != null) {
          const idBytes = bson_1.ByteUtils.allocateUnsafe(16);
          idBytes.set(cloned.id.id.buffer);
          this.id = { id: new bson_1.Binary(idBytes, cloned.id.id.sub_type) };
          this.lastUse = cloned.lastUse;
          this.txnNumber = cloned.txnNumber;
          this.isDirty = cloned.isDirty;
          return;
        }
        this.id = { id: new bson_1.Binary((0, utils_1.uuidV4)(), bson_1.Binary.SUBTYPE_UUID) };
        this.lastUse = (0, utils_1.processTimeMS)();
        this.txnNumber = 0;
        this.isDirty = false;
      }
      /**
       * Determines if the server session has timed out.
       *
       * @param sessionTimeoutMinutes - The server's "logicalSessionTimeoutMinutes"
       */
      hasTimedOut(sessionTimeoutMinutes) {
        const idleTimeMinutes = Math.round((0, utils_1.calculateDurationInMs)(this.lastUse) % 864e5 % 36e5 / 6e4);
        return idleTimeMinutes > sessionTimeoutMinutes - 1;
      }
    };
    exports2.ServerSession = ServerSession;
    var ServerSessionPool = class {
      constructor(client) {
        if (client == null) {
          throw new error_1.MongoRuntimeError("ServerSessionPool requires a MongoClient");
        }
        this.client = client;
        this.sessions = new utils_1.List();
      }
      /**
       * Acquire a Server Session from the pool.
       * Iterates through each session in the pool, removing any stale sessions
       * along the way. The first non-stale session found is removed from the
       * pool and returned. If no non-stale session is found, a new ServerSession is created.
       */
      acquire() {
        const sessionTimeoutMinutes = this.client.topology?.logicalSessionTimeoutMinutes ?? 10;
        let session = null;
        while (this.sessions.length > 0) {
          const potentialSession = this.sessions.shift();
          if (potentialSession != null && (!!this.client.topology?.loadBalanced || !potentialSession.hasTimedOut(sessionTimeoutMinutes))) {
            session = potentialSession;
            break;
          }
        }
        if (session == null) {
          session = new ServerSession();
        }
        return session;
      }
      /**
       * Release a session to the session pool
       * Adds the session back to the session pool if the session has not timed out yet.
       * This method also removes any stale sessions from the pool.
       *
       * @param session - The session to release to the pool
       */
      release(session) {
        const sessionTimeoutMinutes = this.client.topology?.logicalSessionTimeoutMinutes ?? 10;
        if (this.client.topology?.loadBalanced && !sessionTimeoutMinutes) {
          this.sessions.unshift(session);
        }
        if (!sessionTimeoutMinutes) {
          return;
        }
        this.sessions.prune((session2) => session2.hasTimedOut(sessionTimeoutMinutes));
        if (!session.hasTimedOut(sessionTimeoutMinutes)) {
          if (session.isDirty) {
            return;
          }
          this.sessions.unshift(session);
        }
      }
    };
    exports2.ServerSessionPool = ServerSessionPool;
    function applySession(session, command, options) {
      if (session.hasEnded) {
        return new error_1.MongoExpiredSessionError();
      }
      const serverSession = session.serverSession;
      if (serverSession == null) {
        return new error_1.MongoRuntimeError("Unable to acquire server session");
      }
      if (options.writeConcern?.w === 0) {
        if (session && session.explicit) {
          return new error_1.MongoAPIError("Cannot have explicit session with unacknowledged writes");
        }
        return;
      }
      serverSession.lastUse = (0, utils_1.processTimeMS)();
      command.lsid = serverSession.id;
      const inTxnOrTxnCommand = session.inTransaction() || (0, transactions_1.isTransactionCommand)(command);
      const isRetryableWrite = !!options.willRetryWrite;
      if (isRetryableWrite || inTxnOrTxnCommand) {
        serverSession.txnNumber += session.txnNumberIncrement;
        session.txnNumberIncrement = 0;
        command.txnNumber = bson_1.Long.fromNumber(serverSession.txnNumber);
      }
      if (!inTxnOrTxnCommand) {
        if (session.transaction.state !== transactions_1.TxnState.NO_TRANSACTION) {
          session.transaction.transition(transactions_1.TxnState.NO_TRANSACTION);
        }
        if (session.supports.causalConsistency && session.operationTime && (0, utils_1.commandSupportsAfterClusterTime)(command)) {
          command.readConcern = command.readConcern || {};
          Object.assign(command.readConcern, { afterClusterTime: session.operationTime });
        } else if (session.snapshotEnabled) {
          command.readConcern = command.readConcern || { level: read_concern_1.ReadConcernLevel.snapshot };
          if (session.snapshotTime != null) {
            Object.assign(command.readConcern, { atClusterTime: session.snapshotTime });
          }
        }
        return;
      }
      command.autocommit = false;
      if (session.transaction.state === transactions_1.TxnState.STARTING_TRANSACTION) {
        command.startTransaction = true;
        const readConcern = session.transaction.options.readConcern || session?.clientOptions?.readConcern;
        if (readConcern) {
          command.readConcern = readConcern;
        }
        if (session.supports.causalConsistency && session.operationTime) {
          command.readConcern = command.readConcern || {};
          Object.assign(command.readConcern, { afterClusterTime: session.operationTime });
        }
      }
      return;
    }
    function updateSessionFromResponse(session, document2) {
      if (document2.$clusterTime) {
        (0, common_1._advanceClusterTime)(session, document2.$clusterTime);
      }
      if (document2.operationTime && session && session.supports.causalConsistency) {
        session.advanceOperationTime(document2.operationTime);
      }
      if (document2.recoveryToken && session && session.inTransaction()) {
        session.transaction._recoveryToken = document2.recoveryToken;
      }
      if (session?.snapshotEnabled && session.snapshotTime == null) {
        const atClusterTime = document2.atClusterTime;
        if (atClusterTime) {
          session.snapshotTime = atClusterTime;
        }
      }
      if (session.transaction.state === transactions_1.TxnState.STARTING_TRANSACTION) {
        if (document2.ok === 1) {
          session.transaction.transition(transactions_1.TxnState.TRANSACTION_IN_PROGRESS);
        } else {
          const error51 = new error_1.MongoServerError(document2.toObject());
          const isRetryableError = error51.hasErrorLabel(error_1.MongoErrorLabel.RetryableError);
          if (!isRetryableError) {
            session.transaction.transition(transactions_1.TxnState.TRANSACTION_IN_PROGRESS);
          }
        }
      }
    }
  }
});

// node_modules/mongodb/lib/cursor/abstract_cursor.js
var require_abstract_cursor = __commonJS({
  "node_modules/mongodb/lib/cursor/abstract_cursor.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CursorTimeoutContext = exports2.AbstractCursor = exports2.CursorTimeoutMode = exports2.CURSOR_FLAGS = void 0;
    var stream_1 = require("stream");
    var bson_1 = require_bson2();
    var error_1 = require_error();
    var mongo_types_1 = require_mongo_types();
    var execute_operation_1 = require_execute_operation();
    var get_more_1 = require_get_more();
    var kill_cursors_1 = require_kill_cursors();
    var read_concern_1 = require_read_concern();
    var read_preference_1 = require_read_preference();
    var sessions_1 = require_sessions();
    var timeout_1 = require_timeout();
    var utils_1 = require_utils();
    exports2.CURSOR_FLAGS = [
      "tailable",
      "oplogReplay",
      "noCursorTimeout",
      "awaitData",
      "exhaust",
      "partial"
    ];
    function removeActiveCursor() {
      this.client.s.activeCursors.delete(this);
    }
    exports2.CursorTimeoutMode = Object.freeze({
      ITERATION: "iteration",
      LIFETIME: "cursorLifetime"
    });
    var AbstractCursor = class extends mongo_types_1.TypedEventEmitter {
      static {
        this.CLOSE = "close";
      }
      /** @internal */
      constructor(client, namespace, options = {}) {
        super();
        this.documents = null;
        this.hasEmittedClose = false;
        this.on("error", utils_1.noop);
        if (!client.s.isMongoClient) {
          throw new error_1.MongoRuntimeError("Cursor must be constructed with MongoClient");
        }
        this.cursorClient = client;
        this.cursorNamespace = namespace;
        this.cursorId = null;
        this.initialized = false;
        this.isClosed = false;
        this.isKilled = false;
        this.cursorOptions = {
          readPreference: options.readPreference && options.readPreference instanceof read_preference_1.ReadPreference ? options.readPreference : read_preference_1.ReadPreference.primary,
          ...(0, bson_1.pluckBSONSerializeOptions)(options),
          timeoutMS: options?.timeoutContext?.csotEnabled() ? options.timeoutContext.timeoutMS : options.timeoutMS,
          tailable: options.tailable,
          awaitData: options.awaitData
        };
        if (this.cursorOptions.timeoutMS != null) {
          if (options.timeoutMode == null) {
            if (options.tailable) {
              if (options.awaitData) {
                if (options.maxAwaitTimeMS != null && options.maxAwaitTimeMS >= this.cursorOptions.timeoutMS)
                  throw new error_1.MongoInvalidArgumentError("Cannot specify maxAwaitTimeMS >= timeoutMS for a tailable awaitData cursor");
              }
              this.cursorOptions.timeoutMode = exports2.CursorTimeoutMode.ITERATION;
            } else {
              this.cursorOptions.timeoutMode = exports2.CursorTimeoutMode.LIFETIME;
            }
          } else {
            if (options.tailable && options.timeoutMode === exports2.CursorTimeoutMode.LIFETIME) {
              throw new error_1.MongoInvalidArgumentError("Cannot set tailable cursor's timeoutMode to LIFETIME");
            }
            this.cursorOptions.timeoutMode = options.timeoutMode;
          }
        } else {
          if (options.timeoutMode != null)
            throw new error_1.MongoInvalidArgumentError("Cannot set timeoutMode without setting timeoutMS");
        }
        this.cursorOptions.omitMaxTimeMS = this.cursorOptions.timeoutMS != null && (this.cursorOptions.timeoutMode === exports2.CursorTimeoutMode.ITERATION && !this.cursorOptions.tailable || this.cursorOptions.tailable && !this.cursorOptions.awaitData);
        const readConcern = read_concern_1.ReadConcern.fromOptions(options);
        if (readConcern) {
          this.cursorOptions.readConcern = readConcern;
        }
        if (typeof options.batchSize === "number") {
          this.cursorOptions.batchSize = options.batchSize;
        }
        if (options.comment !== void 0) {
          this.cursorOptions.comment = options.comment;
        }
        if (typeof options.maxTimeMS === "number") {
          this.cursorOptions.maxTimeMS = options.maxTimeMS;
        }
        if (typeof options.maxAwaitTimeMS === "number") {
          this.cursorOptions.maxAwaitTimeMS = options.maxAwaitTimeMS;
        }
        this.cursorSession = options.session ?? null;
        this.deserializationOptions = {
          ...this.cursorOptions,
          validation: {
            utf8: options?.enableUtf8Validation === false ? false : true
          }
        };
        this.timeoutContext = options.timeoutContext;
        this.signal = options.signal;
        this.abortListener = (0, utils_1.addAbortListener)(this.signal, () => void this.close().then(void 0, utils_1.squashError));
        this.trackCursor();
      }
      /**
       * The cursor has no id until it receives a response from the initial cursor creating command.
       *
       * It is non-zero for as long as the database has an open cursor.
       *
       * The initiating command may receive a zero id if the entire result is in the `firstBatch`.
       */
      get id() {
        return this.cursorId ?? void 0;
      }
      /** @internal */
      get isDead() {
        return (this.cursorId?.isZero() ?? false) || this.isClosed || this.isKilled;
      }
      /** @internal */
      get client() {
        return this.cursorClient;
      }
      /** @internal */
      get server() {
        return this.selectedServer;
      }
      get namespace() {
        return this.cursorNamespace;
      }
      get readPreference() {
        return this.cursorOptions.readPreference;
      }
      get readConcern() {
        return this.cursorOptions.readConcern;
      }
      /** @internal */
      get session() {
        return this.cursorSession;
      }
      set session(clientSession) {
        this.cursorSession = clientSession;
      }
      /**
       * The cursor is closed and all remaining locally buffered documents have been iterated.
       */
      get closed() {
        return this.isClosed && (this.documents?.length ?? 0) === 0;
      }
      /**
       * A `killCursors` command was attempted on this cursor.
       * This is performed if the cursor id is non zero.
       */
      get killed() {
        return this.isKilled;
      }
      get loadBalanced() {
        return !!this.cursorClient.topology?.loadBalanced;
      }
      /**
       * An alias for {@link AbstractCursor.close|AbstractCursor.close()}.
       */
      async [Symbol.asyncDispose]() {
        await this.close();
      }
      /** Adds cursor to client's tracking so it will be closed by MongoClient.close() */
      trackCursor() {
        this.cursorClient.s.activeCursors.add(this);
        if (!this.listeners("close").includes(removeActiveCursor)) {
          this.once("close", removeActiveCursor);
        }
      }
      /** Returns current buffered documents length */
      bufferedCount() {
        return this.documents?.length ?? 0;
      }
      /** Returns current buffered documents */
      readBufferedDocuments(number4) {
        const bufferedDocs = [];
        const documentsToRead = Math.min(number4 ?? this.documents?.length ?? 0, this.documents?.length ?? 0);
        for (let count = 0; count < documentsToRead; count++) {
          const document2 = this.documents?.shift(this.deserializationOptions);
          if (document2 != null) {
            bufferedDocs.push(document2);
          }
        }
        return bufferedDocs;
      }
      async *[Symbol.asyncIterator]() {
        this.signal?.throwIfAborted();
        if (this.closed) {
          return;
        }
        try {
          while (true) {
            if (this.isKilled) {
              return;
            }
            if (this.closed) {
              return;
            }
            if (this.cursorId != null && this.isDead && (this.documents?.length ?? 0) === 0) {
              return;
            }
            const document2 = await this.next();
            if (document2 === null) {
              return;
            }
            yield document2;
            this.signal?.throwIfAborted();
          }
        } finally {
          if (!this.isClosed) {
            try {
              await this.close();
            } catch (error51) {
              (0, utils_1.squashError)(error51);
            }
          }
        }
      }
      stream() {
        const readable = new ReadableCursorStream(this);
        const abortListener = (0, utils_1.addAbortListener)(this.signal, function() {
          readable.destroy(this.reason);
        });
        readable.once("end", () => {
          abortListener?.[utils_1.kDispose]();
        });
        return readable;
      }
      async hasNext() {
        this.signal?.throwIfAborted();
        if (this.cursorId === bson_1.Long.ZERO) {
          return false;
        }
        if (this.cursorOptions.timeoutMode === exports2.CursorTimeoutMode.ITERATION && this.cursorId != null) {
          this.timeoutContext?.refresh();
        }
        try {
          do {
            if ((this.documents?.length ?? 0) !== 0) {
              return true;
            }
            await this.fetchBatch();
          } while (!this.isDead || (this.documents?.length ?? 0) !== 0);
        } finally {
          if (this.cursorOptions.timeoutMode === exports2.CursorTimeoutMode.ITERATION) {
            this.timeoutContext?.clear();
          }
        }
        return false;
      }
      /** Get the next available document from the cursor, returns null if no more documents are available. */
      async next() {
        this.signal?.throwIfAborted();
        if (this.cursorId === bson_1.Long.ZERO) {
          throw new error_1.MongoCursorExhaustedError();
        }
        if (this.cursorOptions.timeoutMode === exports2.CursorTimeoutMode.ITERATION && this.cursorId != null) {
          this.timeoutContext?.refresh();
        }
        try {
          do {
            const doc = this.documents?.shift(this.deserializationOptions);
            if (doc != null) {
              if (this.transform != null)
                return await this.transformDocument(doc);
              return doc;
            }
            await this.fetchBatch();
          } while (!this.isDead || (this.documents?.length ?? 0) !== 0);
        } finally {
          if (this.cursorOptions.timeoutMode === exports2.CursorTimeoutMode.ITERATION) {
            this.timeoutContext?.clear();
          }
        }
        return null;
      }
      /**
       * Try to get the next available document from the cursor or `null` if an empty batch is returned
       */
      async tryNext() {
        this.signal?.throwIfAborted();
        if (this.cursorId === bson_1.Long.ZERO) {
          throw new error_1.MongoCursorExhaustedError();
        }
        if (this.cursorOptions.timeoutMode === exports2.CursorTimeoutMode.ITERATION && this.cursorId != null) {
          this.timeoutContext?.refresh();
        }
        try {
          let doc = this.documents?.shift(this.deserializationOptions);
          if (doc != null) {
            if (this.transform != null)
              return await this.transformDocument(doc);
            return doc;
          }
          await this.fetchBatch();
          doc = this.documents?.shift(this.deserializationOptions);
          if (doc != null) {
            if (this.transform != null)
              return await this.transformDocument(doc);
            return doc;
          }
        } finally {
          if (this.cursorOptions.timeoutMode === exports2.CursorTimeoutMode.ITERATION) {
            this.timeoutContext?.clear();
          }
        }
        return null;
      }
      /**
       * Iterates over all the documents for this cursor using the iterator, callback pattern.
       *
       * If the iterator returns `false`, iteration will stop.
       *
       * @param iterator - The iteration callback.
       * @deprecated - Will be removed in a future release. Use for await...of instead.
       */
      async forEach(iterator) {
        this.signal?.throwIfAborted();
        if (typeof iterator !== "function") {
          throw new error_1.MongoInvalidArgumentError('Argument "iterator" must be a function');
        }
        for await (const document2 of this) {
          const result = iterator(document2);
          if (result === false) {
            break;
          }
        }
      }
      /**
       * Frees any client-side resources used by the cursor.
       */
      async close(options) {
        await this.cleanup(options?.timeoutMS);
      }
      /**
       * Returns an array of documents. The caller is responsible for making sure that there
       * is enough memory to store the results. Note that the array only contains partial
       * results when this cursor had been previously accessed. In that case,
       * cursor.rewind() can be used to reset the cursor.
       */
      async toArray() {
        this.signal?.throwIfAborted();
        const array2 = [];
        for await (const document2 of this) {
          array2.push(document2);
          const docs = this.readBufferedDocuments();
          if (this.transform != null) {
            for (const doc of docs) {
              array2.push(await this.transformDocument(doc));
            }
          } else {
            for (const doc of docs) {
              array2.push(doc);
            }
          }
        }
        return array2;
      }
      /**
       * Add a cursor flag to the cursor
       *
       * @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -.
       * @param value - The flag boolean value.
       */
      addCursorFlag(flag, value) {
        this.throwIfInitialized();
        if (!exports2.CURSOR_FLAGS.includes(flag)) {
          throw new error_1.MongoInvalidArgumentError(`Flag ${flag} is not one of ${exports2.CURSOR_FLAGS}`);
        }
        if (typeof value !== "boolean") {
          throw new error_1.MongoInvalidArgumentError(`Flag ${flag} must be a boolean value`);
        }
        this.cursorOptions[flag] = value;
        return this;
      }
      /**
       * Map all documents using the provided function
       * If there is a transform set on the cursor, that will be called first and the result passed to
       * this function's transform.
       *
       * @remarks
       *
       * **Note** Cursors use `null` internally to indicate that there are no more documents in the cursor. Providing a mapping
       * function that maps values to `null` will result in the cursor closing itself before it has finished iterating
       * all documents.  This will **not** result in a memory leak, just surprising behavior.  For example:
       *
       * ```typescript
       * const cursor = collection.find({});
       * cursor.map(() => null);
       *
       * const documents = await cursor.toArray();
       * // documents is always [], regardless of how many documents are in the collection.
       * ```
       *
       * Other falsey values are allowed:
       *
       * ```typescript
       * const cursor = collection.find({});
       * cursor.map(() => '');
       *
       * const documents = await cursor.toArray();
       * // documents is now an array of empty strings
       * ```
       *
       * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,
       * it **does not** return a new instance of a cursor. This means when calling map,
       * you should always assign the result to a new variable in order to get a correctly typed cursor variable.
       * Take note of the following example:
       *
       * @example
       * ```typescript
       * const cursor: FindCursor<Document> = coll.find();
       * const mappedCursor: FindCursor<number> = cursor.map(doc => Object.keys(doc).length);
       * const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[]
       * ```
       * @param transform - The mapping transformation method.
       */
      map(transform2) {
        this.throwIfInitialized();
        const oldTransform = this.transform;
        if (oldTransform) {
          this.transform = (doc) => {
            return transform2(oldTransform(doc));
          };
        } else {
          this.transform = transform2;
        }
        return this;
      }
      /**
       * Set the ReadPreference for the cursor.
       *
       * @param readPreference - The new read preference for the cursor.
       */
      withReadPreference(readPreference) {
        this.throwIfInitialized();
        if (readPreference instanceof read_preference_1.ReadPreference) {
          this.cursorOptions.readPreference = readPreference;
        } else if (typeof readPreference === "string") {
          this.cursorOptions.readPreference = read_preference_1.ReadPreference.fromString(readPreference);
        } else {
          throw new error_1.MongoInvalidArgumentError(`Invalid read preference: ${readPreference}`);
        }
        return this;
      }
      /**
       * Set the ReadPreference for the cursor.
       *
       * @param readPreference - The new read preference for the cursor.
       */
      withReadConcern(readConcern) {
        this.throwIfInitialized();
        const resolvedReadConcern = read_concern_1.ReadConcern.fromOptions({ readConcern });
        if (resolvedReadConcern) {
          this.cursorOptions.readConcern = resolvedReadConcern;
        }
        return this;
      }
      /**
       * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)
       *
       * @param value - Number of milliseconds to wait before aborting the query.
       */
      maxTimeMS(value) {
        this.throwIfInitialized();
        if (typeof value !== "number") {
          throw new error_1.MongoInvalidArgumentError("Argument for maxTimeMS must be a number");
        }
        this.cursorOptions.maxTimeMS = value;
        return this;
      }
      /**
       * Set the batch size for the cursor.
       *
       * @param value - The number of documents to return per batch. See {@link https://www.mongodb.com/docs/manual/reference/command/find/|find command documentation}.
       */
      batchSize(value) {
        this.throwIfInitialized();
        if (this.cursorOptions.tailable) {
          throw new error_1.MongoTailableCursorError("Tailable cursor does not support batchSize");
        }
        if (typeof value !== "number") {
          throw new error_1.MongoInvalidArgumentError('Operation "batchSize" requires an integer');
        }
        this.cursorOptions.batchSize = value;
        return this;
      }
      /**
       * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will
       * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even
       * if the resultant data has already been retrieved by this cursor.
       */
      rewind() {
        if (this.timeoutContext && this.timeoutContext.owner !== this) {
          throw new error_1.MongoAPIError(`Cannot rewind cursor that does not own its timeout context.`);
        }
        if (!this.initialized) {
          return;
        }
        this.cursorId = null;
        this.documents?.clear();
        this.timeoutContext?.clear();
        this.timeoutContext = void 0;
        this.isClosed = false;
        this.isKilled = false;
        this.initialized = false;
        this.hasEmittedClose = false;
        this.trackCursor();
        if (this.cursorSession?.explicit === false) {
          if (!this.cursorSession.hasEnded) {
            this.cursorSession.endSession().then(void 0, utils_1.squashError);
          }
          this.cursorSession = null;
        }
      }
      /** @internal */
      async getMore() {
        if (this.cursorId == null) {
          throw new error_1.MongoRuntimeError("Unexpected null cursor id. A cursor creating command should have set this");
        }
        if (this.selectedServer == null) {
          throw new error_1.MongoRuntimeError("Unexpected null selectedServer. A cursor creating command should have set this");
        }
        if (this.cursorSession == null) {
          throw new error_1.MongoRuntimeError("Unexpected null session. A cursor creating command should have set this");
        }
        const getMoreOptions = {
          ...this.cursorOptions,
          session: this.cursorSession,
          batchSize: this.cursorOptions.batchSize
        };
        const getMoreOperation = new get_more_1.GetMoreOperation(this.cursorNamespace, this.cursorId, this.selectedServer, getMoreOptions);
        return await (0, execute_operation_1.executeOperation)(this.cursorClient, getMoreOperation, this.timeoutContext);
      }
      /**
       * @internal
       *
       * This function is exposed for the unified test runner's createChangeStream
       * operation.  We cannot refactor to use the abstract _initialize method without
       * a significant refactor.
       */
      async cursorInit() {
        if (this.cursorOptions.timeoutMS != null) {
          this.timeoutContext ??= new CursorTimeoutContext(timeout_1.TimeoutContext.create({
            serverSelectionTimeoutMS: this.client.s.options.serverSelectionTimeoutMS,
            timeoutMS: this.cursorOptions.timeoutMS
          }), this);
        }
        try {
          this.cursorSession ??= this.cursorClient.startSession({ owner: this, explicit: false });
          const state = await this._initialize(this.cursorSession);
          this.cursorOptions.omitMaxTimeMS = this.cursorOptions.timeoutMS != null;
          const response = state.response;
          this.selectedServer = state.server;
          this.cursorId = response.id;
          this.cursorNamespace = response.ns ?? this.namespace;
          this.documents = response;
          this.initialized = true;
        } catch (error51) {
          this.initialized = true;
          await this.cleanup(void 0, error51);
          throw error51;
        }
        if (this.isDead) {
          await this.cleanup();
        }
        return;
      }
      /** @internal Attempt to obtain more documents */
      async fetchBatch() {
        if (this.isClosed) {
          return;
        }
        if (this.isDead) {
          await this.cleanup();
          return;
        }
        if (this.cursorId == null) {
          await this.cursorInit();
          if ((this.documents?.length ?? 0) !== 0 || this.isDead)
            return;
        }
        try {
          const response = await this.getMore();
          this.cursorId = response.id;
          this.documents = response;
        } catch (error51) {
          try {
            await this.cleanup(void 0, error51);
          } catch (cleanupError) {
            (0, utils_1.squashError)(cleanupError);
          }
          throw error51;
        }
        if (this.isDead) {
          await this.cleanup();
        }
      }
      /** @internal */
      async cleanup(timeoutMS, error51) {
        this.abortListener?.[utils_1.kDispose]();
        this.isClosed = true;
        const timeoutContextForKillCursors = () => {
          if (timeoutMS != null) {
            this.timeoutContext?.clear();
            return new CursorTimeoutContext(timeout_1.TimeoutContext.create({
              serverSelectionTimeoutMS: this.client.s.options.serverSelectionTimeoutMS,
              timeoutMS
            }), this);
          } else {
            return this.timeoutContext?.refreshed();
          }
        };
        const withEmitClose = async (fn) => {
          try {
            await fn();
          } finally {
            this.emitClose();
          }
        };
        const close = async () => {
          const session = this.cursorSession;
          if (!session)
            return;
          try {
            if (!this.isKilled && this.cursorId && !this.cursorId.isZero() && this.cursorNamespace && this.selectedServer && !session.hasEnded) {
              this.isKilled = true;
              const cursorId = this.cursorId;
              this.cursorId = bson_1.Long.ZERO;
              await (0, execute_operation_1.executeOperation)(this.cursorClient, new kill_cursors_1.KillCursorsOperation(cursorId, this.cursorNamespace, this.selectedServer, {
                session
              }), timeoutContextForKillCursors());
            }
          } catch (error52) {
            (0, utils_1.squashError)(error52);
          } finally {
            if (session.owner === this) {
              await session.endSession({ error: error51 });
            }
            if (!session.inTransaction()) {
              (0, sessions_1.maybeClearPinnedConnection)(session, { error: error51 });
            }
          }
        };
        await withEmitClose(close);
      }
      /** @internal */
      emitClose() {
        try {
          if (!this.hasEmittedClose && ((this.documents?.length ?? 0) === 0 || this.isClosed)) {
            this.emit("close");
          }
        } finally {
          this.hasEmittedClose = true;
        }
      }
      /** @internal */
      async transformDocument(document2) {
        if (this.transform == null)
          return document2;
        try {
          const transformedDocument = this.transform(document2);
          if (transformedDocument === null) {
            const TRANSFORM_TO_NULL_ERROR = "Cursor returned a `null` document, but the cursor is not exhausted.  Mapping documents to `null` is not supported in the cursor transform.";
            throw new error_1.MongoAPIError(TRANSFORM_TO_NULL_ERROR);
          }
          return transformedDocument;
        } catch (transformError) {
          try {
            await this.close();
          } catch (closeError) {
            (0, utils_1.squashError)(closeError);
          }
          throw transformError;
        }
      }
      /** @internal */
      throwIfInitialized() {
        if (this.initialized)
          throw new error_1.MongoCursorInUseError();
      }
    };
    exports2.AbstractCursor = AbstractCursor;
    var ReadableCursorStream = class extends stream_1.Readable {
      constructor(cursor) {
        super({
          objectMode: true,
          autoDestroy: false,
          highWaterMark: 1
        });
        this._readInProgress = false;
        this._cursor = cursor;
      }
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      _read(size) {
        if (!this._readInProgress) {
          this._readInProgress = true;
          this._readNext();
        }
      }
      _destroy(error51, callback) {
        this._cursor.close().then(() => callback(error51), (closeError) => callback(closeError));
      }
      _readNext() {
        if (this._cursor.id === bson_1.Long.ZERO) {
          this.push(null);
          return;
        }
        this._cursor.next().then(
          // result from next()
          (result) => {
            if (result == null) {
              this.push(null);
            } else if (this.destroyed) {
              this._cursor.close().then(void 0, utils_1.squashError);
            } else {
              if (this.push(result)) {
                return this._readNext();
              }
              this._readInProgress = false;
            }
          },
          // error from next()
          (err) => {
            if (err.message.match(/server is closed/)) {
              this._cursor.close().then(void 0, utils_1.squashError);
              return this.push(null);
            }
            if (err.message.match(/operation was interrupted/)) {
              return this.push(null);
            }
            return this.destroy(err);
          }
        ).catch((error51) => {
          this._readInProgress = false;
          this.destroy(error51);
        });
      }
    };
    var CursorTimeoutContext = class _CursorTimeoutContext extends timeout_1.TimeoutContext {
      constructor(timeoutContext, owner) {
        super();
        this.timeoutContext = timeoutContext;
        this.owner = owner;
      }
      get serverSelectionTimeout() {
        return this.timeoutContext.serverSelectionTimeout;
      }
      get connectionCheckoutTimeout() {
        return this.timeoutContext.connectionCheckoutTimeout;
      }
      get clearServerSelectionTimeout() {
        return this.timeoutContext.clearServerSelectionTimeout;
      }
      get timeoutForSocketWrite() {
        return this.timeoutContext.timeoutForSocketWrite;
      }
      get timeoutForSocketRead() {
        return this.timeoutContext.timeoutForSocketRead;
      }
      csotEnabled() {
        return this.timeoutContext.csotEnabled();
      }
      refresh() {
        if (typeof this.owner !== "symbol")
          return this.timeoutContext.refresh();
      }
      clear() {
        if (typeof this.owner !== "symbol")
          return this.timeoutContext.clear();
      }
      get maxTimeMS() {
        return this.timeoutContext.maxTimeMS;
      }
      get timeoutMS() {
        return this.timeoutContext.csotEnabled() ? this.timeoutContext.timeoutMS : null;
      }
      refreshed() {
        return new _CursorTimeoutContext(this.timeoutContext.refreshed(), this.owner);
      }
      addMaxTimeMSToCommand(command, options) {
        this.timeoutContext.addMaxTimeMSToCommand(command, options);
      }
      getSocketTimeoutMS() {
        return this.timeoutContext.getSocketTimeoutMS();
      }
    };
    exports2.CursorTimeoutContext = CursorTimeoutContext;
  }
});

// node_modules/mongodb/lib/cursor/explainable_cursor.js
var require_explainable_cursor = __commonJS({
  "node_modules/mongodb/lib/cursor/explainable_cursor.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ExplainableCursor = void 0;
    var abstract_cursor_1 = require_abstract_cursor();
    var ExplainableCursor = class extends abstract_cursor_1.AbstractCursor {
      resolveExplainTimeoutOptions(verbosity, options) {
        let explain;
        let timeout;
        if (verbosity == null && options == null) {
          explain = void 0;
          timeout = void 0;
        } else if (verbosity != null && options == null) {
          explain = typeof verbosity !== "object" ? verbosity : "verbosity" in verbosity ? verbosity : void 0;
          timeout = typeof verbosity === "object" && "timeoutMS" in verbosity ? verbosity : void 0;
        } else {
          explain = verbosity;
          timeout = options;
        }
        return { timeout, explain };
      }
    };
    exports2.ExplainableCursor = ExplainableCursor;
  }
});

// node_modules/mongodb/lib/cursor/aggregation_cursor.js
var require_aggregation_cursor = __commonJS({
  "node_modules/mongodb/lib/cursor/aggregation_cursor.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AggregationCursor = void 0;
    var error_1 = require_error();
    var explain_1 = require_explain();
    var aggregate_1 = require_aggregate();
    var execute_operation_1 = require_execute_operation();
    var utils_1 = require_utils();
    var abstract_cursor_1 = require_abstract_cursor();
    var explainable_cursor_1 = require_explainable_cursor();
    var AggregationCursor = class _AggregationCursor extends explainable_cursor_1.ExplainableCursor {
      /** @internal */
      constructor(client, namespace, pipeline2 = [], options = {}) {
        super(client, namespace, options);
        this.pipeline = pipeline2;
        this.aggregateOptions = options;
        const lastStage = this.pipeline[this.pipeline.length - 1];
        if (this.cursorOptions.timeoutMS != null && this.cursorOptions.timeoutMode === abstract_cursor_1.CursorTimeoutMode.ITERATION && (lastStage?.$merge != null || lastStage?.$out != null))
          throw new error_1.MongoAPIError("Cannot use $out or $merge stage with ITERATION timeoutMode");
      }
      clone() {
        const clonedOptions = (0, utils_1.mergeOptions)({}, this.aggregateOptions);
        delete clonedOptions.session;
        return new _AggregationCursor(this.client, this.namespace, this.pipeline, {
          ...clonedOptions
        });
      }
      map(transform2) {
        return super.map(transform2);
      }
      /** @internal */
      async _initialize(session) {
        const options = {
          ...this.aggregateOptions,
          ...this.cursorOptions,
          session,
          signal: this.signal
        };
        if (options.explain) {
          try {
            (0, explain_1.validateExplainTimeoutOptions)(options, explain_1.Explain.fromOptions(options));
          } catch {
            throw new error_1.MongoAPIError("timeoutMS cannot be used with explain when explain is specified in aggregateOptions");
          }
        }
        const aggregateOperation = new aggregate_1.AggregateOperation(this.namespace, this.pipeline, options);
        const response = await (0, execute_operation_1.executeOperation)(this.client, aggregateOperation, this.timeoutContext);
        return { server: aggregateOperation.server, session, response };
      }
      async explain(verbosity, options) {
        const { explain, timeout } = this.resolveExplainTimeoutOptions(verbosity, options);
        return (await (0, execute_operation_1.executeOperation)(this.client, new aggregate_1.AggregateOperation(this.namespace, this.pipeline, {
          ...this.aggregateOptions,
          // NOTE: order matters here, we may need to refine this
          ...this.cursorOptions,
          ...timeout,
          explain: explain ?? true
        }))).shift(this.deserializationOptions);
      }
      addStage(stage) {
        this.throwIfInitialized();
        if (this.cursorOptions.timeoutMS != null && this.cursorOptions.timeoutMode === abstract_cursor_1.CursorTimeoutMode.ITERATION && (stage.$out != null || stage.$merge != null)) {
          throw new error_1.MongoAPIError("Cannot use $out or $merge stage with ITERATION timeoutMode");
        }
        this.pipeline.push(stage);
        return this;
      }
      group($group) {
        return this.addStage({ $group });
      }
      /** Add a limit stage to the aggregation pipeline */
      limit($limit) {
        return this.addStage({ $limit });
      }
      /** Add a match stage to the aggregation pipeline */
      match($match) {
        return this.addStage({ $match });
      }
      /** Add an out stage to the aggregation pipeline */
      out($out) {
        return this.addStage({ $out });
      }
      /**
       * Add a project stage to the aggregation pipeline
       *
       * @remarks
       * In order to strictly type this function you must provide an interface
       * that represents the effect of your projection on the result documents.
       *
       * By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type.
       * You should specify a parameterized type to have assertions on your final results.
       *
       * @example
       * ```typescript
       * // Best way
       * const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true });
       * // Flexible way
       * const docs: AggregationCursor<Document> = cursor.project({ _id: 0, a: true });
       * ```
       *
       * @remarks
       * In order to strictly type this function you must provide an interface
       * that represents the effect of your projection on the result documents.
       *
       * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,
       * it **does not** return a new instance of a cursor. This means when calling project,
       * you should always assign the result to a new variable in order to get a correctly typed cursor variable.
       * Take note of the following example:
       *
       * @example
       * ```typescript
       * const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]);
       * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true });
       * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray();
       *
       * // or always use chaining and save the final cursor
       *
       * const cursor = coll.aggregate().project<{ a: string }>({
       *   _id: 0,
       *   a: { $convert: { input: '$a', to: 'string' }
       * }});
       * ```
       */
      project($project) {
        return this.addStage({ $project });
      }
      /** Add a lookup stage to the aggregation pipeline */
      lookup($lookup) {
        return this.addStage({ $lookup });
      }
      /** Add a redact stage to the aggregation pipeline */
      redact($redact) {
        return this.addStage({ $redact });
      }
      /** Add a skip stage to the aggregation pipeline */
      skip($skip) {
        return this.addStage({ $skip });
      }
      /** Add a sort stage to the aggregation pipeline */
      sort($sort) {
        return this.addStage({ $sort });
      }
      /** Add a unwind stage to the aggregation pipeline */
      unwind($unwind) {
        return this.addStage({ $unwind });
      }
      /** Add a geoNear stage to the aggregation pipeline */
      geoNear($geoNear) {
        return this.addStage({ $geoNear });
      }
    };
    exports2.AggregationCursor = AggregationCursor;
  }
});

// node_modules/mongodb/lib/operations/count.js
var require_count = __commonJS({
  "node_modules/mongodb/lib/operations/count.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CountOperation = void 0;
    var responses_1 = require_responses();
    var command_1 = require_command();
    var operation_1 = require_operation();
    var CountOperation = class extends command_1.CommandOperation {
      constructor(namespace, filter, options) {
        super({ s: { namespace } }, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.options = options;
        this.collectionName = namespace.collection;
        this.query = filter;
      }
      get commandName() {
        return "count";
      }
      buildCommandDocument(_connection, _session) {
        const options = this.options;
        const cmd = {
          count: this.collectionName,
          query: this.query
        };
        if (typeof options.limit === "number") {
          cmd.limit = options.limit;
        }
        if (typeof options.skip === "number") {
          cmd.skip = options.skip;
        }
        if (options.hint != null) {
          cmd.hint = options.hint;
        }
        if (typeof options.maxTimeMS === "number") {
          cmd.maxTimeMS = options.maxTimeMS;
        }
        return cmd;
      }
      handleOk(response) {
        return response.getNumber("n") ?? 0;
      }
    };
    exports2.CountOperation = CountOperation;
    (0, operation_1.defineAspects)(CountOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE, operation_1.Aspect.SUPPORTS_RAW_DATA]);
  }
});

// node_modules/mongodb/lib/operations/find.js
var require_find = __commonJS({
  "node_modules/mongodb/lib/operations/find.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.FindOperation = void 0;
    var responses_1 = require_responses();
    var error_1 = require_error();
    var sort_1 = require_sort();
    var utils_1 = require_utils();
    var command_1 = require_command();
    var operation_1 = require_operation();
    var FindOperation = class extends command_1.CommandOperation {
      constructor(ns, filter = {}, options = {}) {
        super(void 0, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.CursorResponse;
        this.options = { ...options };
        delete this.options.writeConcern;
        this.ns = ns;
        if (typeof filter !== "object" || Array.isArray(filter)) {
          throw new error_1.MongoInvalidArgumentError("Query filter must be a plain object or ObjectId");
        }
        this.filter = filter != null && filter._bsontype === "ObjectId" ? { _id: filter } : filter;
        this.SERVER_COMMAND_RESPONSE_TYPE = this.explain ? responses_1.ExplainedCursorResponse : responses_1.CursorResponse;
      }
      get commandName() {
        return "find";
      }
      buildOptions(timeoutContext) {
        return {
          ...this.options,
          ...this.bsonOptions,
          documentsReturnedIn: "firstBatch",
          session: this.session,
          timeoutContext
        };
      }
      handleOk(response) {
        return response;
      }
      buildCommandDocument() {
        return makeFindCommand(this.ns, this.filter, this.options);
      }
    };
    exports2.FindOperation = FindOperation;
    function makeFindCommand(ns, filter, options) {
      const findCommand = {
        find: ns.collection,
        filter
      };
      if (options.sort) {
        findCommand.sort = (0, sort_1.formatSort)(options.sort);
      }
      if (options.projection) {
        let projection = options.projection;
        if (projection && Array.isArray(projection)) {
          projection = projection.length ? projection.reduce((result, field) => {
            result[field] = 1;
            return result;
          }, {}) : { _id: 1 };
        }
        findCommand.projection = projection;
      }
      if (options.hint) {
        findCommand.hint = (0, utils_1.normalizeHintField)(options.hint);
      }
      if (typeof options.skip === "number") {
        findCommand.skip = options.skip;
      }
      if (typeof options.limit === "number") {
        if (options.limit < 0) {
          findCommand.limit = -options.limit;
          findCommand.singleBatch = true;
        } else {
          findCommand.limit = options.limit;
        }
      }
      if (typeof options.batchSize === "number") {
        if (options.batchSize < 0) {
          findCommand.limit = -options.batchSize;
        } else {
          if (options.batchSize === options.limit) {
            findCommand.batchSize = options.batchSize + 1;
          } else {
            findCommand.batchSize = options.batchSize;
          }
        }
      }
      if (typeof options.singleBatch === "boolean") {
        findCommand.singleBatch = options.singleBatch;
      }
      if (options.comment !== void 0) {
        findCommand.comment = options.comment;
      }
      if (options.max) {
        findCommand.max = options.max;
      }
      if (options.min) {
        findCommand.min = options.min;
      }
      if (typeof options.returnKey === "boolean") {
        findCommand.returnKey = options.returnKey;
      }
      if (typeof options.showRecordId === "boolean") {
        findCommand.showRecordId = options.showRecordId;
      }
      if (typeof options.tailable === "boolean") {
        findCommand.tailable = options.tailable;
      }
      if (typeof options.oplogReplay === "boolean") {
        findCommand.oplogReplay = options.oplogReplay;
      }
      if (typeof options.timeout === "boolean") {
        findCommand.noCursorTimeout = !options.timeout;
      } else if (typeof options.noCursorTimeout === "boolean") {
        findCommand.noCursorTimeout = options.noCursorTimeout;
      }
      if (typeof options.awaitData === "boolean") {
        findCommand.awaitData = options.awaitData;
      }
      if (typeof options.allowPartialResults === "boolean") {
        findCommand.allowPartialResults = options.allowPartialResults;
      }
      if (typeof options.allowDiskUse === "boolean") {
        findCommand.allowDiskUse = options.allowDiskUse;
      }
      if (options.let) {
        findCommand.let = options.let;
      }
      return findCommand;
    }
    (0, operation_1.defineAspects)(FindOperation, [
      operation_1.Aspect.READ_OPERATION,
      operation_1.Aspect.RETRYABLE,
      operation_1.Aspect.EXPLAINABLE,
      operation_1.Aspect.CURSOR_CREATING,
      operation_1.Aspect.SUPPORTS_RAW_DATA
    ]);
  }
});

// node_modules/mongodb/lib/cursor/find_cursor.js
var require_find_cursor = __commonJS({
  "node_modules/mongodb/lib/cursor/find_cursor.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.FindCursor = exports2.FLAGS = void 0;
    var responses_1 = require_responses();
    var error_1 = require_error();
    var explain_1 = require_explain();
    var count_1 = require_count();
    var execute_operation_1 = require_execute_operation();
    var find_1 = require_find();
    var sort_1 = require_sort();
    var utils_1 = require_utils();
    var explainable_cursor_1 = require_explainable_cursor();
    exports2.FLAGS = [
      "tailable",
      "oplogReplay",
      "noCursorTimeout",
      "awaitData",
      "exhaust",
      "partial"
    ];
    var FindCursor = class _FindCursor extends explainable_cursor_1.ExplainableCursor {
      /** @internal */
      constructor(client, namespace, filter = {}, options = {}) {
        super(client, namespace, options);
        this.numReturned = 0;
        this.cursorFilter = filter;
        this.findOptions = options;
        if (options.sort != null) {
          this.findOptions.sort = (0, sort_1.formatSort)(options.sort);
        }
      }
      clone() {
        const clonedOptions = (0, utils_1.mergeOptions)({}, this.findOptions);
        delete clonedOptions.session;
        return new _FindCursor(this.client, this.namespace, this.cursorFilter, {
          ...clonedOptions
        });
      }
      map(transform2) {
        return super.map(transform2);
      }
      /** @internal */
      async _initialize(session) {
        const options = {
          ...this.findOptions,
          // NOTE: order matters here, we may need to refine this
          ...this.cursorOptions,
          session,
          signal: this.signal
        };
        if (options.explain) {
          try {
            (0, explain_1.validateExplainTimeoutOptions)(options, explain_1.Explain.fromOptions(options));
          } catch {
            throw new error_1.MongoAPIError("timeoutMS cannot be used with explain when explain is specified in findOptions");
          }
        }
        const findOperation = new find_1.FindOperation(this.namespace, this.cursorFilter, options);
        const response = await (0, execute_operation_1.executeOperation)(this.client, findOperation, this.timeoutContext);
        this.numReturned = response.batchSize;
        return { server: findOperation.server, session, response };
      }
      /** @internal */
      async getMore() {
        const numReturned = this.numReturned;
        const limit = this.findOptions.limit ?? Infinity;
        const remaining = limit - numReturned;
        if (numReturned === limit && !this.id?.isZero()) {
          try {
            await this.close();
          } catch (error51) {
            (0, utils_1.squashError)(error51);
          }
          return responses_1.CursorResponse.emptyGetMore;
        }
        let cleanup = utils_1.noop;
        const { batchSize } = this.cursorOptions;
        if (batchSize != null && batchSize > remaining) {
          this.cursorOptions.batchSize = remaining;
          cleanup = () => {
            this.cursorOptions.batchSize = batchSize;
          };
        }
        try {
          const response = await super.getMore();
          this.numReturned = this.numReturned + response.batchSize;
          return response;
        } finally {
          cleanup?.();
        }
      }
      /**
       * Get the count of documents for this cursor
       * @deprecated Use `collection.estimatedDocumentCount` or `collection.countDocuments` instead
       */
      async count(options) {
        (0, utils_1.emitWarningOnce)("cursor.count is deprecated and will be removed in the next major version, please use `collection.estimatedDocumentCount` or `collection.countDocuments` instead ");
        if (typeof options === "boolean") {
          throw new error_1.MongoInvalidArgumentError("Invalid first parameter to count");
        }
        return await (0, execute_operation_1.executeOperation)(this.client, new count_1.CountOperation(this.namespace, this.cursorFilter, {
          ...this.findOptions,
          // NOTE: order matters here, we may need to refine this
          ...this.cursorOptions,
          ...options
        }));
      }
      async explain(verbosity, options) {
        const { explain, timeout } = this.resolveExplainTimeoutOptions(verbosity, options);
        return (await (0, execute_operation_1.executeOperation)(this.client, new find_1.FindOperation(this.namespace, this.cursorFilter, {
          ...this.findOptions,
          // NOTE: order matters here, we may need to refine this
          ...this.cursorOptions,
          ...timeout,
          explain: explain ?? true
        }))).shift(this.deserializationOptions);
      }
      /** Set the cursor query */
      filter(filter) {
        this.throwIfInitialized();
        this.cursorFilter = filter;
        return this;
      }
      /**
       * Set the cursor hint
       *
       * @param hint - If specified, then the query system will only consider plans using the hinted index.
       */
      hint(hint) {
        this.throwIfInitialized();
        this.findOptions.hint = hint;
        return this;
      }
      /**
       * Set the cursor min
       *
       * @param min - Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order.
       */
      min(min) {
        this.throwIfInitialized();
        this.findOptions.min = min;
        return this;
      }
      /**
       * Set the cursor max
       *
       * @param max - Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order.
       */
      max(max) {
        this.throwIfInitialized();
        this.findOptions.max = max;
        return this;
      }
      /**
       * Set the cursor returnKey.
       * If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents.
       * If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields.
       *
       * @param value - the returnKey value.
       */
      returnKey(value) {
        this.throwIfInitialized();
        this.findOptions.returnKey = value;
        return this;
      }
      /**
       * Modifies the output of a query by adding a field $recordId to matching documents. $recordId is the internal key which uniquely identifies a document in a collection.
       *
       * @param value - The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find.
       */
      showRecordId(value) {
        this.throwIfInitialized();
        this.findOptions.showRecordId = value;
        return this;
      }
      /**
       * Add a query modifier to the cursor query
       *
       * @param name - The query modifier (must start with $, such as $orderby etc)
       * @param value - The modifier value.
       */
      addQueryModifier(name, value) {
        this.throwIfInitialized();
        if (name[0] !== "$") {
          throw new error_1.MongoInvalidArgumentError(`${name} is not a valid query modifier`);
        }
        const field = name.substr(1);
        switch (field) {
          case "comment":
            this.findOptions.comment = value;
            break;
          case "explain":
            this.findOptions.explain = value;
            break;
          case "hint":
            this.findOptions.hint = value;
            break;
          case "max":
            this.findOptions.max = value;
            break;
          case "maxTimeMS":
            this.findOptions.maxTimeMS = value;
            break;
          case "min":
            this.findOptions.min = value;
            break;
          case "orderby":
            this.findOptions.sort = (0, sort_1.formatSort)(value);
            break;
          case "query":
            this.cursorFilter = value;
            break;
          case "returnKey":
            this.findOptions.returnKey = value;
            break;
          case "showDiskLoc":
            this.findOptions.showRecordId = value;
            break;
          default:
            throw new error_1.MongoInvalidArgumentError(`Invalid query modifier: ${name}`);
        }
        return this;
      }
      /**
       * Add a comment to the cursor query allowing for tracking the comment in the log.
       *
       * @param value - The comment attached to this query.
       */
      comment(value) {
        this.throwIfInitialized();
        this.findOptions.comment = value;
        return this;
      }
      /**
       * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise)
       *
       * @param value - Number of milliseconds to wait before aborting the tailed query.
       */
      maxAwaitTimeMS(value) {
        this.throwIfInitialized();
        if (typeof value !== "number") {
          throw new error_1.MongoInvalidArgumentError("Argument for maxAwaitTimeMS must be a number");
        }
        this.findOptions.maxAwaitTimeMS = value;
        return this;
      }
      /**
       * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)
       *
       * @param value - Number of milliseconds to wait before aborting the query.
       */
      maxTimeMS(value) {
        this.throwIfInitialized();
        if (typeof value !== "number") {
          throw new error_1.MongoInvalidArgumentError("Argument for maxTimeMS must be a number");
        }
        this.findOptions.maxTimeMS = value;
        return this;
      }
      /**
       * Add a project stage to the aggregation pipeline
       *
       * @remarks
       * In order to strictly type this function you must provide an interface
       * that represents the effect of your projection on the result documents.
       *
       * By default chaining a projection to your cursor changes the returned type to the generic
       * {@link Document} type.
       * You should specify a parameterized type to have assertions on your final results.
       *
       * @example
       * ```typescript
       * // Best way
       * const docs: FindCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true });
       * // Flexible way
       * const docs: FindCursor<Document> = cursor.project({ _id: 0, a: true });
       * ```
       *
       * @remarks
       *
       * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,
       * it **does not** return a new instance of a cursor. This means when calling project,
       * you should always assign the result to a new variable in order to get a correctly typed cursor variable.
       * Take note of the following example:
       *
       * @example
       * ```typescript
       * const cursor: FindCursor<{ a: number; b: string }> = coll.find();
       * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true });
       * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray();
       *
       * // or always use chaining and save the final cursor
       *
       * const cursor = coll.find().project<{ a: string }>({
       *   _id: 0,
       *   a: { $convert: { input: '$a', to: 'string' }
       * }});
       * ```
       */
      project(value) {
        this.throwIfInitialized();
        this.findOptions.projection = value;
        return this;
      }
      /**
       * Sets the sort order of the cursor query.
       *
       * @param sort - The key or keys set for the sort.
       * @param direction - The direction of the sorting (1 or -1).
       */
      sort(sort, direction) {
        this.throwIfInitialized();
        if (this.findOptions.tailable) {
          throw new error_1.MongoTailableCursorError("Tailable cursor does not support sorting");
        }
        this.findOptions.sort = (0, sort_1.formatSort)(sort, direction);
        return this;
      }
      /**
       * Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher)
       *
       * @remarks
       * {@link https://www.mongodb.com/docs/manual/reference/command/find/#find-cmd-allowdiskuse | find command allowDiskUse documentation}
       */
      allowDiskUse(allow = true) {
        this.throwIfInitialized();
        if (!this.findOptions.sort) {
          throw new error_1.MongoInvalidArgumentError('Option "allowDiskUse" requires a sort specification');
        }
        if (!allow) {
          this.findOptions.allowDiskUse = false;
          return this;
        }
        this.findOptions.allowDiskUse = true;
        return this;
      }
      /**
       * Set the collation options for the cursor.
       *
       * @param value - The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
       */
      collation(value) {
        this.throwIfInitialized();
        this.findOptions.collation = value;
        return this;
      }
      /**
       * Set the limit for the cursor.
       *
       * @param value - The limit for the cursor query.
       */
      limit(value) {
        this.throwIfInitialized();
        if (this.findOptions.tailable) {
          throw new error_1.MongoTailableCursorError("Tailable cursor does not support limit");
        }
        if (typeof value !== "number") {
          throw new error_1.MongoInvalidArgumentError('Operation "limit" requires an integer');
        }
        this.findOptions.limit = value;
        return this;
      }
      /**
       * Set the skip for the cursor.
       *
       * @param value - The skip for the cursor query.
       */
      skip(value) {
        this.throwIfInitialized();
        if (this.findOptions.tailable) {
          throw new error_1.MongoTailableCursorError("Tailable cursor does not support skip");
        }
        if (typeof value !== "number") {
          throw new error_1.MongoInvalidArgumentError('Operation "skip" requires an integer');
        }
        this.findOptions.skip = value;
        return this;
      }
    };
    exports2.FindCursor = FindCursor;
  }
});

// node_modules/mongodb/lib/operations/indexes.js
var require_indexes = __commonJS({
  "node_modules/mongodb/lib/operations/indexes.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ListIndexesOperation = exports2.DropIndexOperation = exports2.CreateIndexesOperation = void 0;
    var responses_1 = require_responses();
    var error_1 = require_error();
    var utils_1 = require_utils();
    var command_1 = require_command();
    var operation_1 = require_operation();
    var VALID_INDEX_OPTIONS = /* @__PURE__ */ new Set([
      "background",
      "unique",
      "name",
      "partialFilterExpression",
      "sparse",
      "hidden",
      "expireAfterSeconds",
      "storageEngine",
      "collation",
      "version",
      // text indexes
      "weights",
      "default_language",
      "language_override",
      "textIndexVersion",
      // 2d-sphere indexes
      "2dsphereIndexVersion",
      // 2d indexes
      "bits",
      "min",
      "max",
      // geoHaystack Indexes
      "bucketSize",
      // wildcard indexes
      "wildcardProjection"
    ]);
    function isIndexDirection(x2) {
      return typeof x2 === "number" || x2 === "2d" || x2 === "2dsphere" || x2 === "text" || x2 === "geoHaystack";
    }
    function isSingleIndexTuple(t2) {
      return Array.isArray(t2) && t2.length === 2 && isIndexDirection(t2[1]);
    }
    function constructIndexDescriptionMap(indexSpec) {
      const key = /* @__PURE__ */ new Map();
      const indexSpecs = !Array.isArray(indexSpec) || isSingleIndexTuple(indexSpec) ? [indexSpec] : indexSpec;
      for (const spec of indexSpecs) {
        if (typeof spec === "string") {
          key.set(spec, 1);
        } else if (Array.isArray(spec)) {
          key.set(spec[0], spec[1] ?? 1);
        } else if (spec instanceof Map) {
          for (const [property, value] of spec) {
            key.set(property, value);
          }
        } else if ((0, utils_1.isObject)(spec)) {
          for (const [property, value] of Object.entries(spec)) {
            key.set(property, value);
          }
        }
      }
      return key;
    }
    function resolveIndexDescription(description) {
      const validProvidedOptions = Object.entries(description).filter(([optionName]) => VALID_INDEX_OPTIONS.has(optionName));
      return Object.fromEntries(
        // we support the `version` option, but the `createIndexes` command expects it to be the `v`
        validProvidedOptions.map(([name, value]) => name === "version" ? ["v", value] : [name, value])
      );
    }
    var CreateIndexesOperation = class _CreateIndexesOperation extends command_1.CommandOperation {
      constructor(parent, collectionName, indexes, options) {
        super(parent, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.options = options ?? {};
        this.options.collation = void 0;
        this.collectionName = collectionName;
        this.indexes = indexes.map((userIndex) => {
          const key = userIndex.key instanceof Map ? userIndex.key : new Map(Object.entries(userIndex.key));
          const name = userIndex.name ?? Array.from(key).flat().join("_");
          const validIndexOptions = resolveIndexDescription(userIndex);
          return {
            ...validIndexOptions,
            name,
            key
          };
        });
        this.ns = parent.s.namespace;
      }
      static fromIndexDescriptionArray(parent, collectionName, indexes, options) {
        return new _CreateIndexesOperation(parent, collectionName, indexes, options);
      }
      static fromIndexSpecification(parent, collectionName, indexSpec, options = {}) {
        const key = constructIndexDescriptionMap(indexSpec);
        const description = { ...options, key };
        return new _CreateIndexesOperation(parent, collectionName, [description], options);
      }
      get commandName() {
        return "createIndexes";
      }
      buildCommandDocument(connection) {
        const options = this.options;
        const indexes = this.indexes;
        const serverWireVersion = (0, utils_1.maxWireVersion)(connection);
        const cmd = { createIndexes: this.collectionName, indexes };
        if (options.commitQuorum != null) {
          if (serverWireVersion < 9) {
            throw new error_1.MongoCompatibilityError("Option `commitQuorum` for `createIndexes` not supported on servers < 4.4");
          }
          cmd.commitQuorum = options.commitQuorum;
        }
        return cmd;
      }
      handleOk(_response) {
        const indexNames = this.indexes.map((index) => index.name || "");
        return indexNames;
      }
    };
    exports2.CreateIndexesOperation = CreateIndexesOperation;
    var DropIndexOperation = class extends command_1.CommandOperation {
      constructor(collection, indexName, options) {
        super(collection, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.options = options ?? {};
        this.collection = collection;
        this.indexName = indexName;
        this.ns = collection.fullNamespace;
      }
      get commandName() {
        return "dropIndexes";
      }
      buildCommandDocument(_connection) {
        return { dropIndexes: this.collection.collectionName, index: this.indexName };
      }
    };
    exports2.DropIndexOperation = DropIndexOperation;
    var ListIndexesOperation = class extends command_1.CommandOperation {
      constructor(collection, options) {
        super(collection, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.CursorResponse;
        this.options = { ...options };
        delete this.options.writeConcern;
        this.collectionNamespace = collection.s.namespace;
      }
      get commandName() {
        return "listIndexes";
      }
      buildCommandDocument(connection) {
        const serverWireVersion = (0, utils_1.maxWireVersion)(connection);
        const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {};
        const command = { listIndexes: this.collectionNamespace.collection, cursor };
        if (serverWireVersion >= 9 && this.options.comment !== void 0) {
          command.comment = this.options.comment;
        }
        return command;
      }
      handleOk(response) {
        return response;
      }
    };
    exports2.ListIndexesOperation = ListIndexesOperation;
    (0, operation_1.defineAspects)(ListIndexesOperation, [
      operation_1.Aspect.READ_OPERATION,
      operation_1.Aspect.RETRYABLE,
      operation_1.Aspect.CURSOR_CREATING,
      operation_1.Aspect.SUPPORTS_RAW_DATA
    ]);
    (0, operation_1.defineAspects)(CreateIndexesOperation, [operation_1.Aspect.WRITE_OPERATION, operation_1.Aspect.SUPPORTS_RAW_DATA]);
    (0, operation_1.defineAspects)(DropIndexOperation, [operation_1.Aspect.WRITE_OPERATION, operation_1.Aspect.SUPPORTS_RAW_DATA]);
  }
});

// node_modules/mongodb/lib/cursor/list_indexes_cursor.js
var require_list_indexes_cursor = __commonJS({
  "node_modules/mongodb/lib/cursor/list_indexes_cursor.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ListIndexesCursor = void 0;
    var execute_operation_1 = require_execute_operation();
    var indexes_1 = require_indexes();
    var abstract_cursor_1 = require_abstract_cursor();
    var ListIndexesCursor = class _ListIndexesCursor extends abstract_cursor_1.AbstractCursor {
      constructor(collection, options) {
        super(collection.client, collection.s.namespace, options);
        this.parent = collection;
        this.options = options;
      }
      clone() {
        return new _ListIndexesCursor(this.parent, {
          ...this.options,
          ...this.cursorOptions
        });
      }
      /** @internal */
      async _initialize(session) {
        const operation = new indexes_1.ListIndexesOperation(this.parent, {
          ...this.cursorOptions,
          ...this.options,
          session
        });
        const response = await (0, execute_operation_1.executeOperation)(this.parent.client, operation, this.timeoutContext);
        return { server: operation.server, session, response };
      }
    };
    exports2.ListIndexesCursor = ListIndexesCursor;
  }
});

// node_modules/mongodb/lib/cursor/list_search_indexes_cursor.js
var require_list_search_indexes_cursor = __commonJS({
  "node_modules/mongodb/lib/cursor/list_search_indexes_cursor.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ListSearchIndexesCursor = void 0;
    var aggregation_cursor_1 = require_aggregation_cursor();
    var ListSearchIndexesCursor = class extends aggregation_cursor_1.AggregationCursor {
      /** @internal */
      constructor({ fullNamespace: ns, client }, name, options = {}) {
        const pipeline2 = name == null ? [{ $listSearchIndexes: {} }] : [{ $listSearchIndexes: { name } }];
        super(client, ns, pipeline2, options);
      }
    };
    exports2.ListSearchIndexesCursor = ListSearchIndexesCursor;
  }
});

// node_modules/mongodb/lib/operations/distinct.js
var require_distinct = __commonJS({
  "node_modules/mongodb/lib/operations/distinct.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DistinctOperation = void 0;
    var responses_1 = require_responses();
    var command_1 = require_command();
    var operation_1 = require_operation();
    var DistinctOperation = class extends command_1.CommandOperation {
      /**
       * Construct a Distinct operation.
       *
       * @param collection - Collection instance.
       * @param key - Field of the document to find distinct values for.
       * @param query - The query for filtering the set of documents to which we apply the distinct filter.
       * @param options - Optional settings. See Collection.prototype.distinct for a list of options.
       */
      constructor(collection, key, query, options) {
        super(collection, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.options = options ?? {};
        this.collection = collection;
        this.key = key;
        this.query = query;
      }
      get commandName() {
        return "distinct";
      }
      buildCommandDocument(_connection) {
        const command = {
          distinct: this.collection.collectionName,
          key: this.key,
          query: this.query
        };
        if (this.options.comment !== void 0) {
          command.comment = this.options.comment;
        }
        if (this.options.hint != null) {
          command.hint = this.options.hint;
        }
        return command;
      }
      handleOk(response) {
        if (this.explain) {
          return response.toObject(this.bsonOptions);
        }
        return response.toObject(this.bsonOptions).values;
      }
    };
    exports2.DistinctOperation = DistinctOperation;
    (0, operation_1.defineAspects)(DistinctOperation, [
      operation_1.Aspect.READ_OPERATION,
      operation_1.Aspect.RETRYABLE,
      operation_1.Aspect.EXPLAINABLE,
      operation_1.Aspect.SUPPORTS_RAW_DATA
    ]);
  }
});

// node_modules/mongodb/lib/operations/estimated_document_count.js
var require_estimated_document_count = __commonJS({
  "node_modules/mongodb/lib/operations/estimated_document_count.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.EstimatedDocumentCountOperation = void 0;
    var responses_1 = require_responses();
    var command_1 = require_command();
    var operation_1 = require_operation();
    var EstimatedDocumentCountOperation = class extends command_1.CommandOperation {
      constructor(collection, options = {}) {
        super(collection, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.options = options;
        this.collectionName = collection.collectionName;
      }
      get commandName() {
        return "count";
      }
      buildCommandDocument(_connection, _session) {
        const cmd = { count: this.collectionName };
        if (typeof this.options.maxTimeMS === "number") {
          cmd.maxTimeMS = this.options.maxTimeMS;
        }
        if (this.options.comment !== void 0) {
          cmd.comment = this.options.comment;
        }
        return cmd;
      }
      handleOk(response) {
        return response.getNumber("n") ?? 0;
      }
    };
    exports2.EstimatedDocumentCountOperation = EstimatedDocumentCountOperation;
    (0, operation_1.defineAspects)(EstimatedDocumentCountOperation, [
      operation_1.Aspect.READ_OPERATION,
      operation_1.Aspect.RETRYABLE,
      operation_1.Aspect.CURSOR_CREATING,
      operation_1.Aspect.SUPPORTS_RAW_DATA
    ]);
  }
});

// node_modules/mongodb/lib/operations/find_and_modify.js
var require_find_and_modify = __commonJS({
  "node_modules/mongodb/lib/operations/find_and_modify.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.FindOneAndUpdateOperation = exports2.FindOneAndReplaceOperation = exports2.FindOneAndDeleteOperation = exports2.FindAndModifyOperation = exports2.ReturnDocument = void 0;
    var responses_1 = require_responses();
    var error_1 = require_error();
    var read_preference_1 = require_read_preference();
    var sort_1 = require_sort();
    var utils_1 = require_utils();
    var command_1 = require_command();
    var operation_1 = require_operation();
    exports2.ReturnDocument = Object.freeze({
      BEFORE: "before",
      AFTER: "after"
    });
    function configureFindAndModifyCmdBaseUpdateOpts(cmdBase, options) {
      cmdBase.new = options.returnDocument === exports2.ReturnDocument.AFTER;
      cmdBase.upsert = options.upsert === true;
      if (options.bypassDocumentValidation === true) {
        cmdBase.bypassDocumentValidation = options.bypassDocumentValidation;
      }
      return cmdBase;
    }
    var FindAndModifyOperation = class extends command_1.CommandOperation {
      constructor(collection, query, options) {
        super(collection, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.options = options;
        this.readPreference = read_preference_1.ReadPreference.primary;
        this.collection = collection;
        this.query = query;
      }
      get commandName() {
        return "findAndModify";
      }
      buildCommandDocument(connection, _session) {
        const options = this.options;
        const command = {
          findAndModify: this.collection.collectionName,
          query: this.query,
          remove: false,
          new: false,
          upsert: false
        };
        options.includeResultMetadata ??= false;
        const sort = (0, sort_1.formatSort)(options.sort);
        if (sort) {
          command.sort = sort;
        }
        if (options.projection) {
          command.fields = options.projection;
        }
        if (options.maxTimeMS) {
          command.maxTimeMS = options.maxTimeMS;
        }
        if (options.writeConcern) {
          command.writeConcern = options.writeConcern;
        }
        if (options.let) {
          command.let = options.let;
        }
        if (options.comment !== void 0) {
          command.comment = options.comment;
        }
        (0, utils_1.decorateWithCollation)(command, options);
        if (options.hint) {
          const unacknowledgedWrite = this.writeConcern?.w === 0;
          if (unacknowledgedWrite && (0, utils_1.maxWireVersion)(connection) < 9) {
            throw new error_1.MongoCompatibilityError("hint for the findAndModify command is only supported on MongoDB 4.4+");
          }
          command.hint = options.hint;
        }
        return command;
      }
      handleOk(response) {
        const result = super.handleOk(response);
        return this.options.includeResultMetadata ? result : result.value ?? null;
      }
    };
    exports2.FindAndModifyOperation = FindAndModifyOperation;
    var FindOneAndDeleteOperation = class extends FindAndModifyOperation {
      constructor(collection, filter, options) {
        if (filter == null || typeof filter !== "object") {
          throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object');
        }
        super(collection, filter, options);
      }
      buildCommandDocument(connection, session) {
        const document2 = super.buildCommandDocument(connection, session);
        document2.remove = true;
        return document2;
      }
    };
    exports2.FindOneAndDeleteOperation = FindOneAndDeleteOperation;
    var FindOneAndReplaceOperation = class extends FindAndModifyOperation {
      constructor(collection, filter, replacement, options) {
        if (filter == null || typeof filter !== "object") {
          throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object');
        }
        if (replacement == null || typeof replacement !== "object") {
          throw new error_1.MongoInvalidArgumentError('Argument "replacement" must be an object');
        }
        if ((0, utils_1.hasAtomicOperators)(replacement)) {
          throw new error_1.MongoInvalidArgumentError("Replacement document must not contain atomic operators");
        }
        super(collection, filter, options);
        this.replacement = replacement;
      }
      buildCommandDocument(connection, session) {
        const document2 = super.buildCommandDocument(connection, session);
        document2.update = this.replacement;
        configureFindAndModifyCmdBaseUpdateOpts(document2, this.options);
        return document2;
      }
    };
    exports2.FindOneAndReplaceOperation = FindOneAndReplaceOperation;
    var FindOneAndUpdateOperation = class extends FindAndModifyOperation {
      constructor(collection, filter, update, options) {
        if (filter == null || typeof filter !== "object") {
          throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object');
        }
        if (update == null || typeof update !== "object") {
          throw new error_1.MongoInvalidArgumentError('Argument "update" must be an object');
        }
        if (!(0, utils_1.hasAtomicOperators)(update, options)) {
          throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators");
        }
        super(collection, filter, options);
        this.update = update;
        this.options = options;
      }
      buildCommandDocument(connection, session) {
        const document2 = super.buildCommandDocument(connection, session);
        document2.update = this.update;
        configureFindAndModifyCmdBaseUpdateOpts(document2, this.options);
        if (this.options.arrayFilters) {
          document2.arrayFilters = this.options.arrayFilters;
        }
        return document2;
      }
    };
    exports2.FindOneAndUpdateOperation = FindOneAndUpdateOperation;
    (0, operation_1.defineAspects)(FindAndModifyOperation, [
      operation_1.Aspect.WRITE_OPERATION,
      operation_1.Aspect.RETRYABLE,
      operation_1.Aspect.EXPLAINABLE,
      operation_1.Aspect.SUPPORTS_RAW_DATA
    ]);
  }
});

// node_modules/mongodb/lib/operations/rename.js
var require_rename = __commonJS({
  "node_modules/mongodb/lib/operations/rename.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RenameOperation = void 0;
    var responses_1 = require_responses();
    var collection_1 = require_collection();
    var utils_1 = require_utils();
    var command_1 = require_command();
    var operation_1 = require_operation();
    var RenameOperation = class extends command_1.CommandOperation {
      constructor(collection, newName, options) {
        super(collection, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.collection = collection;
        this.newName = newName;
        this.options = options;
        this.ns = new utils_1.MongoDBNamespace("admin", "$cmd");
      }
      get commandName() {
        return "renameCollection";
      }
      buildCommandDocument(_connection, _session) {
        const renameCollection = this.collection.namespace;
        const to = this.collection.s.namespace.withCollection(this.newName).toString();
        const dropTarget = typeof this.options.dropTarget === "boolean" ? this.options.dropTarget : false;
        return {
          renameCollection,
          to,
          dropTarget
        };
      }
      handleOk(_response) {
        return new collection_1.Collection(this.collection.db, this.newName, this.collection.s.options);
      }
    };
    exports2.RenameOperation = RenameOperation;
    (0, operation_1.defineAspects)(RenameOperation, [operation_1.Aspect.WRITE_OPERATION]);
  }
});

// node_modules/mongodb/lib/operations/search_indexes/create.js
var require_create = __commonJS({
  "node_modules/mongodb/lib/operations/search_indexes/create.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CreateSearchIndexesOperation = void 0;
    var responses_1 = require_responses();
    var operation_1 = require_operation();
    var CreateSearchIndexesOperation = class extends operation_1.AbstractOperation {
      constructor(collection, descriptions) {
        super();
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.collection = collection;
        this.descriptions = descriptions;
        this.ns = collection.fullNamespace;
      }
      get commandName() {
        return "createSearchIndexes";
      }
      buildCommand(_connection, _session) {
        const namespace = this.collection.fullNamespace;
        return {
          createSearchIndexes: namespace.collection,
          indexes: this.descriptions
        };
      }
      handleOk(response) {
        return super.handleOk(response).indexesCreated.map((val) => val.name);
      }
      buildOptions(timeoutContext) {
        return { session: this.session, timeoutContext };
      }
    };
    exports2.CreateSearchIndexesOperation = CreateSearchIndexesOperation;
  }
});

// node_modules/mongodb/lib/operations/search_indexes/drop.js
var require_drop = __commonJS({
  "node_modules/mongodb/lib/operations/search_indexes/drop.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DropSearchIndexOperation = void 0;
    var responses_1 = require_responses();
    var error_1 = require_error();
    var operation_1 = require_operation();
    var DropSearchIndexOperation = class extends operation_1.AbstractOperation {
      constructor(collection, name) {
        super();
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.collection = collection;
        this.name = name;
        this.ns = collection.fullNamespace;
      }
      get commandName() {
        return "dropSearchIndex";
      }
      buildCommand(_connection, _session) {
        const namespace = this.collection.fullNamespace;
        const command = {
          dropSearchIndex: namespace.collection
        };
        if (typeof this.name === "string") {
          command.name = this.name;
        }
        return command;
      }
      handleOk(_response) {
      }
      buildOptions(timeoutContext) {
        return { session: this.session, timeoutContext };
      }
      handleError(error51) {
        const isNamespaceNotFoundError = error51 instanceof error_1.MongoServerError && error51.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound;
        if (!isNamespaceNotFoundError) {
          throw error51;
        }
      }
    };
    exports2.DropSearchIndexOperation = DropSearchIndexOperation;
  }
});

// node_modules/mongodb/lib/operations/search_indexes/update.js
var require_update2 = __commonJS({
  "node_modules/mongodb/lib/operations/search_indexes/update.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.UpdateSearchIndexOperation = void 0;
    var responses_1 = require_responses();
    var operation_1 = require_operation();
    var UpdateSearchIndexOperation = class extends operation_1.AbstractOperation {
      constructor(collection, name, definition) {
        super();
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.collection = collection;
        this.name = name;
        this.definition = definition;
        this.ns = collection.fullNamespace;
      }
      get commandName() {
        return "updateSearchIndex";
      }
      buildCommand(_connection, _session) {
        const namespace = this.collection.fullNamespace;
        return {
          updateSearchIndex: namespace.collection,
          name: this.name,
          definition: this.definition
        };
      }
      handleOk(_response) {
      }
      buildOptions(timeoutContext) {
        return { session: this.session, timeoutContext };
      }
    };
    exports2.UpdateSearchIndexOperation = UpdateSearchIndexOperation;
  }
});

// node_modules/mongodb/lib/collection.js
var require_collection = __commonJS({
  "node_modules/mongodb/lib/collection.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Collection = void 0;
    var bson_1 = require_bson2();
    var ordered_1 = require_ordered();
    var unordered_1 = require_unordered();
    var change_stream_1 = require_change_stream();
    var aggregation_cursor_1 = require_aggregation_cursor();
    var find_cursor_1 = require_find_cursor();
    var list_indexes_cursor_1 = require_list_indexes_cursor();
    var list_search_indexes_cursor_1 = require_list_search_indexes_cursor();
    var error_1 = require_error();
    var count_1 = require_count();
    var delete_1 = require_delete();
    var distinct_1 = require_distinct();
    var estimated_document_count_1 = require_estimated_document_count();
    var execute_operation_1 = require_execute_operation();
    var find_and_modify_1 = require_find_and_modify();
    var indexes_1 = require_indexes();
    var insert_1 = require_insert();
    var rename_1 = require_rename();
    var create_1 = require_create();
    var drop_1 = require_drop();
    var update_1 = require_update2();
    var update_2 = require_update();
    var read_concern_1 = require_read_concern();
    var read_preference_1 = require_read_preference();
    var utils_1 = require_utils();
    var write_concern_1 = require_write_concern();
    var Collection = class {
      /**
       * Create a new Collection instance
       * @internal
       */
      constructor(db, name, options) {
        this.db = db;
        this.s = {
          db,
          options,
          namespace: new utils_1.MongoDBCollectionNamespace(db.databaseName, name),
          pkFactory: db.options?.pkFactory ?? utils_1.DEFAULT_PK_FACTORY,
          readPreference: read_preference_1.ReadPreference.fromOptions(options),
          bsonOptions: (0, bson_1.resolveBSONOptions)(options, db),
          readConcern: read_concern_1.ReadConcern.fromOptions(options),
          writeConcern: write_concern_1.WriteConcern.fromOptions(options)
        };
        this.client = db.client;
      }
      /**
       * The name of the database this collection belongs to
       */
      get dbName() {
        return this.s.namespace.db;
      }
      /**
       * The name of this collection
       */
      get collectionName() {
        return this.s.namespace.collection;
      }
      /**
       * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}`
       */
      get namespace() {
        return this.fullNamespace.toString();
      }
      /**
       *  @internal
       *
       * The `MongoDBNamespace` for the collection.
       */
      get fullNamespace() {
        return this.s.namespace;
      }
      /**
       * The current readConcern of the collection. If not explicitly defined for
       * this collection, will be inherited from the parent DB
       */
      get readConcern() {
        if (this.s.readConcern == null) {
          return this.db.readConcern;
        }
        return this.s.readConcern;
      }
      /**
       * The current readPreference of the collection. If not explicitly defined for
       * this collection, will be inherited from the parent DB
       */
      get readPreference() {
        if (this.s.readPreference == null) {
          return this.db.readPreference;
        }
        return this.s.readPreference;
      }
      get bsonOptions() {
        return this.s.bsonOptions;
      }
      /**
       * The current writeConcern of the collection. If not explicitly defined for
       * this collection, will be inherited from the parent DB
       */
      get writeConcern() {
        if (this.s.writeConcern == null) {
          return this.db.writeConcern;
        }
        return this.s.writeConcern;
      }
      /** The current index hint for the collection */
      get hint() {
        return this.s.collectionHint;
      }
      set hint(v) {
        this.s.collectionHint = (0, utils_1.normalizeHintField)(v);
      }
      get timeoutMS() {
        return this.s.options.timeoutMS;
      }
      /**
       * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field,
       * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
       * can be overridden by setting the **forceServerObjectId** flag.
       *
       * @param doc - The document to insert
       * @param options - Optional settings for the command
       */
      async insertOne(doc, options) {
        return await (0, execute_operation_1.executeOperation)(this.client, new insert_1.InsertOneOperation(this, doc, (0, utils_1.resolveOptions)(this, options)));
      }
      /**
       * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field,
       * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
       * can be overridden by setting the **forceServerObjectId** flag.
       *
       * @param docs - The documents to insert
       * @param options - Optional settings for the command
       */
      async insertMany(docs, options) {
        if (!Array.isArray(docs)) {
          throw new error_1.MongoInvalidArgumentError('Argument "docs" must be an array of documents');
        }
        options = (0, utils_1.resolveOptions)(this, options ?? {});
        const acknowledged = write_concern_1.WriteConcern.fromOptions(options)?.w !== 0;
        try {
          const res = await this.bulkWrite(docs.map((doc) => ({ insertOne: { document: doc } })), options);
          return {
            acknowledged,
            insertedCount: res.insertedCount,
            insertedIds: res.insertedIds
          };
        } catch (err) {
          if (err && err.message === "Operation must be an object with an operation key") {
            throw new error_1.MongoInvalidArgumentError("Collection.insertMany() cannot be called with an array that has null/undefined values");
          }
          throw err;
        }
      }
      /**
       * Perform a bulkWrite operation without a fluent API
       *
       * Legal operation types are
       * - `insertOne`
       * - `replaceOne`
       * - `updateOne`
       * - `updateMany`
       * - `deleteOne`
       * - `deleteMany`
       *
       * If documents passed in do not contain the **_id** field,
       * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
       * can be overridden by setting the **forceServerObjectId** flag.
       *
       * @param operations - Bulk operations to perform
       * @param options - Optional settings for the command
       * @throws MongoDriverError if operations is not an array
       */
      async bulkWrite(operations, options) {
        if (!Array.isArray(operations)) {
          throw new error_1.MongoInvalidArgumentError('Argument "operations" must be an array of documents');
        }
        options = (0, utils_1.resolveOptions)(this, options ?? {});
        const isConnected = this.client.topology != null;
        if (!isConnected) {
          await (0, execute_operation_1.autoConnect)(this.client);
        }
        const bulk = options.ordered === false ? this.initializeUnorderedBulkOp(options) : this.initializeOrderedBulkOp(options);
        for (const operation of operations) {
          bulk.raw(operation);
        }
        return await bulk.execute({ ...options });
      }
      /**
       * Update a single document in a collection
       *
       * The value of `update` can be either:
       * - UpdateFilter<TSchema> - A document that contains update operator expressions,
       * - Document[] - an aggregation pipeline.
       *
       * @param filter - The filter used to select the document to update
       * @param update - The modifications to apply
       * @param options - Optional settings for the command
       */
      async updateOne(filter, update, options) {
        return await (0, execute_operation_1.executeOperation)(this.client, new update_2.UpdateOneOperation(this.s.namespace, filter, update, (0, utils_1.resolveOptions)(this, options)));
      }
      /**
       * Replace a document in a collection with another document
       *
       * @param filter - The filter used to select the document to replace
       * @param replacement - The Document that replaces the matching document
       * @param options - Optional settings for the command
       */
      async replaceOne(filter, replacement, options) {
        return await (0, execute_operation_1.executeOperation)(this.client, new update_2.ReplaceOneOperation(this.s.namespace, filter, replacement, (0, utils_1.resolveOptions)(this, options)));
      }
      /**
       * Update multiple documents in a collection
       *
       * The value of `update` can be either:
       * - UpdateFilter<TSchema> - A document that contains update operator expressions,
       * - Document[] - an aggregation pipeline.
       *
       * @param filter - The filter used to select the document to update
       * @param update - The modifications to apply
       * @param options - Optional settings for the command
       */
      async updateMany(filter, update, options) {
        return await (0, execute_operation_1.executeOperation)(this.client, new update_2.UpdateManyOperation(this.s.namespace, filter, update, (0, utils_1.resolveOptions)(this, options)));
      }
      /**
       * Delete a document from a collection
       *
       * @param filter - The filter used to select the document to remove
       * @param options - Optional settings for the command
       */
      async deleteOne(filter = {}, options = {}) {
        return await (0, execute_operation_1.executeOperation)(this.client, new delete_1.DeleteOneOperation(this.s.namespace, filter, (0, utils_1.resolveOptions)(this, options)));
      }
      /**
       * Delete multiple documents from a collection
       *
       * @param filter - The filter used to select the documents to remove
       * @param options - Optional settings for the command
       */
      async deleteMany(filter = {}, options = {}) {
        return await (0, execute_operation_1.executeOperation)(this.client, new delete_1.DeleteManyOperation(this.s.namespace, filter, (0, utils_1.resolveOptions)(this, options)));
      }
      /**
       * Rename the collection.
       *
       * @remarks
       * This operation does not inherit options from the Db or MongoClient.
       *
       * @param newName - New name of of the collection.
       * @param options - Optional settings for the command
       */
      async rename(newName, options) {
        return await (0, execute_operation_1.executeOperation)(this.client, new rename_1.RenameOperation(this, newName, (0, utils_1.resolveOptions)(void 0, {
          ...options,
          readPreference: read_preference_1.ReadPreference.PRIMARY
        })));
      }
      /**
       * Drop the collection from the database, removing it permanently. New accesses will create a new collection.
       *
       * @param options - Optional settings for the command
       */
      async drop(options) {
        return await this.db.dropCollection(this.collectionName, options);
      }
      async findOne(filter = {}, options = {}) {
        const { ...opts } = options;
        opts.singleBatch = true;
        const cursor = this.find(filter, opts).limit(1);
        const result = await cursor.next();
        await cursor.close();
        return result;
      }
      find(filter = {}, options = {}) {
        return new find_cursor_1.FindCursor(this.client, this.s.namespace, filter, (0, utils_1.resolveOptions)(this, options));
      }
      /**
       * Returns the options of the collection.
       *
       * @param options - Optional settings for the command
       */
      async options(options) {
        options = (0, utils_1.resolveOptions)(this, options);
        const [collection] = await this.db.listCollections({ name: this.collectionName }, { ...options, nameOnly: false }).toArray();
        if (collection == null || collection.options == null) {
          throw new error_1.MongoAPIError(`collection ${this.namespace} not found`);
        }
        return collection.options;
      }
      /**
       * Returns if the collection is a capped collection
       *
       * @param options - Optional settings for the command
       */
      async isCapped(options) {
        const { capped } = await this.options(options);
        return Boolean(capped);
      }
      /**
       * Creates an index on the db and collection collection.
       *
       * @param indexSpec - The field name or index specification to create an index for
       * @param options - Optional settings for the command
       *
       * @example
       * ```ts
       * const collection = client.db('foo').collection('bar');
       *
       * await collection.createIndex({ a: 1, b: -1 });
       *
       * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes
       * await collection.createIndex([ [c, 1], [d, -1] ]);
       *
       * // Equivalent to { e: 1 }
       * await collection.createIndex('e');
       *
       * // Equivalent to { f: 1, g: 1 }
       * await collection.createIndex(['f', 'g'])
       *
       * // Equivalent to { h: 1, i: -1 }
       * await collection.createIndex([ { h: 1 }, { i: -1 } ]);
       *
       * // Equivalent to { j: 1, k: -1, l: 2d }
       * await collection.createIndex(['j', ['k', -1], { l: '2d' }])
       * ```
       */
      async createIndex(indexSpec, options) {
        const indexes = await (0, execute_operation_1.executeOperation)(this.client, indexes_1.CreateIndexesOperation.fromIndexSpecification(this, this.collectionName, indexSpec, (0, utils_1.resolveOptions)(this, options)));
        return indexes[0];
      }
      /**
       * Creates multiple indexes in the collection, this method is only supported for
       * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported
       * error.
       *
       * **Note**: Unlike {@link Collection#createIndex| createIndex}, this function takes in raw index specifications.
       * Index specifications are defined {@link https://www.mongodb.com/docs/manual/reference/command/createIndexes/| here}.
       *
       * @param indexSpecs - An array of index specifications to be created
       * @param options - Optional settings for the command
       *
       * @example
       * ```ts
       * const collection = client.db('foo').collection('bar');
       * await collection.createIndexes([
       *   // Simple index on field fizz
       *   {
       *     key: { fizz: 1 },
       *   }
       *   // wildcard index
       *   {
       *     key: { '$**': 1 }
       *   },
       *   // named index on darmok and jalad
       *   {
       *     key: { darmok: 1, jalad: -1 }
       *     name: 'tanagra'
       *   }
       * ]);
       * ```
       */
      async createIndexes(indexSpecs, options) {
        return await (0, execute_operation_1.executeOperation)(this.client, indexes_1.CreateIndexesOperation.fromIndexDescriptionArray(this, this.collectionName, indexSpecs, (0, utils_1.resolveOptions)(this, { ...options, maxTimeMS: void 0 })));
      }
      /**
       * Drops an index from this collection.
       *
       * @param indexName - Name of the index to drop.
       * @param options - Optional settings for the command
       */
      async dropIndex(indexName, options) {
        return await (0, execute_operation_1.executeOperation)(this.client, new indexes_1.DropIndexOperation(this, indexName, {
          ...(0, utils_1.resolveOptions)(this, options),
          readPreference: read_preference_1.ReadPreference.primary
        }));
      }
      /**
       * Drops all indexes from this collection.
       *
       * @param options - Optional settings for the command
       */
      async dropIndexes(options) {
        try {
          await (0, execute_operation_1.executeOperation)(this.client, new indexes_1.DropIndexOperation(this, "*", (0, utils_1.resolveOptions)(this, options)));
          return true;
        } catch (error51) {
          if (error51 instanceof error_1.MongoOperationTimeoutError)
            throw error51;
          return false;
        }
      }
      /**
       * Get the list of all indexes information for the collection.
       *
       * @param options - Optional settings for the command
       */
      listIndexes(options) {
        return new list_indexes_cursor_1.ListIndexesCursor(this, (0, utils_1.resolveOptions)(this, options));
      }
      /**
       * Checks if one or more indexes exist on the collection, fails on first non-existing index
       *
       * @param indexes - One or more index names to check.
       * @param options - Optional settings for the command
       */
      async indexExists(indexes, options) {
        const indexNames = Array.isArray(indexes) ? indexes : [indexes];
        const allIndexes = new Set(await this.listIndexes(options).map(({ name }) => name).toArray());
        return indexNames.every((name) => allIndexes.has(name));
      }
      async indexInformation(options) {
        return await this.indexes({
          ...options,
          full: options?.full ?? false
        });
      }
      /**
       * Gets an estimate of the count of documents in a collection using collection metadata.
       * This will always run a count command on all server versions.
       *
       * due to an oversight in versions 5.0.0-5.0.8 of MongoDB, the count command,
       * which estimatedDocumentCount uses in its implementation, was not included in v1 of
       * the Stable API, and so users of the Stable API with estimatedDocumentCount are
       * recommended to upgrade their server version to 5.0.9+ or set apiStrict: false to avoid
       * encountering errors.
       *
       * @see {@link https://www.mongodb.com/docs/manual/reference/command/count/#behavior|Count: Behavior}
       * @param options - Optional settings for the command
       */
      async estimatedDocumentCount(options) {
        return await (0, execute_operation_1.executeOperation)(this.client, new estimated_document_count_1.EstimatedDocumentCountOperation(this, (0, utils_1.resolveOptions)(this, options)));
      }
      /**
       * Gets the number of documents matching the filter.
       * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount| estimatedDocumentCount}.
       *
       * Due to countDocuments using the $match aggregation pipeline stage, certain query operators cannot be used in countDocuments. This includes the $where and $near query operators, among others. Details can be found in the documentation for the $match aggregation pipeline stage.
       *
       * **Note**: When migrating from {@link Collection#count| count} to {@link Collection#countDocuments| countDocuments}
       * the following query operators must be replaced:
       *
       * | Operator | Replacement |
       * | -------- | ----------- |
       * | `$where`   | [`$expr`][1] |
       * | `$near`    | [`$geoWithin`][2] with [`$center`][3] |
       * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] |
       *
       * [1]: https://www.mongodb.com/docs/manual/reference/operator/query/expr/
       * [2]: https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/
       * [3]: https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center
       * [4]: https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere
       *
       * @param filter - The filter for the count
       * @param options - Optional settings for the command
       *
       * @see https://www.mongodb.com/docs/manual/reference/operator/query/expr/
       * @see https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/
       * @see https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center
       * @see https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere
       */
      async countDocuments(filter = {}, options = {}) {
        const pipeline2 = [];
        pipeline2.push({ $match: filter });
        if (typeof options.skip === "number") {
          pipeline2.push({ $skip: options.skip });
        }
        if (typeof options.limit === "number") {
          pipeline2.push({ $limit: options.limit });
        }
        pipeline2.push({ $group: { _id: 1, n: { $sum: 1 } } });
        const cursor = this.aggregate(pipeline2, options);
        const doc = await cursor.next();
        await cursor.close();
        return doc?.n ?? 0;
      }
      async distinct(key, filter = {}, options = {}) {
        return await (0, execute_operation_1.executeOperation)(this.client, new distinct_1.DistinctOperation(this, key, filter, (0, utils_1.resolveOptions)(this, options)));
      }
      async indexes(options) {
        const indexes = await this.listIndexes(options).toArray();
        const full = options?.full ?? true;
        if (full) {
          return indexes;
        }
        const object3 = Object.fromEntries(indexes.map(({ name, key }) => [name, Object.entries(key)]));
        return object3;
      }
      async findOneAndDelete(filter, options) {
        return await (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndDeleteOperation(this, filter, (0, utils_1.resolveOptions)(this, options)));
      }
      async findOneAndReplace(filter, replacement, options) {
        return await (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndReplaceOperation(this, filter, replacement, (0, utils_1.resolveOptions)(this, options)));
      }
      async findOneAndUpdate(filter, update, options) {
        return await (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndUpdateOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options)));
      }
      /**
       * Execute an aggregation framework pipeline against the collection, needs MongoDB \>= 2.2
       *
       * @param pipeline - An array of aggregation pipelines to execute
       * @param options - Optional settings for the command
       */
      aggregate(pipeline2 = [], options) {
        if (!Array.isArray(pipeline2)) {
          throw new error_1.MongoInvalidArgumentError('Argument "pipeline" must be an array of aggregation stages');
        }
        return new aggregation_cursor_1.AggregationCursor(this.client, this.s.namespace, pipeline2, (0, utils_1.resolveOptions)(this, options));
      }
      /**
       * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection.
       *
       * @remarks
       * watch() accepts two generic arguments for distinct use cases:
       * - The first is to override the schema that may be defined for this specific collection
       * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument
       * @example
       * By just providing the first argument I can type the change to be `ChangeStreamDocument<{ _id: number }>`
       * ```ts
       * collection.watch<{ _id: number }>()
       *   .on('change', change => console.log(change._id.toFixed(4)));
       * ```
       *
       * @example
       * Passing a second argument provides a way to reflect the type changes caused by an advanced pipeline.
       * Here, we are using a pipeline to have MongoDB filter for insert changes only and add a comment.
       * No need start from scratch on the ChangeStreamInsertDocument type!
       * By using an intersection we can save time and ensure defaults remain the same type!
       * ```ts
       * collection
       *   .watch<Schema, ChangeStreamInsertDocument<Schema> & { comment: string }>([
       *     { $addFields: { comment: 'big changes' } },
       *     { $match: { operationType: 'insert' } }
       *   ])
       *   .on('change', change => {
       *     change.comment.startsWith('big');
       *     change.operationType === 'insert';
       *     // No need to narrow in code because the generics did that for us!
       *     expectType<Schema>(change.fullDocument);
       *   });
       * ```
       *
       * @remarks
       * When `timeoutMS` is configured for a change stream, it will have different behaviour depending
       * on whether the change stream is in iterator mode or emitter mode. In both cases, a change
       * stream will time out if it does not receive a change event within `timeoutMS` of the last change
       * event.
       *
       * Note that if a change stream is consistently timing out when watching a collection, database or
       * client that is being changed, then this may be due to the server timing out before it can finish
       * processing the existing oplog. To address this, restart the change stream with a higher
       * `timeoutMS`.
       *
       * If the change stream times out the initial aggregate operation to establish the change stream on
       * the server, then the client will close the change stream. If the getMore calls to the server
       * time out, then the change stream will be left open, but will throw a MongoOperationTimeoutError
       * when in iterator mode and emit an error event that returns a MongoOperationTimeoutError in
       * emitter mode.
       *
       * To determine whether or not the change stream is still open following a timeout, check the
       * {@link ChangeStream.closed} getter.
       *
       * @example
       * In iterator mode, if a next() call throws a timeout error, it will attempt to resume the change stream.
       * The next call can just be retried after this succeeds.
       * ```ts
       * const changeStream = collection.watch([], { timeoutMS: 100 });
       * try {
       *     await changeStream.next();
       * } catch (e) {
       *     if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
       *       await changeStream.next();
       *     }
       *     throw e;
       * }
       * ```
       *
       * @example
       * In emitter mode, if the change stream goes `timeoutMS` without emitting a change event, it will
       * emit an error event that returns a MongoOperationTimeoutError, but will not close the change
       * stream unless the resume attempt fails. There is no need to re-establish change listeners as
       * this will automatically continue emitting change events once the resume attempt completes.
       *
       * ```ts
       * const changeStream = collection.watch([], { timeoutMS: 100 });
       * changeStream.on('change', console.log);
       * changeStream.on('error', e => {
       *     if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
       *         // do nothing
       *     } else {
       *         changeStream.close();
       *     }
       * });
       * ```
       *
       * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
       * @param options - Optional settings for the command
       * @typeParam TLocal - Type of the data being detected by the change stream
       * @typeParam TChange - Type of the whole change stream document emitted
       */
      watch(pipeline2 = [], options = {}) {
        if (!Array.isArray(pipeline2)) {
          options = pipeline2;
          pipeline2 = [];
        }
        return new change_stream_1.ChangeStream(this, pipeline2, (0, utils_1.resolveOptions)(this, options));
      }
      /**
       * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
       *
       * @throws MongoNotConnectedError
       * @remarks
       * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation.
       * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting.
       */
      initializeUnorderedBulkOp(options) {
        return new unordered_1.UnorderedBulkOperation(this, (0, utils_1.resolveOptions)(this, options));
      }
      /**
       * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types.
       *
       * @throws MongoNotConnectedError
       * @remarks
       * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation.
       * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting.
       */
      initializeOrderedBulkOp(options) {
        return new ordered_1.OrderedBulkOperation(this, (0, utils_1.resolveOptions)(this, options));
      }
      /**
       * An estimated count of matching documents in the db to a filter.
       *
       * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents
       * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments| countDocuments}.
       * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount| estimatedDocumentCount}.
       *
       * @deprecated use {@link Collection#countDocuments| countDocuments} or {@link Collection#estimatedDocumentCount| estimatedDocumentCount} instead
       *
       * @param filter - The filter for the count.
       * @param options - Optional settings for the command
       */
      async count(filter = {}, options = {}) {
        return await (0, execute_operation_1.executeOperation)(this.client, new count_1.CountOperation(this.fullNamespace, filter, (0, utils_1.resolveOptions)(this, options)));
      }
      listSearchIndexes(indexNameOrOptions, options) {
        options = typeof indexNameOrOptions === "object" ? indexNameOrOptions : options == null ? {} : options;
        const indexName = indexNameOrOptions == null ? null : typeof indexNameOrOptions === "object" ? null : indexNameOrOptions;
        return new list_search_indexes_cursor_1.ListSearchIndexesCursor(this, indexName, options);
      }
      /**
       * Creates a single search index for the collection.
       *
       * @param description - The index description for the new search index.
       * @returns A promise that resolves to the name of the new search index.
       *
       * @remarks Only available when used against a 7.0+ Atlas cluster.
       */
      async createSearchIndex(description) {
        const [index] = await this.createSearchIndexes([description]);
        return index;
      }
      /**
       * Creates multiple search indexes for the current collection.
       *
       * @param descriptions - An array of `SearchIndexDescription`s for the new search indexes.
       * @returns A promise that resolves to an array of the newly created search index names.
       *
       * @remarks Only available when used against a 7.0+ Atlas cluster.
       * @returns
       */
      async createSearchIndexes(descriptions) {
        return await (0, execute_operation_1.executeOperation)(this.client, new create_1.CreateSearchIndexesOperation(this, descriptions));
      }
      /**
       * Deletes a search index by index name.
       *
       * @param name - The name of the search index to be deleted.
       *
       * @remarks Only available when used against a 7.0+ Atlas cluster.
       */
      async dropSearchIndex(name) {
        return await (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropSearchIndexOperation(this, name));
      }
      /**
       * Updates a search index by replacing the existing index definition with the provided definition.
       *
       * @param name - The name of the search index to update.
       * @param definition - The new search index definition.
       *
       * @remarks Only available when used against a 7.0+ Atlas cluster.
       */
      async updateSearchIndex(name, definition) {
        return await (0, execute_operation_1.executeOperation)(this.client, new update_1.UpdateSearchIndexOperation(this, name, definition));
      }
    };
    exports2.Collection = Collection;
  }
});

// node_modules/mongodb/lib/cursor/change_stream_cursor.js
var require_change_stream_cursor = __commonJS({
  "node_modules/mongodb/lib/cursor/change_stream_cursor.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ChangeStreamCursor = void 0;
    var change_stream_1 = require_change_stream();
    var constants_1 = require_constants2();
    var aggregate_1 = require_aggregate();
    var execute_operation_1 = require_execute_operation();
    var utils_1 = require_utils();
    var abstract_cursor_1 = require_abstract_cursor();
    var ChangeStreamCursor = class _ChangeStreamCursor extends abstract_cursor_1.AbstractCursor {
      constructor(client, namespace, pipeline2 = [], options = {}) {
        super(client, namespace, { ...options, tailable: true, awaitData: true });
        this.pipeline = pipeline2;
        this.changeStreamCursorOptions = options;
        this._resumeToken = null;
        this.startAtOperationTime = options.startAtOperationTime ?? null;
        if (options.startAfter) {
          this.resumeToken = options.startAfter;
        } else if (options.resumeAfter) {
          this.resumeToken = options.resumeAfter;
        }
      }
      set resumeToken(token) {
        this._resumeToken = token;
        this.emit(change_stream_1.ChangeStream.RESUME_TOKEN_CHANGED, token);
      }
      get resumeToken() {
        return this._resumeToken;
      }
      get resumeOptions() {
        const options = {
          ...this.changeStreamCursorOptions
        };
        for (const key of ["resumeAfter", "startAfter", "startAtOperationTime"]) {
          delete options[key];
        }
        if (this.resumeToken != null) {
          if (this.changeStreamCursorOptions.startAfter && !this.hasReceived) {
            options.startAfter = this.resumeToken;
          } else {
            options.resumeAfter = this.resumeToken;
          }
        } else if (this.startAtOperationTime != null) {
          options.startAtOperationTime = this.startAtOperationTime;
        }
        return options;
      }
      cacheResumeToken(resumeToken) {
        if (this.bufferedCount() === 0 && this.postBatchResumeToken) {
          this.resumeToken = this.postBatchResumeToken;
        } else {
          this.resumeToken = resumeToken;
        }
        this.hasReceived = true;
      }
      _processBatch(response) {
        const { postBatchResumeToken } = response;
        if (postBatchResumeToken) {
          this.postBatchResumeToken = postBatchResumeToken;
          if (response.batchSize === 0) {
            this.resumeToken = postBatchResumeToken;
          }
        }
      }
      clone() {
        return new _ChangeStreamCursor(this.client, this.namespace, this.pipeline, {
          ...this.cursorOptions
        });
      }
      async _initialize(session) {
        const aggregateOperation = new aggregate_1.AggregateOperation(this.namespace, this.pipeline, {
          ...this.cursorOptions,
          ...this.changeStreamCursorOptions,
          session
        });
        const response = await (0, execute_operation_1.executeOperation)(session.client, aggregateOperation, this.timeoutContext);
        const server = aggregateOperation.server;
        this.maxWireVersion = (0, utils_1.maxWireVersion)(server);
        if (this.startAtOperationTime == null && this.changeStreamCursorOptions.resumeAfter == null && this.changeStreamCursorOptions.startAfter == null) {
          this.startAtOperationTime = response.operationTime;
        }
        this._processBatch(response);
        this.emit(constants_1.INIT, response);
        this.emit(constants_1.RESPONSE);
        return { server, session, response };
      }
      async getMore() {
        const response = await super.getMore();
        this.maxWireVersion = (0, utils_1.maxWireVersion)(this.server);
        this._processBatch(response);
        this.emit(change_stream_1.ChangeStream.MORE, response);
        this.emit(change_stream_1.ChangeStream.RESPONSE);
        return response;
      }
    };
    exports2.ChangeStreamCursor = ChangeStreamCursor;
  }
});

// node_modules/mongodb/lib/operations/list_collections.js
var require_list_collections = __commonJS({
  "node_modules/mongodb/lib/operations/list_collections.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ListCollectionsOperation = void 0;
    var responses_1 = require_responses();
    var utils_1 = require_utils();
    var command_1 = require_command();
    var operation_1 = require_operation();
    var ListCollectionsOperation = class extends command_1.CommandOperation {
      constructor(db, filter, options) {
        super(db, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.CursorResponse;
        this.options = { ...options };
        delete this.options.writeConcern;
        this.db = db;
        this.filter = filter;
        this.nameOnly = !!this.options.nameOnly;
        this.authorizedCollections = !!this.options.authorizedCollections;
        if (typeof this.options.batchSize === "number") {
          this.batchSize = this.options.batchSize;
        }
        this.SERVER_COMMAND_RESPONSE_TYPE = this.explain ? responses_1.ExplainedCursorResponse : responses_1.CursorResponse;
      }
      get commandName() {
        return "listCollections";
      }
      buildCommandDocument(connection) {
        const command = {
          listCollections: 1,
          filter: this.filter,
          cursor: this.batchSize ? { batchSize: this.batchSize } : {},
          nameOnly: this.nameOnly,
          authorizedCollections: this.authorizedCollections
        };
        if ((0, utils_1.maxWireVersion)(connection) >= 9 && this.options.comment !== void 0) {
          command.comment = this.options.comment;
        }
        return command;
      }
      handleOk(response) {
        return response;
      }
    };
    exports2.ListCollectionsOperation = ListCollectionsOperation;
    (0, operation_1.defineAspects)(ListCollectionsOperation, [
      operation_1.Aspect.READ_OPERATION,
      operation_1.Aspect.RETRYABLE,
      operation_1.Aspect.CURSOR_CREATING,
      operation_1.Aspect.SUPPORTS_RAW_DATA
    ]);
  }
});

// node_modules/mongodb/lib/cursor/list_collections_cursor.js
var require_list_collections_cursor = __commonJS({
  "node_modules/mongodb/lib/cursor/list_collections_cursor.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ListCollectionsCursor = void 0;
    var execute_operation_1 = require_execute_operation();
    var list_collections_1 = require_list_collections();
    var abstract_cursor_1 = require_abstract_cursor();
    var ListCollectionsCursor = class _ListCollectionsCursor extends abstract_cursor_1.AbstractCursor {
      constructor(db, filter, options) {
        super(db.client, db.s.namespace, options);
        this.parent = db;
        this.filter = filter;
        this.options = options;
      }
      clone() {
        return new _ListCollectionsCursor(this.parent, this.filter, {
          ...this.options,
          ...this.cursorOptions
        });
      }
      /** @internal */
      async _initialize(session) {
        const operation = new list_collections_1.ListCollectionsOperation(this.parent, this.filter, {
          ...this.cursorOptions,
          ...this.options,
          session,
          signal: this.signal
        });
        const response = await (0, execute_operation_1.executeOperation)(this.parent.client, operation, this.timeoutContext);
        return { server: operation.server, session, response };
      }
    };
    exports2.ListCollectionsCursor = ListCollectionsCursor;
  }
});

// node_modules/mongodb/lib/cursor/run_command_cursor.js
var require_run_command_cursor = __commonJS({
  "node_modules/mongodb/lib/cursor/run_command_cursor.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RunCommandCursor = void 0;
    var error_1 = require_error();
    var execute_operation_1 = require_execute_operation();
    var get_more_1 = require_get_more();
    var run_command_1 = require_run_command();
    var utils_1 = require_utils();
    var abstract_cursor_1 = require_abstract_cursor();
    var RunCommandCursor = class extends abstract_cursor_1.AbstractCursor {
      /**
       * Controls the `getMore.comment` field
       * @param comment - any BSON value
       */
      setComment(comment) {
        this.getMoreOptions.comment = comment;
        return this;
      }
      /**
       * Controls the `getMore.maxTimeMS` field. Only valid when cursor is tailable await
       * @param maxTimeMS - the number of milliseconds to wait for new data
       */
      setMaxTimeMS(maxTimeMS) {
        this.getMoreOptions.maxAwaitTimeMS = maxTimeMS;
        return this;
      }
      /**
       * Controls the `getMore.batchSize` field
       * @param batchSize - the number documents to return in the `nextBatch`
       */
      setBatchSize(batchSize) {
        this.getMoreOptions.batchSize = batchSize;
        return this;
      }
      /** Unsupported for RunCommandCursor */
      clone() {
        throw new error_1.MongoAPIError("Clone not supported, create a new cursor with db.runCursorCommand");
      }
      /** Unsupported for RunCommandCursor: readConcern must be configured directly on command document */
      withReadConcern(_) {
        throw new error_1.MongoAPIError("RunCommandCursor does not support readConcern it must be attached to the command being run");
      }
      /** Unsupported for RunCommandCursor: various cursor flags must be configured directly on command document */
      addCursorFlag(_, __) {
        throw new error_1.MongoAPIError("RunCommandCursor does not support cursor flags, they must be attached to the command being run");
      }
      /**
       * Unsupported for RunCommandCursor: maxTimeMS must be configured directly on command document
       */
      maxTimeMS(_) {
        throw new error_1.MongoAPIError("maxTimeMS must be configured on the command document directly, to configure getMore.maxTimeMS use cursor.setMaxTimeMS()");
      }
      /** Unsupported for RunCommandCursor: batchSize must be configured directly on command document */
      batchSize(_) {
        throw new error_1.MongoAPIError("batchSize must be configured on the command document directly, to configure getMore.batchSize use cursor.setBatchSize()");
      }
      /** @internal */
      constructor(db, command, options = {}) {
        super(db.client, (0, utils_1.ns)(db.namespace), options);
        this.getMoreOptions = {};
        this.db = db;
        this.command = Object.freeze({ ...command });
      }
      /** @internal */
      async _initialize(session) {
        const operation = new run_command_1.RunCursorCommandOperation(this.db.s.namespace, this.command, {
          ...this.cursorOptions,
          session,
          readPreference: this.cursorOptions.readPreference
        });
        const response = await (0, execute_operation_1.executeOperation)(this.client, operation, this.timeoutContext);
        return {
          server: operation.server,
          session,
          response
        };
      }
      /** @internal */
      async getMore() {
        if (!this.session) {
          throw new error_1.MongoRuntimeError("Unexpected null session. A cursor creating command should have set this");
        }
        const getMoreOperation = new get_more_1.GetMoreOperation(this.namespace, this.id, this.server, {
          ...this.cursorOptions,
          session: this.session,
          ...this.getMoreOptions
        });
        return await (0, execute_operation_1.executeOperation)(this.client, getMoreOperation, this.timeoutContext);
      }
    };
    exports2.RunCommandCursor = RunCommandCursor;
  }
});

// node_modules/mongodb/lib/operations/create_collection.js
var require_create_collection = __commonJS({
  "node_modules/mongodb/lib/operations/create_collection.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CreateCollectionOperation = void 0;
    exports2.createCollections = createCollections;
    var constants_1 = require_constants();
    var responses_1 = require_responses();
    var collection_1 = require_collection();
    var error_1 = require_error();
    var timeout_1 = require_timeout();
    var utils_1 = require_utils();
    var command_1 = require_command();
    var execute_operation_1 = require_execute_operation();
    var indexes_1 = require_indexes();
    var operation_1 = require_operation();
    var ILLEGAL_COMMAND_FIELDS = /* @__PURE__ */ new Set([
      "w",
      "wtimeout",
      "timeoutMS",
      "j",
      "fsync",
      "pkFactory",
      "raw",
      "readPreference",
      "session",
      "readConcern",
      "writeConcern",
      "raw",
      "fieldsAsRaw",
      "useBigInt64",
      "promoteLongs",
      "promoteValues",
      "promoteBuffers",
      "bsonRegExp",
      "serializeFunctions",
      "ignoreUndefined",
      "enableUtf8Validation"
    ]);
    var INVALID_QE_VERSION = "Driver support of Queryable Encryption is incompatible with server. Upgrade server to use Queryable Encryption.";
    var CreateCollectionOperation = class extends command_1.CommandOperation {
      constructor(db, name, options = {}) {
        super(db, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.options = options;
        this.db = db;
        this.name = name;
      }
      get commandName() {
        return "create";
      }
      buildCommandDocument(_connection, _session) {
        const isOptionValid = ([k, v]) => v != null && typeof v !== "function" && !ILLEGAL_COMMAND_FIELDS.has(k);
        return {
          create: this.name,
          ...Object.fromEntries(Object.entries(this.options).filter(isOptionValid))
        };
      }
      handleOk(_response) {
        return new collection_1.Collection(this.db, this.name, this.options);
      }
    };
    exports2.CreateCollectionOperation = CreateCollectionOperation;
    async function createCollections(db, name, options) {
      const timeoutContext = timeout_1.TimeoutContext.create({
        session: options.session,
        serverSelectionTimeoutMS: db.client.s.options.serverSelectionTimeoutMS,
        waitQueueTimeoutMS: db.client.s.options.waitQueueTimeoutMS,
        timeoutMS: options.timeoutMS
      });
      const encryptedFields = options.encryptedFields ?? db.client.s.options.autoEncryption?.encryptedFieldsMap?.[`${db.databaseName}.${name}`];
      if (encryptedFields) {
        class CreateSupportingFLEv2CollectionOperation extends CreateCollectionOperation {
          buildCommandDocument(connection, session) {
            if (!connection.description.loadBalanced && (0, utils_1.maxWireVersion)(connection) < constants_1.MIN_SUPPORTED_QE_WIRE_VERSION) {
              throw new error_1.MongoCompatibilityError(`${INVALID_QE_VERSION} The minimum server version required is ${constants_1.MIN_SUPPORTED_QE_SERVER_VERSION}`);
            }
            return super.buildCommandDocument(connection, session);
          }
        }
        const escCollection = encryptedFields.escCollection ?? `enxcol_.${name}.esc`;
        const ecocCollection = encryptedFields.ecocCollection ?? `enxcol_.${name}.ecoc`;
        for (const collectionName of [escCollection, ecocCollection]) {
          const createOp = new CreateSupportingFLEv2CollectionOperation(db, collectionName, {
            clusteredIndex: {
              key: { _id: 1 },
              unique: true
            },
            session: options.session
          });
          await (0, execute_operation_1.executeOperation)(db.client, createOp, timeoutContext);
        }
        if (!options.encryptedFields) {
          options = { ...options, encryptedFields };
        }
      }
      const coll = await (0, execute_operation_1.executeOperation)(db.client, new CreateCollectionOperation(db, name, options), timeoutContext);
      if (encryptedFields) {
        const createIndexOp = indexes_1.CreateIndexesOperation.fromIndexSpecification(db, name, { __safeContent__: 1 }, { session: options.session });
        await (0, execute_operation_1.executeOperation)(db.client, createIndexOp, timeoutContext);
      }
      return coll;
    }
    (0, operation_1.defineAspects)(CreateCollectionOperation, [operation_1.Aspect.WRITE_OPERATION]);
  }
});

// node_modules/mongodb/lib/operations/drop.js
var require_drop2 = __commonJS({
  "node_modules/mongodb/lib/operations/drop.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DropDatabaseOperation = exports2.DropCollectionOperation = void 0;
    exports2.dropCollections = dropCollections;
    var __1 = require_lib3();
    var responses_1 = require_responses();
    var abstract_cursor_1 = require_abstract_cursor();
    var error_1 = require_error();
    var timeout_1 = require_timeout();
    var command_1 = require_command();
    var execute_operation_1 = require_execute_operation();
    var operation_1 = require_operation();
    var DropCollectionOperation = class extends command_1.CommandOperation {
      constructor(db, name, options = {}) {
        super(db, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.options = options;
        this.name = name;
      }
      get commandName() {
        return "drop";
      }
      buildCommandDocument(_connection, _session) {
        return { drop: this.name };
      }
      handleOk(_response) {
        return true;
      }
      handleError(error51) {
        if (!(error51 instanceof __1.MongoServerError))
          throw error51;
        if (Number(error51.code) !== error_1.MONGODB_ERROR_CODES.NamespaceNotFound)
          throw error51;
        return false;
      }
    };
    exports2.DropCollectionOperation = DropCollectionOperation;
    async function dropCollections(db, name, options) {
      const timeoutContext = timeout_1.TimeoutContext.create({
        session: options.session,
        serverSelectionTimeoutMS: db.client.s.options.serverSelectionTimeoutMS,
        waitQueueTimeoutMS: db.client.s.options.waitQueueTimeoutMS,
        timeoutMS: options.timeoutMS
      });
      const encryptedFieldsMap = db.client.s.options.autoEncryption?.encryptedFieldsMap;
      let encryptedFields = options.encryptedFields ?? encryptedFieldsMap?.[`${db.databaseName}.${name}`];
      if (!encryptedFields && encryptedFieldsMap) {
        const listCollectionsResult = await db.listCollections({ name }, {
          nameOnly: false,
          session: options.session,
          timeoutContext: new abstract_cursor_1.CursorTimeoutContext(timeoutContext, /* @__PURE__ */ Symbol())
        }).toArray();
        encryptedFields = listCollectionsResult?.[0]?.options?.encryptedFields;
      }
      if (encryptedFields) {
        const escCollection = encryptedFields.escCollection || `enxcol_.${name}.esc`;
        const ecocCollection = encryptedFields.ecocCollection || `enxcol_.${name}.ecoc`;
        for (const collectionName of [escCollection, ecocCollection]) {
          const dropOp = new DropCollectionOperation(db, collectionName, options);
          await (0, execute_operation_1.executeOperation)(db.client, dropOp, timeoutContext);
        }
      }
      return await (0, execute_operation_1.executeOperation)(db.client, new DropCollectionOperation(db, name, options), timeoutContext);
    }
    var DropDatabaseOperation = class extends command_1.CommandOperation {
      constructor(db, options) {
        super(db, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.options = options;
      }
      get commandName() {
        return "dropDatabase";
      }
      buildCommandDocument(_connection, _session) {
        return { dropDatabase: 1 };
      }
      handleOk(_response) {
        return true;
      }
    };
    exports2.DropDatabaseOperation = DropDatabaseOperation;
    (0, operation_1.defineAspects)(DropCollectionOperation, [operation_1.Aspect.WRITE_OPERATION]);
    (0, operation_1.defineAspects)(DropDatabaseOperation, [operation_1.Aspect.WRITE_OPERATION]);
  }
});

// node_modules/mongodb/lib/operations/profiling_level.js
var require_profiling_level = __commonJS({
  "node_modules/mongodb/lib/operations/profiling_level.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ProfilingLevelOperation = void 0;
    var bson_1 = require_bson2();
    var responses_1 = require_responses();
    var error_1 = require_error();
    var command_1 = require_command();
    var ProfilingLevelResponse = class extends responses_1.MongoDBResponse {
      get was() {
        return this.get("was", bson_1.BSONType.int, true);
      }
    };
    var ProfilingLevelOperation = class extends command_1.CommandOperation {
      constructor(db, options) {
        super(db, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = ProfilingLevelResponse;
        this.options = options;
      }
      get commandName() {
        return "profile";
      }
      buildCommandDocument(_connection) {
        return { profile: -1 };
      }
      handleOk(response) {
        if (response.ok === 1) {
          const was = response.was;
          if (was === 0)
            return "off";
          if (was === 1)
            return "slow_only";
          if (was === 2)
            return "all";
          throw new error_1.MongoUnexpectedServerResponseError(`Illegal profiling level value ${was}`);
        } else {
          throw new error_1.MongoUnexpectedServerResponseError("Error with profile command");
        }
      }
    };
    exports2.ProfilingLevelOperation = ProfilingLevelOperation;
  }
});

// node_modules/mongodb/lib/operations/set_profiling_level.js
var require_set_profiling_level = __commonJS({
  "node_modules/mongodb/lib/operations/set_profiling_level.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SetProfilingLevelOperation = exports2.ProfilingLevel = void 0;
    var responses_1 = require_responses();
    var error_1 = require_error();
    var utils_1 = require_utils();
    var command_1 = require_command();
    var levelValues = /* @__PURE__ */ new Set(["off", "slow_only", "all"]);
    exports2.ProfilingLevel = Object.freeze({
      off: "off",
      slowOnly: "slow_only",
      all: "all"
    });
    var SetProfilingLevelOperation = class extends command_1.CommandOperation {
      constructor(db, level, options) {
        super(db, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.options = options;
        switch (level) {
          case exports2.ProfilingLevel.off:
            this.profile = 0;
            break;
          case exports2.ProfilingLevel.slowOnly:
            this.profile = 1;
            break;
          case exports2.ProfilingLevel.all:
            this.profile = 2;
            break;
          default:
            this.profile = 0;
            break;
        }
        this.level = level;
      }
      get commandName() {
        return "profile";
      }
      buildCommandDocument(_connection) {
        const level = this.level;
        if (!levelValues.has(level)) {
          throw new error_1.MongoInvalidArgumentError(`Profiling level must be one of "${(0, utils_1.enumToString)(exports2.ProfilingLevel)}"`);
        }
        return { profile: this.profile };
      }
      handleOk(_response) {
        return this.level;
      }
    };
    exports2.SetProfilingLevelOperation = SetProfilingLevelOperation;
  }
});

// node_modules/mongodb/lib/operations/stats.js
var require_stats = __commonJS({
  "node_modules/mongodb/lib/operations/stats.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DbStatsOperation = void 0;
    var responses_1 = require_responses();
    var command_1 = require_command();
    var operation_1 = require_operation();
    var DbStatsOperation = class extends command_1.CommandOperation {
      constructor(db, options) {
        super(db, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.options = options;
      }
      get commandName() {
        return "dbStats";
      }
      buildCommandDocument(_connection) {
        const command = { dbStats: true };
        if (this.options.scale != null) {
          command.scale = this.options.scale;
        }
        return command;
      }
    };
    exports2.DbStatsOperation = DbStatsOperation;
    (0, operation_1.defineAspects)(DbStatsOperation, [operation_1.Aspect.READ_OPERATION]);
  }
});

// node_modules/mongodb/lib/db.js
var require_db = __commonJS({
  "node_modules/mongodb/lib/db.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Db = void 0;
    var admin_1 = require_admin();
    var bson_1 = require_bson2();
    var change_stream_1 = require_change_stream();
    var collection_1 = require_collection();
    var CONSTANTS = require_constants2();
    var aggregation_cursor_1 = require_aggregation_cursor();
    var list_collections_cursor_1 = require_list_collections_cursor();
    var run_command_cursor_1 = require_run_command_cursor();
    var error_1 = require_error();
    var create_collection_1 = require_create_collection();
    var drop_1 = require_drop2();
    var execute_operation_1 = require_execute_operation();
    var indexes_1 = require_indexes();
    var profiling_level_1 = require_profiling_level();
    var remove_user_1 = require_remove_user();
    var rename_1 = require_rename();
    var run_command_1 = require_run_command();
    var set_profiling_level_1 = require_set_profiling_level();
    var stats_1 = require_stats();
    var read_concern_1 = require_read_concern();
    var read_preference_1 = require_read_preference();
    var utils_1 = require_utils();
    var write_concern_1 = require_write_concern();
    var DB_OPTIONS_ALLOW_LIST = [
      "writeConcern",
      "readPreference",
      "readPreferenceTags",
      "native_parser",
      "forceServerObjectId",
      "pkFactory",
      "serializeFunctions",
      "raw",
      "authSource",
      "ignoreUndefined",
      "readConcern",
      "retryMiliSeconds",
      "numberOfRetries",
      "useBigInt64",
      "promoteBuffers",
      "promoteLongs",
      "bsonRegExp",
      "enableUtf8Validation",
      "promoteValues",
      "compression",
      "retryWrites",
      "timeoutMS"
    ];
    var Db = class {
      static {
        this.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION;
      }
      static {
        this.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION;
      }
      static {
        this.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION;
      }
      static {
        this.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION;
      }
      static {
        this.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION;
      }
      static {
        this.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION;
      }
      /**
       * Creates a new Db instance.
       *
       * Db name cannot contain a dot, the server may apply more restrictions when an operation is run.
       *
       * @param client - The MongoClient for the database.
       * @param databaseName - The name of the database this instance represents.
       * @param options - Optional settings for Db construction.
       */
      constructor(client, databaseName, options) {
        options = options ?? {};
        options = (0, utils_1.filterOptions)(options, DB_OPTIONS_ALLOW_LIST);
        if (typeof databaseName === "string" && databaseName.includes(".")) {
          throw new error_1.MongoInvalidArgumentError(`Database names cannot contain the character '.'`);
        }
        this.s = {
          // Options
          options,
          // Unpack read preference
          readPreference: read_preference_1.ReadPreference.fromOptions(options),
          // Merge bson options
          bsonOptions: (0, bson_1.resolveBSONOptions)(options, client),
          // Set up the primary key factory or fallback to ObjectId
          pkFactory: options?.pkFactory ?? utils_1.DEFAULT_PK_FACTORY,
          // ReadConcern
          readConcern: read_concern_1.ReadConcern.fromOptions(options),
          writeConcern: write_concern_1.WriteConcern.fromOptions(options),
          // Namespace
          namespace: new utils_1.MongoDBNamespace(databaseName)
        };
        this.client = client;
      }
      get databaseName() {
        return this.s.namespace.db;
      }
      // Options
      get options() {
        return this.s.options;
      }
      /**
       * Check if a secondary can be used (because the read preference is *not* set to primary)
       */
      get secondaryOk() {
        return this.s.readPreference?.preference !== "primary" || false;
      }
      get readConcern() {
        return this.s.readConcern;
      }
      /**
       * The current readPreference of the Db. If not explicitly defined for
       * this Db, will be inherited from the parent MongoClient
       */
      get readPreference() {
        if (this.s.readPreference == null) {
          return this.client.readPreference;
        }
        return this.s.readPreference;
      }
      get bsonOptions() {
        return this.s.bsonOptions;
      }
      // get the write Concern
      get writeConcern() {
        return this.s.writeConcern;
      }
      get namespace() {
        return this.s.namespace.toString();
      }
      get timeoutMS() {
        return this.s.options?.timeoutMS;
      }
      /**
       * Create a new collection on a server with the specified options. Use this to create capped collections.
       * More information about command options available at https://www.mongodb.com/docs/manual/reference/command/create/
       *
       * Collection namespace validation is performed server-side.
       *
       * @param name - The name of the collection to create
       * @param options - Optional settings for the command
       */
      async createCollection(name, options) {
        options = (0, utils_1.resolveOptions)(this, options);
        return await (0, create_collection_1.createCollections)(this, name, options);
      }
      /**
       * Execute a command
       *
       * @remarks
       * This command does not inherit options from the MongoClient.
       *
       * The driver will ensure the following fields are attached to the command sent to the server:
       * - `lsid` - sourced from an implicit session or options.session
       * - `$readPreference` - defaults to primary or can be configured by options.readPreference
       * - `$db` - sourced from the name of this database
       *
       * If the client has a serverApi setting:
       * - `apiVersion`
       * - `apiStrict`
       * - `apiDeprecationErrors`
       *
       * When in a transaction:
       * - `readConcern` - sourced from readConcern set on the TransactionOptions
       * - `writeConcern` - sourced from writeConcern set on the TransactionOptions
       *
       * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value.
       *
       * @param command - The command to run
       * @param options - Optional settings for the command
       */
      async command(command, options) {
        return await (0, execute_operation_1.executeOperation)(this.client, new run_command_1.RunCommandOperation(this.s.namespace, command, (0, utils_1.resolveOptions)(void 0, {
          ...(0, bson_1.resolveBSONOptions)(options),
          timeoutMS: options?.timeoutMS ?? this.timeoutMS,
          session: options?.session,
          readPreference: options?.readPreference,
          signal: options?.signal
        })));
      }
      /**
       * Execute an aggregation framework pipeline against the database.
       *
       * @param pipeline - An array of aggregation stages to be executed
       * @param options - Optional settings for the command
       */
      aggregate(pipeline2 = [], options) {
        return new aggregation_cursor_1.AggregationCursor(this.client, this.s.namespace, pipeline2, (0, utils_1.resolveOptions)(this, options));
      }
      /** Return the Admin db instance */
      admin() {
        return new admin_1.Admin(this);
      }
      /**
       * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly.
       *
       * Collection namespace validation is performed server-side.
       *
       * @param name - the collection name we wish to access.
       * @returns return the new Collection instance
       */
      collection(name, options = {}) {
        if (typeof options === "function") {
          throw new error_1.MongoInvalidArgumentError("The callback form of this helper has been removed.");
        }
        return new collection_1.Collection(this, name, (0, utils_1.resolveOptions)(this, options));
      }
      /**
       * Get all the db statistics.
       *
       * @param options - Optional settings for the command
       */
      async stats(options) {
        return await (0, execute_operation_1.executeOperation)(this.client, new stats_1.DbStatsOperation(this, (0, utils_1.resolveOptions)(this, options)));
      }
      listCollections(filter = {}, options = {}) {
        return new list_collections_cursor_1.ListCollectionsCursor(this, filter, (0, utils_1.resolveOptions)(this, options));
      }
      /**
       * Rename a collection.
       *
       * @remarks
       * This operation does not inherit options from the MongoClient.
       *
       * @param fromCollection - Name of current collection to rename
       * @param toCollection - New name of of the collection
       * @param options - Optional settings for the command
       */
      async renameCollection(fromCollection, toCollection, options) {
        return await (0, execute_operation_1.executeOperation)(this.client, new rename_1.RenameOperation(this.collection(fromCollection), toCollection, (0, utils_1.resolveOptions)(void 0, {
          ...options,
          readPreference: read_preference_1.ReadPreference.primary
        })));
      }
      /**
       * Drop a collection from the database, removing it permanently. New accesses will create a new collection.
       *
       * @param name - Name of collection to drop
       * @param options - Optional settings for the command
       */
      async dropCollection(name, options) {
        options = (0, utils_1.resolveOptions)(this, options);
        return await (0, drop_1.dropCollections)(this, name, options);
      }
      /**
       * Drop a database, removing it permanently from the server.
       *
       * @param options - Optional settings for the command
       */
      async dropDatabase(options) {
        return await (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropDatabaseOperation(this, (0, utils_1.resolveOptions)(this, options)));
      }
      /**
       * Fetch all collections for the current db.
       *
       * @param options - Optional settings for the command
       */
      async collections(options) {
        options = (0, utils_1.resolveOptions)(this, options);
        const collections = await this.listCollections({}, { ...options, nameOnly: true }).toArray();
        return collections.filter(
          // Filter collections removing any illegal ones
          ({ name }) => !name.includes("$")
        ).map(({ name }) => new collection_1.Collection(this, name, this.s.options));
      }
      /**
       * Creates an index on the db and collection.
       *
       * @param name - Name of the collection to create the index on.
       * @param indexSpec - Specify the field to index, or an index specification
       * @param options - Optional settings for the command
       */
      async createIndex(name, indexSpec, options) {
        const indexes = await (0, execute_operation_1.executeOperation)(this.client, indexes_1.CreateIndexesOperation.fromIndexSpecification(this, name, indexSpec, options));
        return indexes[0];
      }
      /**
       * Remove a user from a database
       *
       * @param username - The username to remove
       * @param options - Optional settings for the command
       */
      async removeUser(username, options) {
        return await (0, execute_operation_1.executeOperation)(this.client, new remove_user_1.RemoveUserOperation(this, username, (0, utils_1.resolveOptions)(this, options)));
      }
      /**
       * Set the current profiling level of MongoDB
       *
       * @param level - The new profiling level (off, slow_only, all).
       * @param options - Optional settings for the command
       */
      async setProfilingLevel(level, options) {
        return await (0, execute_operation_1.executeOperation)(this.client, new set_profiling_level_1.SetProfilingLevelOperation(this, level, (0, utils_1.resolveOptions)(this, options)));
      }
      /**
       * Retrieve the current profiling Level for MongoDB
       *
       * @param options - Optional settings for the command
       */
      async profilingLevel(options) {
        return await (0, execute_operation_1.executeOperation)(this.client, new profiling_level_1.ProfilingLevelOperation(this, (0, utils_1.resolveOptions)(this, options)));
      }
      async indexInformation(name, options) {
        return await this.collection(name).indexInformation((0, utils_1.resolveOptions)(this, options));
      }
      /**
       * Create a new Change Stream, watching for new changes (insertions, updates,
       * replacements, deletions, and invalidations) in this database. Will ignore all
       * changes to system collections.
       *
       * @remarks
       * watch() accepts two generic arguments for distinct use cases:
       * - The first is to provide the schema that may be defined for all the collections within this database
       * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument
       *
       * @remarks
       * When `timeoutMS` is configured for a change stream, it will have different behaviour depending
       * on whether the change stream is in iterator mode or emitter mode. In both cases, a change
       * stream will time out if it does not receive a change event within `timeoutMS` of the last change
       * event.
       *
       * Note that if a change stream is consistently timing out when watching a collection, database or
       * client that is being changed, then this may be due to the server timing out before it can finish
       * processing the existing oplog. To address this, restart the change stream with a higher
       * `timeoutMS`.
       *
       * If the change stream times out the initial aggregate operation to establish the change stream on
       * the server, then the client will close the change stream. If the getMore calls to the server
       * time out, then the change stream will be left open, but will throw a MongoOperationTimeoutError
       * when in iterator mode and emit an error event that returns a MongoOperationTimeoutError in
       * emitter mode.
       *
       * To determine whether or not the change stream is still open following a timeout, check the
       * {@link ChangeStream.closed} getter.
       *
       * @example
       * In iterator mode, if a next() call throws a timeout error, it will attempt to resume the change stream.
       * The next call can just be retried after this succeeds.
       * ```ts
       * const changeStream = collection.watch([], { timeoutMS: 100 });
       * try {
       *     await changeStream.next();
       * } catch (e) {
       *     if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
       *       await changeStream.next();
       *     }
       *     throw e;
       * }
       * ```
       *
       * @example
       * In emitter mode, if the change stream goes `timeoutMS` without emitting a change event, it will
       * emit an error event that returns a MongoOperationTimeoutError, but will not close the change
       * stream unless the resume attempt fails. There is no need to re-establish change listeners as
       * this will automatically continue emitting change events once the resume attempt completes.
       *
       * ```ts
       * const changeStream = collection.watch([], { timeoutMS: 100 });
       * changeStream.on('change', console.log);
       * changeStream.on('error', e => {
       *     if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
       *         // do nothing
       *     } else {
       *         changeStream.close();
       *     }
       * });
       * ```
       * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
       * @param options - Optional settings for the command
       * @typeParam TSchema - Type of the data being detected by the change stream
       * @typeParam TChange - Type of the whole change stream document emitted
       */
      watch(pipeline2 = [], options = {}) {
        if (!Array.isArray(pipeline2)) {
          options = pipeline2;
          pipeline2 = [];
        }
        return new change_stream_1.ChangeStream(this, pipeline2, (0, utils_1.resolveOptions)(this, options));
      }
      /**
       * A low level cursor API providing basic driver functionality:
       * - ClientSession management
       * - ReadPreference for server selection
       * - Running getMores automatically when a local batch is exhausted
       *
       * @param command - The command that will start a cursor on the server.
       * @param options - Configurations for running the command, bson options will apply to getMores
       */
      runCursorCommand(command, options) {
        return new run_command_cursor_1.RunCommandCursor(this, command, options);
      }
    };
    exports2.Db = Db;
  }
});

// node_modules/extend/index.js
var require_extend = __commonJS({
  "node_modules/extend/index.js"(exports2, module2) {
    "use strict";
    var hasOwn = Object.prototype.hasOwnProperty;
    var toStr = Object.prototype.toString;
    var defineProperty = Object.defineProperty;
    var gOPD = Object.getOwnPropertyDescriptor;
    var isArray = function isArray2(arr) {
      if (typeof Array.isArray === "function") {
        return Array.isArray(arr);
      }
      return toStr.call(arr) === "[object Array]";
    };
    var isPlainObject3 = function isPlainObject4(obj) {
      if (!obj || toStr.call(obj) !== "[object Object]") {
        return false;
      }
      var hasOwnConstructor = hasOwn.call(obj, "constructor");
      var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, "isPrototypeOf");
      if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
        return false;
      }
      var key;
      for (key in obj) {
      }
      return typeof key === "undefined" || hasOwn.call(obj, key);
    };
    var setProperty = function setProperty2(target, options) {
      if (defineProperty && options.name === "__proto__") {
        defineProperty(target, options.name, {
          enumerable: true,
          configurable: true,
          value: options.newValue,
          writable: true
        });
      } else {
        target[options.name] = options.newValue;
      }
    };
    var getProperty = function getProperty2(obj, name) {
      if (name === "__proto__") {
        if (!hasOwn.call(obj, name)) {
          return void 0;
        } else if (gOPD) {
          return gOPD(obj, name).value;
        }
      }
      return obj[name];
    };
    module2.exports = function extend2() {
      var options, name, src, copy, copyIsArray, clone3;
      var target = arguments[0];
      var i2 = 1;
      var length = arguments.length;
      var deep = false;
      if (typeof target === "boolean") {
        deep = target;
        target = arguments[1] || {};
        i2 = 2;
      }
      if (target == null || typeof target !== "object" && typeof target !== "function") {
        target = {};
      }
      for (; i2 < length; ++i2) {
        options = arguments[i2];
        if (options != null) {
          for (name in options) {
            src = getProperty(target, name);
            copy = getProperty(options, name);
            if (target !== copy) {
              if (deep && copy && (isPlainObject3(copy) || (copyIsArray = isArray(copy)))) {
                if (copyIsArray) {
                  copyIsArray = false;
                  clone3 = src && isArray(src) ? src : [];
                } else {
                  clone3 = src && isPlainObject3(src) ? src : {};
                }
                setProperty(target, { name, newValue: extend2(deep, clone3, copy) });
              } else if (typeof copy !== "undefined") {
                setProperty(target, { name, newValue: copy });
              }
            }
          }
        }
      }
      return target;
    };
  }
});

// node_modules/gaxios/package.json
var require_package = __commonJS({
  "node_modules/gaxios/package.json"(exports2, module2) {
    module2.exports = {
      name: "gaxios",
      version: "7.3.0",
      description: "A simple common HTTP client specifically for Google APIs and services.",
      main: "build/cjs/src/index.js",
      types: "build/cjs/src/index.d.ts",
      files: [
        "build/"
      ],
      exports: {
        ".": {
          import: {
            types: "./build/esm/src/index.d.ts",
            default: "./build/esm/src/index.js"
          },
          require: {
            types: "./build/cjs/src/index.d.ts",
            default: "./build/cjs/src/index.js"
          }
        }
      },
      scripts: {
        lint: "gts check --no-inline-config",
        test: "c8 mocha build/esm/test",
        "presystem-test": "npm run compile",
        "system-test": "mocha build/esm/system-test --timeout 80000",
        compile: "tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",
        fix: "gts fix",
        prepare: "npm run compile",
        pretest: "npm run compile",
        webpack: "webpack",
        "prebrowser-test": "npm run compile",
        "browser-test": "node build/browser-test/browser-test-runner.js",
        docs: "jsdoc -c .jsdoc.js",
        "samples-test": "cd samples/ && npm link ../ && npm test && cd ../",
        prelint: "cd samples; npm link ../; npm install",
        clean: "gts clean"
      },
      repository: {
        type: "git",
        directory: "core/packages/gaxios",
        url: "https://github.com/googleapis/google-cloud-node.git"
      },
      keywords: [
        "google"
      ],
      engines: {
        node: ">=18"
      },
      author: "Google, LLC",
      license: "Apache-2.0",
      devDependencies: {
        "@babel/plugin-proposal-private-methods": "^7.18.6",
        "@types/cors": "^2.8.6",
        "@types/express": "^5.0.0",
        "@types/extend": "^3.0.1",
        "@types/mocha": "^10.0.10",
        "@types/multiparty": "4.2.1",
        "@types/mv": "^2.1.0",
        "@types/ncp": "^2.0.8",
        "@types/node": "^24.0.0",
        "@types/sinon": "^21.0.0",
        "@types/tmp": "^0.2.6",
        assert: "^2.0.0",
        browserify: "^17.0.0",
        c8: "^10.1.3",
        cors: "^2.8.5",
        express: "^5.0.0",
        gts: "^6.0.2",
        "is-docker": "^3.0.0",
        jsdoc: "^4.0.4",
        "jsdoc-fresh": "^5.0.0",
        "jsdoc-region-tag": "^4.0.0",
        karma: "^6.0.0",
        "karma-chrome-launcher": "^3.0.0",
        "karma-coverage": "^2.0.0",
        "karma-firefox-launcher": "^2.0.0",
        "karma-mocha": "^2.0.0",
        "karma-remap-coverage": "^0.1.5",
        "karma-sourcemap-loader": "^0.4.0",
        "karma-webpack": "^5.0.1",
        mocha: "^11.1.0",
        multiparty: "^4.2.1",
        mv: "^2.1.1",
        ncp: "^2.0.0",
        nock: "14.0.5",
        "null-loader": "^4.0.1",
        "pack-n-play": "^4.0.0",
        puppeteer: "^24.0.0",
        sinon: "21.0.3",
        "stream-browserify": "^3.0.0",
        tmp: "0.2.6",
        "ts-loader": "^9.5.2",
        typescript: "5.8.3",
        "undici-types": "^7.24.1",
        webpack: "^5.97.1",
        "webpack-cli": "^6.0.1"
      },
      dependencies: {
        extend: "^3.0.2",
        "https-proxy-agent": "^7.0.1",
        "node-fetch": "^3.3.2"
      },
      homepage: "https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"
    };
  }
});

// node_modules/gaxios/build/cjs/src/util.cjs
var require_util = __commonJS({
  "node_modules/gaxios/build/cjs/src/util.cjs"(exports2, module2) {
    "use strict";
    var pkg = require_package();
    module2.exports = { pkg };
  }
});

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// node_modules/gaxios/build/cjs/src/gaxios.js
var require_gaxios = __commonJS({
  "node_modules/gaxios/build/cjs/src/gaxios.js"(exports2) {
    "use strict";
    var __importDefault = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    var _a3;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Gaxios = void 0;
    var extend_1 = __importDefault(require_extend());
    var https_1 = require("https");
    var common_js_1 = require_common3();
    var retry_js_1 = require_retry();
    var stream_1 = require("stream");
    var interceptor_js_1 = require_interceptor();
    var randomUUID = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
    var HTTP_STATUS_NO_CONTENT = 204;
    var Gaxios = class {
      agentCache = /* @__PURE__ */ new Map();
      /**
       * Default HTTP options that will be used for every HTTP request.
       */
      defaults;
      /**
       * Interceptors
       */
      interceptors;
      /**
       * The Gaxios class is responsible for making HTTP requests.
       * @param defaults The default set of options to be used for this instance.
       */
      constructor(defaults) {
        this.defaults = defaults || {};
        this.interceptors = {
          request: new interceptor_js_1.GaxiosInterceptorManager(),
          response: new interceptor_js_1.GaxiosInterceptorManager()
        };
      }
      /**
       * A {@link fetch `fetch`} compliant API for {@link Gaxios}.
       *
       * @remarks
       *
       * This is useful as a drop-in replacement for `fetch` API usage.
       *
       * @example
       *
       * ```ts
       * const gaxios = new Gaxios();
       * const myFetch: typeof fetch = (...args) => gaxios.fetch(...args);
       * await myFetch('https://example.com');
       * ```
       *
       * @param args `fetch` API or `Gaxios#request` parameters
       * @returns the {@link Response} with Gaxios-added properties
       */
      fetch(...args) {
        const input = args[0];
        const init = args[1];
        let url2 = void 0;
        const headers = new Headers();
        if (typeof input === "string") {
          url2 = new URL(input);
        } else if (input instanceof URL) {
          url2 = input;
        } else if (input && input.url) {
          url2 = new URL(input.url);
        }
        if (input && typeof input === "object" && "headers" in input) {
          _a3.mergeHeaders(headers, input.headers);
        }
        if (init) {
          _a3.mergeHeaders(headers, new Headers(init.headers));
        }
        if (typeof input === "object" && !(input instanceof URL)) {
          return this.request({ ...init, ...input, headers, url: url2 });
        } else {
          return this.request({ ...init, headers, url: url2 });
        }
      }
      /**
       * Perform an HTTP request with the given options.
       * @param opts Set of HTTP options that will be used for this HTTP request.
       */
      async request(opts = {}) {
        let prepared = await this.#prepareRequest(opts);
        prepared = await this.#applyRequestInterceptors(prepared);
        return this.#applyResponseInterceptors(this._request(prepared));
      }
      async _defaultAdapter(config2) {
        const fetchImpl = config2.fetchImplementation || this.defaults.fetchImplementation || await _a3.#getFetch();
        const preparedOpts = { ...config2 };
        delete preparedOpts.data;
        const res = await fetchImpl(config2.url, preparedOpts);
        const data = await this.getResponseData(config2, res);
        if (!Object.getOwnPropertyDescriptor(res, "data")?.configurable) {
          Object.defineProperties(res, {
            data: {
              configurable: true,
              writable: true,
              enumerable: true,
              value: data
            }
          });
        }
        return Object.assign(res, { config: config2, data });
      }
      /**
       * Internal, retryable version of the `request` method.
       * @param opts Set of HTTP options that will be used for this HTTP request.
       */
      async _request(opts) {
        try {
          let translatedResponse;
          if (opts.adapter) {
            translatedResponse = await opts.adapter(opts, this._defaultAdapter.bind(this));
          } else {
            translatedResponse = await this._defaultAdapter(opts);
          }
          if (!opts.validateStatus(translatedResponse.status)) {
            if (opts.responseType === "stream") {
              const response = [];
              for await (const chunk of translatedResponse.data) {
                response.push(chunk);
              }
              translatedResponse.data = Buffer.concat(response.map((c) => typeof c === "string" ? Buffer.from(c) : c)).toString("utf8");
            }
            const errorInfo = common_js_1.GaxiosError.extractAPIErrorFromResponse(translatedResponse, `Request failed with status code ${translatedResponse.status}`);
            throw new common_js_1.GaxiosError(errorInfo?.message, opts, translatedResponse, errorInfo);
          }
          return translatedResponse;
        } catch (e2) {
          let err;
          if (e2 instanceof common_js_1.GaxiosError) {
            err = e2;
          } else if (e2 instanceof Error) {
            err = new common_js_1.GaxiosError(e2.message, opts, void 0, e2);
          } else {
            err = new common_js_1.GaxiosError("Unexpected Gaxios Error", opts, void 0, e2);
          }
          const { shouldRetry, config: config2 } = await (0, retry_js_1.getRetryConfig)(err);
          if (shouldRetry && config2) {
            err.config.retryConfig.currentRetryAttempt = config2.retryConfig.currentRetryAttempt;
            opts.retryConfig = err.config?.retryConfig;
            this.#appendTimeoutToSignal(opts);
            return this._request(opts);
          }
          if (opts.errorRedactor) {
            opts.errorRedactor(err);
          }
          throw err;
        }
      }
      async getResponseData(opts, res) {
        if (res.status === HTTP_STATUS_NO_CONTENT) {
          return "";
        }
        if (opts.maxContentLength && res.headers.has("content-length") && opts.maxContentLength < Number.parseInt(res.headers?.get("content-length") || "")) {
          throw new common_js_1.GaxiosError("Response's `Content-Length` is over the limit.", opts, Object.assign(res, { config: opts }));
        }
        switch (opts.responseType) {
          case "stream":
            return res.body;
          case "json": {
            const data = await res.text();
            try {
              return JSON.parse(data);
            } catch {
              return data;
            }
          }
          case "arraybuffer":
            return res.arrayBuffer();
          case "blob":
            return res.blob();
          case "text":
            return res.text();
          default:
            return this.getResponseDataFromContentType(res);
        }
      }
      #urlMayUseProxy(url2, noProxy = []) {
        const candidate = new URL(url2);
        const noProxyList = [...noProxy];
        const noProxyEnvList = (process.env.NO_PROXY ?? process.env.no_proxy)?.split(",") || [];
        for (const rule of noProxyEnvList) {
          noProxyList.push(rule.trim());
        }
        for (const rule of noProxyList) {
          if (rule instanceof RegExp) {
            if (rule.test(candidate.toString())) {
              return false;
            }
          } else if (rule instanceof URL) {
            if (rule.origin === candidate.origin) {
              return false;
            }
          } else if (rule.startsWith("*.") || rule.startsWith(".")) {
            const cleanedRule = rule.replace(/^\*\./, ".");
            if (candidate.hostname.endsWith(cleanedRule)) {
              return false;
            }
          } else if (rule === candidate.origin || rule === candidate.hostname || rule === candidate.href) {
            return false;
          }
        }
        return true;
      }
      /**
       * Applies the request interceptors. The request interceptors are applied after the
       * call to prepareRequest is completed.
       *
       * @param {GaxiosOptionsPrepared} options The current set of options.
       *
       * @returns {Promise<GaxiosOptionsPrepared>} Promise that resolves to the set of options or response after interceptors are applied.
       */
      async #applyRequestInterceptors(options) {
        let promiseChain = Promise.resolve(options);
        for (const interceptor of this.interceptors.request.values()) {
          if (interceptor) {
            promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected);
          }
        }
        return promiseChain;
      }
      /**
       * Applies the response interceptors. The response interceptors are applied after the
       * call to request is made.
       *
       * @param {GaxiosOptionsPrepared} options The current set of options.
       *
       * @returns {Promise<GaxiosOptionsPrepared>} Promise that resolves to the set of options or response after interceptors are applied.
       */
      async #applyResponseInterceptors(response) {
        let promiseChain = Promise.resolve(response);
        for (const interceptor of this.interceptors.response.values()) {
          if (interceptor) {
            promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected);
          }
        }
        return promiseChain;
      }
      /**
       * Validates the options, merges them with defaults, and prepare request.
       *
       * @param options The original options passed from the client.
       * @returns Prepared options, ready to make a request
       */
      async #prepareRequest(options) {
        const preparedHeaders = new Headers(this.defaults.headers);
        _a3.mergeHeaders(preparedHeaders, options.headers);
        const opts = (0, extend_1.default)(true, {}, this.defaults, options);
        if (!opts.url) {
          throw new Error("URL is required.");
        }
        if (opts.baseURL) {
          opts.url = new URL(opts.url, opts.baseURL);
        }
        opts.url = new URL(opts.url);
        if (opts.params) {
          if (opts.paramsSerializer) {
            let additionalQueryParams = opts.paramsSerializer(opts.params);
            if (additionalQueryParams.startsWith("?")) {
              additionalQueryParams = additionalQueryParams.slice(1);
            }
            const prefix = opts.url.toString().includes("?") ? "&" : "?";
            opts.url = opts.url + prefix + additionalQueryParams;
          } else {
            const url2 = opts.url instanceof URL ? opts.url : new URL(opts.url);
            for (const [key, value] of new URLSearchParams(opts.params)) {
              url2.searchParams.append(key, value);
            }
            opts.url = url2;
          }
        }
        if (typeof options.maxContentLength === "number") {
          opts.size = options.maxContentLength;
        }
        if (typeof options.maxRedirects === "number") {
          opts.follow = options.maxRedirects;
        }
        const shouldDirectlyPassData = typeof opts.data === "string" || opts.data instanceof ArrayBuffer || opts.data instanceof Blob || // Node 18 does not have a global `File` object
        globalThis.File && opts.data instanceof File || opts.data instanceof FormData || opts.data instanceof stream_1.Readable || opts.data instanceof ReadableStream || opts.data instanceof String || opts.data instanceof URLSearchParams || ArrayBuffer.isView(opts.data) || // `Buffer` (Node.js), `DataView`, `TypedArray`
        /**
         * @deprecated `node-fetch` or another third-party's request types
         */
        ["Blob", "File", "FormData"].includes(opts.data?.constructor?.name || "");
        if (opts.multipart?.length) {
          const boundary = await randomUUID();
          preparedHeaders.set("content-type", `multipart/related; boundary=${boundary}`);
          opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary));
        } else if (shouldDirectlyPassData) {
          opts.body = opts.data;
        } else if (typeof opts.data === "object") {
          if (preparedHeaders.get("Content-Type") === "application/x-www-form-urlencoded") {
            opts.body = opts.paramsSerializer ? opts.paramsSerializer(opts.data) : new URLSearchParams(opts.data);
          } else {
            if (!preparedHeaders.has("content-type")) {
              preparedHeaders.set("content-type", "application/json");
            }
            opts.body = JSON.stringify(opts.data);
          }
        } else if (opts.data) {
          opts.body = opts.data;
        }
        opts.validateStatus = opts.validateStatus || this.validateStatus;
        opts.responseType = opts.responseType || "unknown";
        if (!preparedHeaders.has("accept") && opts.responseType === "json") {
          preparedHeaders.set("accept", "application/json");
        }
        const proxy = opts.proxy || process?.env?.HTTPS_PROXY || process?.env?.https_proxy || process?.env?.HTTP_PROXY || process?.env?.http_proxy;
        if (opts.agent) {
        } else if (proxy && this.#urlMayUseProxy(opts.url, opts.noProxy)) {
          const HttpsProxyAgent = await _a3.#getProxyAgent();
          if (this.agentCache.has(proxy)) {
            opts.agent = this.agentCache.get(proxy);
          } else {
            opts.agent = new HttpsProxyAgent(proxy, {
              cert: opts.cert,
              key: opts.key
            });
            this.agentCache.set(proxy, opts.agent);
          }
        } else if (opts.cert && opts.key) {
          if (this.agentCache.has(opts.key)) {
            opts.agent = this.agentCache.get(opts.key);
          } else {
            opts.agent = new https_1.Agent({
              cert: opts.cert,
              key: opts.key
            });
            this.agentCache.set(opts.key, opts.agent);
          }
        }
        if (typeof opts.errorRedactor !== "function" && opts.errorRedactor !== false) {
          opts.errorRedactor = common_js_1.defaultErrorRedactor;
        }
        if (opts.body && !("duplex" in opts)) {
          opts.duplex = "half";
        }
        this.#appendTimeoutToSignal(opts);
        return Object.assign(opts, {
          headers: preparedHeaders,
          url: opts.url instanceof URL ? opts.url : new URL(opts.url)
        });
      }
      #appendTimeoutToSignal(opts) {
        if (opts.timeout) {
          const timeoutSignal = AbortSignal.timeout(opts.timeout);
          if (opts.signal && !opts.signal.aborted) {
            opts.signal = AbortSignal.any([opts.signal, timeoutSignal]);
          } else {
            opts.signal = timeoutSignal;
          }
        }
      }
      /**
       * By default, throw for any non-2xx status code
       * @param status status code from the HTTP response
       */
      validateStatus(status) {
        return status >= 200 && status < 300;
      }
      /**
       * Attempts to parse a response by looking at the Content-Type header.
       * @param {Response} response the HTTP response.
       * @returns a promise that resolves to the response data.
       */
      async getResponseDataFromContentType(response) {
        let contentType = response.headers.get("Content-Type");
        if (contentType === null) {
          return response.text();
        }
        contentType = contentType.toLowerCase();
        if (contentType.includes("application/json")) {
          let data = await response.text();
          try {
            data = JSON.parse(data);
          } catch {
          }
          return data;
        } else if (contentType.match(/^text\//)) {
          return response.text();
        } else {
          return response.blob();
        }
      }
      /**
       * Creates an async generator that yields the pieces of a multipart/related request body.
       * This implementation follows the spec: https://www.ietf.org/rfc/rfc2387.txt. However, recursive
       * multipart/related requests are not currently supported.
       *
       * @param {GaxiosMultipartOptions[]} multipartOptions the pieces to turn into a multipart/related body.
       * @param {string} boundary the boundary string to be placed between each part.
       */
      async *getMultipartRequest(multipartOptions, boundary) {
        const finale = `--${boundary}--`;
        for (const currentPart of multipartOptions) {
          const partContentType = currentPart.headers.get("Content-Type") || "application/octet-stream";
          const preamble = `--${boundary}\r
Content-Type: ${partContentType}\r
\r
`;
          yield preamble;
          if (typeof currentPart.content === "string") {
            yield currentPart.content;
          } else {
            yield* currentPart.content;
          }
          yield "\r\n";
        }
        yield finale;
      }
      /**
       * A cache for the lazily-loaded proxy agent.
       *
       * Should use {@link Gaxios[#getProxyAgent]} to retrieve.
       */
      // using `import` to dynamically import the types here
      static #proxyAgent;
      /**
       * A cache for the lazily-loaded fetch library.
       *
       * Should use {@link Gaxios[#getFetch]} to retrieve.
       */
      //
      static #fetch;
      /**
       * Imports, caches, and returns a proxy agent - if not already imported
       *
       * @returns A proxy agent
       */
      static async #getProxyAgent() {
        this.#proxyAgent ||= (await Promise.resolve().then(() => __toESM(require_dist2()))).HttpsProxyAgent;
        return this.#proxyAgent;
      }
      static async #getFetch() {
        const hasWindow = typeof window !== "undefined" && !!window;
        this.#fetch ||= hasWindow ? window.fetch : (await Promise.resolve().then(() => (init_src(), src_exports))).default;
        return this.#fetch;
      }
      /**
       * Merges headers.
       * If the base headers do not exist a new `Headers` object will be returned.
       *
       * @remarks
       *
       * Using this utility can be helpful when the headers are not known to exist:
       * - if they exist as `Headers`, that instance will be used
       *   - it improves performance and allows users to use their existing references to their `Headers`
       * - if they exist in another form (`HeadersInit`), they will be used to create a new `Headers` object
       * - if the base headers do not exist a new `Headers` object will be created
       *
       * @param base headers to append/overwrite to
       * @param append headers to append/overwrite with
       * @returns the base headers instance with merged `Headers`
       */
      static mergeHeaders(base, ...append) {
        base = base instanceof Headers ? base : new Headers(base);
        for (const headers of append) {
          const add = headers instanceof Headers ? headers : new Headers(headers);
          add.forEach((value, key) => {
            key === "set-cookie" ? base.append(key, value) : base.set(key, value);
          });
        }
        return base;
      }
    };
    exports2.Gaxios = Gaxios;
    _a3 = Gaxios;
  }
});

// node_modules/gaxios/build/cjs/src/index.js
var require_src2 = __commonJS({
  "node_modules/gaxios/build/cjs/src/index.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __exportStar = exports2 && exports2.__exportStar || function(m2, exports3) {
      for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m2, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.instance = exports2.Gaxios = exports2.GaxiosError = void 0;
    exports2.request = request;
    var gaxios_js_1 = require_gaxios();
    Object.defineProperty(exports2, "Gaxios", { enumerable: true, get: function() {
      return gaxios_js_1.Gaxios;
    } });
    var common_js_1 = require_common3();
    Object.defineProperty(exports2, "GaxiosError", { enumerable: true, get: function() {
      return common_js_1.GaxiosError;
    } });
    __exportStar(require_interceptor(), exports2);
    exports2.instance = new gaxios_js_1.Gaxios();
    async function request(opts) {
      return exports2.instance.request(opts);
    }
  }
});

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

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

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

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

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

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

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

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

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

// node_modules/mongodb/lib/deps.js
var require_deps = __commonJS({
  "node_modules/mongodb/lib/deps.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getKerberos = getKerberos;
    exports2.getZstdLibrary = getZstdLibrary;
    exports2.getAwsCredentialProvider = getAwsCredentialProvider;
    exports2.getGcpMetadata = getGcpMetadata;
    exports2.getSnappy = getSnappy;
    exports2.getSocks = getSocks;
    exports2.getMongoDBClientEncryption = getMongoDBClientEncryption;
    var error_1 = require_error();
    function makeErrorModule(error51) {
      const props = error51 ? { kModuleError: error51 } : {};
      return new Proxy(props, {
        get: (_, key) => {
          if (key === "kModuleError") {
            return error51;
          }
          throw error51;
        },
        set: () => {
          throw error51;
        }
      });
    }
    function getKerberos() {
      let kerberos;
      try {
        kerberos = require("kerberos");
      } catch (error51) {
        kerberos = makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `kerberos` not found. Please install it to enable kerberos authentication", { cause: error51, dependencyName: "kerberos" }));
      }
      return kerberos;
    }
    function getZstdLibrary() {
      let ZStandard;
      try {
        ZStandard = require("@mongodb-js/zstd");
      } catch (error51) {
        ZStandard = makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `@mongodb-js/zstd` not found. Please install it to enable zstd compression", { cause: error51, dependencyName: "zstd" }));
      }
      return ZStandard;
    }
    function getAwsCredentialProvider() {
      try {
        const credentialProvider = require("@aws-sdk/credential-providers");
        return credentialProvider;
      } catch (error51) {
        return makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `@aws-sdk/credential-providers` not found. Please install it to enable getting aws credentials via the official sdk.", { cause: error51, dependencyName: "@aws-sdk/credential-providers" }));
      }
    }
    function getGcpMetadata() {
      try {
        const credentialProvider = require_src4();
        return credentialProvider;
      } catch (error51) {
        return makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `gcp-metadata` not found. Please install it to enable getting gcp credentials via the official sdk.", { cause: error51, dependencyName: "gcp-metadata" }));
      }
    }
    function getSnappy() {
      try {
        const value = require("snappy");
        return value;
      } catch (error51) {
        const kModuleError = new error_1.MongoMissingDependencyError("Optional module `snappy` not found. Please install it to enable snappy compression", { cause: error51, dependencyName: "snappy" });
        return { kModuleError };
      }
    }
    function getSocks() {
      try {
        const value = require("socks");
        return value;
      } catch (error51) {
        const kModuleError = new error_1.MongoMissingDependencyError("Optional module `socks` not found. Please install it to connections over a SOCKS5 proxy", { cause: error51, dependencyName: "socks" });
        return { kModuleError };
      }
    }
    function getMongoDBClientEncryption() {
      let mongodbClientEncryption = null;
      try {
        mongodbClientEncryption = require("mongodb-client-encryption");
      } catch (error51) {
        const kModuleError = new error_1.MongoMissingDependencyError("Optional module `mongodb-client-encryption` not found. Please install it to use auto encryption or ClientEncryption.", { cause: error51, dependencyName: "mongodb-client-encryption" });
        return { kModuleError };
      }
      return mongodbClientEncryption;
    }
  }
});

// node_modules/mongodb/lib/cmap/auth/auth_provider.js
var require_auth_provider = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/auth_provider.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AuthProvider = exports2.AuthContext = void 0;
    var error_1 = require_error();
    var AuthContext = class {
      constructor(connection, credentials, options) {
        this.reauthenticating = false;
        this.connection = connection;
        this.credentials = credentials;
        this.options = options;
      }
    };
    exports2.AuthContext = AuthContext;
    var AuthProvider = class {
      /**
       * Prepare the handshake document before the initial handshake.
       *
       * @param handshakeDoc - The document used for the initial handshake on a connection
       * @param authContext - Context for authentication flow
       */
      async prepare(handshakeDoc, _authContext) {
        return handshakeDoc;
      }
      /**
       * Reauthenticate.
       * @param context - The shared auth context.
       */
      async reauth(context) {
        if (context.reauthenticating) {
          throw new error_1.MongoRuntimeError("Reauthentication already in progress.");
        }
        try {
          context.reauthenticating = true;
          await this.auth(context);
        } finally {
          context.reauthenticating = false;
        }
      }
    };
    exports2.AuthProvider = AuthProvider;
  }
});

// node_modules/mongodb/lib/cmap/auth/gssapi.js
var require_gssapi = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/gssapi.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.GSSAPI = exports2.GSSAPICanonicalizationValue = void 0;
    exports2.performGSSAPICanonicalizeHostName = performGSSAPICanonicalizeHostName;
    exports2.resolveCname = resolveCname;
    var dns2 = require("dns");
    var deps_1 = require_deps();
    var error_1 = require_error();
    var utils_1 = require_utils();
    var auth_provider_1 = require_auth_provider();
    exports2.GSSAPICanonicalizationValue = Object.freeze({
      on: true,
      off: false,
      none: "none",
      forward: "forward",
      forwardAndReverse: "forwardAndReverse"
    });
    async function externalCommand(connection, command) {
      const response = await connection.command((0, utils_1.ns)("$external.$cmd"), command);
      return response;
    }
    var krb;
    var GSSAPI = class extends auth_provider_1.AuthProvider {
      async auth(authContext) {
        const { connection, credentials } = authContext;
        if (credentials == null) {
          throw new error_1.MongoMissingCredentialsError("Credentials required for GSSAPI authentication");
        }
        const { username } = credentials;
        const client = await makeKerberosClient(authContext);
        const payload = await client.step("");
        const saslStartResponse = await externalCommand(connection, saslStart(payload));
        const negotiatedPayload = await negotiate(client, 10, saslStartResponse.payload);
        const saslContinueResponse = await externalCommand(connection, saslContinue(negotiatedPayload, saslStartResponse.conversationId));
        const finalizePayload = await finalize2(client, username, saslContinueResponse.payload);
        await externalCommand(connection, {
          saslContinue: 1,
          conversationId: saslContinueResponse.conversationId,
          payload: finalizePayload
        });
      }
    };
    exports2.GSSAPI = GSSAPI;
    async function makeKerberosClient({ options: { hostAddress, runtime: { os } }, credentials }) {
      if (!hostAddress || typeof hostAddress.host !== "string" || !credentials) {
        throw new error_1.MongoInvalidArgumentError("Connection must have host and port and credentials defined.");
      }
      loadKrb();
      if ("kModuleError" in krb) {
        throw krb["kModuleError"];
      }
      const { initializeClient } = krb;
      const { username, password } = credentials;
      const mechanismProperties = credentials.mechanismProperties;
      const serviceName = mechanismProperties.SERVICE_NAME ?? "mongodb";
      const host = await performGSSAPICanonicalizeHostName(hostAddress.host, mechanismProperties);
      const initOptions = {};
      if (password != null) {
        Object.assign(initOptions, { user: username, password });
      }
      const spnHost = mechanismProperties.SERVICE_HOST ?? host;
      let spn = `${serviceName}${os.platform() === "win32" ? "/" : "@"}${spnHost}`;
      if ("SERVICE_REALM" in mechanismProperties) {
        spn = `${spn}@${mechanismProperties.SERVICE_REALM}`;
      }
      return await initializeClient(spn, initOptions);
    }
    function saslStart(payload) {
      return {
        saslStart: 1,
        mechanism: "GSSAPI",
        payload,
        autoAuthorize: 1
      };
    }
    function saslContinue(payload, conversationId) {
      return {
        saslContinue: 1,
        conversationId,
        payload
      };
    }
    async function negotiate(client, retries, payload) {
      try {
        const response = await client.step(payload);
        return response || "";
      } catch (error51) {
        if (retries === 0) {
          throw error51;
        }
        return await negotiate(client, retries - 1, payload);
      }
    }
    async function finalize2(client, user, payload) {
      const response = await client.unwrap(payload);
      return await client.wrap(response || "", { user });
    }
    async function performGSSAPICanonicalizeHostName(host, mechanismProperties) {
      const mode = mechanismProperties.CANONICALIZE_HOST_NAME;
      if (!mode || mode === exports2.GSSAPICanonicalizationValue.none) {
        return host;
      }
      if (mode === exports2.GSSAPICanonicalizationValue.on || mode === exports2.GSSAPICanonicalizationValue.forwardAndReverse) {
        const { address } = await dns2.promises.lookup(host);
        try {
          const results = await dns2.promises.resolve(address, "PTR");
          return results.length > 0 ? results[0] : host;
        } catch {
          return await resolveCname(host);
        }
      } else {
        return await resolveCname(host);
      }
    }
    async function resolveCname(host) {
      try {
        const results = await dns2.promises.resolve(host, "CNAME");
        return results.length > 0 ? results[0] : host;
      } catch {
        return host;
      }
    }
    function loadKrb() {
      if (!krb) {
        krb = (0, deps_1.getKerberos)();
      }
    }
  }
});

// node_modules/mongodb/lib/cmap/auth/providers.js
var require_providers = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/providers.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AUTH_MECHS_AUTH_SRC_EXTERNAL = exports2.AuthMechanism = void 0;
    exports2.AuthMechanism = Object.freeze({
      MONGODB_AWS: "MONGODB-AWS",
      MONGODB_DEFAULT: "DEFAULT",
      MONGODB_GSSAPI: "GSSAPI",
      MONGODB_PLAIN: "PLAIN",
      MONGODB_SCRAM_SHA1: "SCRAM-SHA-1",
      MONGODB_SCRAM_SHA256: "SCRAM-SHA-256",
      MONGODB_X509: "MONGODB-X509",
      MONGODB_OIDC: "MONGODB-OIDC"
    });
    exports2.AUTH_MECHS_AUTH_SRC_EXTERNAL = /* @__PURE__ */ new Set([
      exports2.AuthMechanism.MONGODB_GSSAPI,
      exports2.AuthMechanism.MONGODB_AWS,
      exports2.AuthMechanism.MONGODB_OIDC,
      exports2.AuthMechanism.MONGODB_X509
    ]);
  }
});

// node_modules/mongodb/lib/cmap/auth/mongo_credentials.js
var require_mongo_credentials = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/mongo_credentials.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MongoCredentials = exports2.DEFAULT_ALLOWED_HOSTS = void 0;
    var error_1 = require_error();
    var gssapi_1 = require_gssapi();
    var providers_1 = require_providers();
    function getDefaultAuthMechanism(hello) {
      if (hello) {
        if (Array.isArray(hello.saslSupportedMechs)) {
          return hello.saslSupportedMechs.includes(providers_1.AuthMechanism.MONGODB_SCRAM_SHA256) ? providers_1.AuthMechanism.MONGODB_SCRAM_SHA256 : providers_1.AuthMechanism.MONGODB_SCRAM_SHA1;
        }
      }
      return providers_1.AuthMechanism.MONGODB_SCRAM_SHA256;
    }
    var ALLOWED_ENVIRONMENT_NAMES = [
      "test",
      "azure",
      "gcp",
      "k8s"
    ];
    var ALLOWED_HOSTS_ERROR = "Auth mechanism property ALLOWED_HOSTS must be an array of strings.";
    exports2.DEFAULT_ALLOWED_HOSTS = [
      "*.mongodb.net",
      "*.mongodb-qa.net",
      "*.mongodb-dev.net",
      "*.mongodbgov.net",
      "localhost",
      "127.0.0.1",
      "::1",
      "*.mongo.com"
    ];
    var TOKEN_RESOURCE_MISSING_ERROR = "TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is azure or gcp.";
    var MongoCredentials = class _MongoCredentials {
      constructor(options) {
        this.username = options.username ?? "";
        this.password = options.password;
        this.source = options.source;
        if (!this.source && options.db) {
          this.source = options.db;
        }
        this.mechanism = options.mechanism || providers_1.AuthMechanism.MONGODB_DEFAULT;
        this.mechanismProperties = options.mechanismProperties || {};
        if (this.mechanism === providers_1.AuthMechanism.MONGODB_OIDC && !this.mechanismProperties.ALLOWED_HOSTS) {
          this.mechanismProperties = {
            ...this.mechanismProperties,
            ALLOWED_HOSTS: exports2.DEFAULT_ALLOWED_HOSTS
          };
        }
        Object.freeze(this.mechanismProperties);
        Object.freeze(this);
      }
      /** Determines if two MongoCredentials objects are equivalent */
      equals(other) {
        return this.mechanism === other.mechanism && this.username === other.username && this.password === other.password && this.source === other.source;
      }
      /**
       * If the authentication mechanism is set to "default", resolves the authMechanism
       * based on the server version and server supported sasl mechanisms.
       *
       * @param hello - A hello response from the server
       */
      resolveAuthMechanism(hello) {
        if (this.mechanism.match(/DEFAULT/i)) {
          return new _MongoCredentials({
            username: this.username,
            password: this.password,
            source: this.source,
            mechanism: getDefaultAuthMechanism(hello),
            mechanismProperties: this.mechanismProperties
          });
        }
        return this;
      }
      validate() {
        if ((this.mechanism === providers_1.AuthMechanism.MONGODB_GSSAPI || this.mechanism === providers_1.AuthMechanism.MONGODB_PLAIN || this.mechanism === providers_1.AuthMechanism.MONGODB_SCRAM_SHA1 || this.mechanism === providers_1.AuthMechanism.MONGODB_SCRAM_SHA256) && !this.username) {
          throw new error_1.MongoMissingCredentialsError(`Username required for mechanism '${this.mechanism}'`);
        }
        if (this.mechanism === providers_1.AuthMechanism.MONGODB_OIDC) {
          if (this.username && this.mechanismProperties.ENVIRONMENT && this.mechanismProperties.ENVIRONMENT !== "azure") {
            throw new error_1.MongoInvalidArgumentError(`username and ENVIRONMENT '${this.mechanismProperties.ENVIRONMENT}' may not be used together for mechanism '${this.mechanism}'.`);
          }
          if (this.username && this.password) {
            throw new error_1.MongoInvalidArgumentError(`No password is allowed in ENVIRONMENT '${this.mechanismProperties.ENVIRONMENT}' for '${this.mechanism}'.`);
          }
          if ((this.mechanismProperties.ENVIRONMENT === "azure" || this.mechanismProperties.ENVIRONMENT === "gcp") && !this.mechanismProperties.TOKEN_RESOURCE) {
            throw new error_1.MongoInvalidArgumentError(TOKEN_RESOURCE_MISSING_ERROR);
          }
          if (this.mechanismProperties.ENVIRONMENT && !ALLOWED_ENVIRONMENT_NAMES.includes(this.mechanismProperties.ENVIRONMENT)) {
            throw new error_1.MongoInvalidArgumentError(`Currently only a ENVIRONMENT in ${ALLOWED_ENVIRONMENT_NAMES.join(",")} is supported for mechanism '${this.mechanism}'.`);
          }
          if (!this.mechanismProperties.ENVIRONMENT && !this.mechanismProperties.OIDC_CALLBACK && !this.mechanismProperties.OIDC_HUMAN_CALLBACK) {
            throw new error_1.MongoInvalidArgumentError(`Either a ENVIRONMENT, OIDC_CALLBACK, or OIDC_HUMAN_CALLBACK must be specified for mechanism '${this.mechanism}'.`);
          }
          if (this.mechanismProperties.ALLOWED_HOSTS) {
            const hosts = this.mechanismProperties.ALLOWED_HOSTS;
            if (!Array.isArray(hosts)) {
              throw new error_1.MongoInvalidArgumentError(ALLOWED_HOSTS_ERROR);
            }
            for (const host of hosts) {
              if (typeof host !== "string") {
                throw new error_1.MongoInvalidArgumentError(ALLOWED_HOSTS_ERROR);
              }
            }
          }
        }
        if (providers_1.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(this.mechanism)) {
          if (this.source != null && this.source !== "$external") {
            throw new error_1.MongoAPIError(`Invalid source '${this.source}' for mechanism '${this.mechanism}' specified.`);
          }
        }
        if (this.mechanism === providers_1.AuthMechanism.MONGODB_PLAIN && this.source == null) {
          throw new error_1.MongoAPIError("PLAIN Authentication Mechanism needs an auth source");
        }
        if (this.mechanism === providers_1.AuthMechanism.MONGODB_X509 && this.password != null) {
          if (this.password === "") {
            Reflect.set(this, "password", void 0);
            return;
          }
          throw new error_1.MongoAPIError(`Password not allowed for mechanism MONGODB-X509`);
        }
        const canonicalization = this.mechanismProperties.CANONICALIZE_HOST_NAME ?? false;
        if (!Object.values(gssapi_1.GSSAPICanonicalizationValue).includes(canonicalization)) {
          throw new error_1.MongoAPIError(`Invalid CANONICALIZE_HOST_NAME value: ${canonicalization}`);
        }
      }
      static merge(creds, options) {
        return new _MongoCredentials({
          username: options.username ?? creds?.username ?? "",
          password: options.password ?? creds?.password ?? "",
          mechanism: options.mechanism ?? creds?.mechanism ?? providers_1.AuthMechanism.MONGODB_DEFAULT,
          mechanismProperties: options.mechanismProperties ?? creds?.mechanismProperties ?? {},
          source: options.source ?? options.db ?? creds?.source ?? "admin"
        });
      }
    };
    exports2.MongoCredentials = MongoCredentials;
  }
});

// node_modules/mongodb/package.json
var require_package2 = __commonJS({
  "node_modules/mongodb/package.json"(exports2, module2) {
    module2.exports = {
      name: "mongodb",
      version: "7.5.0",
      description: "The official MongoDB driver for Node.js",
      main: "lib/index.js",
      files: [
        "lib",
        "src",
        "etc/prepare.js",
        "mongodb.d.ts",
        "tsconfig.json"
      ],
      types: "mongodb.d.ts",
      repository: {
        type: "git",
        url: "git@github.com:mongodb/node-mongodb-native.git"
      },
      keywords: [
        "mongodb",
        "driver",
        "official"
      ],
      author: {
        name: "The MongoDB NodeJS Team",
        email: "dbx-node@mongodb.com"
      },
      dependencies: {
        "@mongodb-js/saslprep": "^1.4.11",
        bson: "^7.2.0",
        "mongodb-connection-string-url": "^7.0.1"
      },
      peerDependencies: {
        "@aws-sdk/credential-providers": "^3.806.0",
        "@mongodb-js/zstd": "^7.0.0",
        "gcp-metadata": "^7.0.1",
        kerberos: "^7.0.0",
        "mongodb-client-encryption": "^7.2.0",
        snappy: "^7.3.2",
        socks: "^2.8.6"
      },
      peerDependenciesMeta: {
        "@aws-sdk/credential-providers": {
          optional: true
        },
        "@mongodb-js/zstd": {
          optional: true
        },
        kerberos: {
          optional: true
        },
        snappy: {
          optional: true
        },
        "mongodb-client-encryption": {
          optional: true
        },
        "gcp-metadata": {
          optional: true
        },
        socks: {
          optional: true
        }
      },
      devDependencies: {
        "@aws-sdk/credential-providers": "^3.876.0",
        "@iarna/toml": "^2.2.5",
        "@istanbuljs/nyc-config-typescript": "^1.0.2",
        "@microsoft/api-extractor": "^7.58.7",
        "@microsoft/tsdoc-config": "^0.18.1",
        "@mongodb-js/zstd": "^7.0.0",
        "@types/chai-subset": "^1.3.5",
        "@types/express": "^5.0.6",
        "@types/kerberos": "^1.1.5",
        "@types/mocha": "^10.0.9",
        "@types/node": "^22.15.3",
        "@types/saslprep": "^1.0.3",
        "@types/semver": "^7.7.0",
        "@types/sinon": "^17.0.4",
        "@types/whatwg-url": "^13.0.0",
        "@typescript-eslint/eslint-plugin": "^8.60.1",
        "@typescript-eslint/parser": "^8.31.1",
        aws4: "^1.13.2",
        chai: "^5.3.3",
        "chai-subset": "^1.6.0",
        chalk: "^4.1.2",
        esbuild: "^0.28.0",
        eslint: "^9.39.1",
        "eslint-config-prettier": "^10.1.8",
        "eslint-plugin-mocha": "^10.4.1",
        "eslint-plugin-prettier": "^5.5.6",
        "eslint-plugin-simple-import-sort": "^12.1.1",
        "eslint-plugin-tsdoc": "^0.5.2",
        "eslint-plugin-unused-imports": "^4.4.1",
        express: "^5.2.1",
        "gcp-metadata": "^7.0.1",
        "js-yaml": "^4.2.0",
        mocha: "^11.7.6",
        "mocha-sinon": "^2.1.2",
        "mongodb-client-encryption": "^7.2.0",
        nyc: "^17.1.0",
        prettier: "^3.6.2",
        semver: "^7.7.2",
        sinon: "^18.0.1",
        "sinon-chai": "^4.0.1",
        snappy: "^7.3.2",
        socks: "^2.8.7",
        "source-map-support": "^0.5.21",
        "ts-node": "^10.9.2",
        tsd: "^0.33.0",
        typescript: "5.8.3",
        "typescript-cached-transpile": "^0.0.6",
        "v8-heapsnapshot": "^1.3.1",
        yargs: "^18.0.0"
      },
      license: "Apache-2.0",
      engines: {
        node: ">=20.19.0"
      },
      bugs: {
        url: "https://jira.mongodb.org/projects/NODE/issues/"
      },
      homepage: "https://github.com/mongodb/node-mongodb-native",
      scripts: {
        "build:evergreen": "node .evergreen/generate_evergreen_tasks.js",
        "build:ts": "node ./node_modules/typescript/bin/tsc",
        "build:dts": "npm run build:ts && api-extractor run && node etc/clean_definition_files.cjs && ESLINT_USE_FLAT_CONFIG=false eslint --no-ignore --fix mongodb.d.ts",
        "build:docs": "./etc/docs/build.ts",
        "build:typedoc": "typedoc",
        "build:nightly": "node ./.github/scripts/nightly.mjs",
        "check:bench": "npm --prefix test/benchmarks/driver_bench start",
        "check:coverage": "nyc npm run test:all",
        "check:integration-coverage": "nyc npm run check:test",
        "check:lambda": "npm run build:bundle && nyc mocha --config test/mocha_lambda.js test/integration/node-specific/examples/handler.test.js",
        "check:lambda:aws": "npm run build:bundle && nyc mocha --config test/mocha_lambda.js test/integration/node-specific/examples/aws_handler.test.js",
        "check:lint": "npm run build:dts && npm run check:dts && npm run check:eslint && npm run check:tsd",
        "check:eslint": "npm run build:dts && ESLINT_USE_FLAT_CONFIG=false eslint -v && ESLINT_USE_FLAT_CONFIG=false eslint --max-warnings=0 --ext '.js,.ts' src test",
        "check:tsd": "tsd --version && tsd",
        "check:dependencies": "npm run build:bundle && mocha test/action/dependency.test.ts",
        "check:dts": "npm run build:bundle && node ./node_modules/typescript/bin/tsc --target es2023 --module commonjs --noEmit mongodb.d.ts && tsd",
        "check:search-indexes": "npm run build:bundle && nyc mocha --config test/mocha_mongodb.js test/manual/search-index-management.prose.test.ts",
        "check:test": "npm run build:bundle && nyc mocha --config test/mocha_mongodb.js test/integration",
        "check:test:debug": "npm run mocha:debug -- --config test/mocha_mongodb.js test/integration",
        "check:test-bundled": "MONGODB_BUNDLED=true npm run check:test",
        "check:unit": "npm run build:bundle && nyc mocha test/unit",
        "check:unit:debug": "npm run mocha:debug -- test/unit",
        "check:unit-bundled": "MONGODB_BUNDLED=true npm run check:unit",
        "check:ts": "node ./node_modules/typescript/bin/tsc -v && node ./node_modules/typescript/bin/tsc --noEmit",
        "check:atlas": "npm run build:bundle && nyc mocha --config test/manual/mocharc.js test/manual/atlas_connectivity.test.ts",
        "check:drivers-atlas-testing": "npm run build:bundle && nyc mocha --config test/mocha_mongodb.js test/atlas/drivers_atlas_testing.test.ts",
        "check:aws": "npm run build:bundle && nyc mocha --config test/mocha_mongodb.js test/integration/auth/mongodb_aws.test.ts test/integration/auth/mongodb_aws.prose.test.ts",
        "check:oidc-auth": "npm run build:bundle && nyc mocha --config test/mocha_mongodb.js test/integration/auth/auth.spec.test.ts",
        "check:oidc-test": "npm run build:bundle && nyc mocha --config test/mocha_mongodb.js test/integration/auth/mongodb_oidc.prose.test.ts",
        "check:kerberos": "npm run build:bundle && nyc mocha --config test/manual/mocharc.js test/manual/kerberos.test.ts",
        "check:tls": "npm run build:bundle && nyc mocha --config test/manual/mocharc.js test/manual/tls_support.test.ts",
        "check:ldap": "npm run build:bundle && nyc mocha --config test/manual/mocharc.js test/manual/ldap.test.ts",
        "check:socks5": "npm run build:bundle && nyc mocha --config test/manual/mocharc.js test/manual/socks5.test.ts",
        "check:csfle": "npm run build:bundle && nyc mocha --config test/mocha_mongodb.js test/integration/client-side-encryption",
        "check:snappy": "npm run build:bundle && nyc mocha test/unit/assorted/snappy.test.js",
        "check:x509": "npm run build:bundle && nyc mocha test/manual/x509_auth.test.ts",
        "mocha:debug": "npm run build:bundle && node --inspect --enable-source-maps --no-experimental-strip-types ./node_modules/mocha/bin/mocha.js",
        "build:bundle": "npm run bundle:driver && npm run bundle:types && npm run build:runtime-barrel",
        "build:runtime-barrel": "node etc/build-runtime-barrel.mjs",
        "bundle:driver": "node etc/bundle-driver.mjs",
        "bundle:types": "npx tsc --project ./tsconfig.json --declaration --emitDeclarationOnly --declarationDir test/tools/runner/bundle/types",
        "fix:eslint": "npm run check:eslint -- --fix",
        prepare: "node etc/prepare.js",
        "preview:docs": "ts-node etc/docs/preview.ts",
        "switch:to-bundled": "MONGODB_BUNDLED=true npm run build:runtime-barrel",
        "switch:to-unbundled": "MONGODB_BUNDLED=false npm run build:runtime-barrel",
        test: "npm run check:lint && npm run test:all",
        "test:all": "npm run check:unit && npm run check:test",
        "update:docs": "npm run build:docs -- --yes"
      },
      tsd: {
        directory: "test/types",
        compilerOptions: {
          strict: true,
          target: "esnext",
          module: "commonjs",
          moduleResolution: "node"
        }
      }
    };
  }
});

// node_modules/mongodb/lib/cmap/handshake/client_metadata.js
var require_client_metadata = __commonJS({
  "node_modules/mongodb/lib/cmap/handshake/client_metadata.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LimitedSizeDocument = void 0;
    exports2.isDriverInfoEqual = isDriverInfoEqual;
    exports2.makeClientMetadata = makeClientMetadata;
    exports2.getFAASEnv = getFAASEnv;
    var process4 = require("process");
    var bson_1 = require_bson2();
    var error_1 = require_error();
    var utils_1 = require_utils();
    var NODE_DRIVER_VERSION = require_package2().version;
    function isDriverInfoEqual(info1, info2) {
      const nonEmptyCmp = (s1, s2) => {
        s1 ||= void 0;
        s2 ||= void 0;
        return s1 === s2;
      };
      return nonEmptyCmp(info1.name, info2.name) && nonEmptyCmp(info1.platform, info2.platform) && nonEmptyCmp(info1.version, info2.version);
    }
    var LimitedSizeDocument = class {
      constructor(maxSize) {
        this.document = /* @__PURE__ */ new Map();
        this.documentSize = 5;
        this.maxSize = maxSize;
      }
      /** Only adds key/value if the bsonByteLength is less than MAX_SIZE */
      ifItFitsItSits(key, value) {
        const newElementSize = bson_1.BSON.serialize((/* @__PURE__ */ new Map()).set(key, value)).byteLength - 5;
        if (newElementSize + this.documentSize > this.maxSize) {
          return false;
        }
        this.documentSize += newElementSize;
        this.document.set(key, value);
        return true;
      }
      toObject() {
        return bson_1.BSON.deserialize(bson_1.BSON.serialize(this.document), {
          promoteLongs: false,
          promoteBuffers: false,
          promoteValues: false,
          useBigInt64: false
        });
      }
    };
    exports2.LimitedSizeDocument = LimitedSizeDocument;
    async function makeClientMetadata(driverInfoList, { appName = "", runtime: { os } }) {
      const metadataDocument = new LimitedSizeDocument(512);
      if (appName.length > 0) {
        const name = bson_1.ByteUtils.utf8ByteLength(appName) <= 128 ? appName : bson_1.ByteUtils.toUTF8(bson_1.ByteUtils.fromUTF8(appName), 0, 128, false);
        metadataDocument.ifItFitsItSits("application", { name });
      }
      const driverInfo = {
        name: "nodejs",
        version: NODE_DRIVER_VERSION
      };
      for (const { name: n = "", version: v = "" } of driverInfoList) {
        if (n.length > 0) {
          driverInfo.name = `${driverInfo.name}|${n}`;
        }
        if (v.length > 0) {
          driverInfo.version = `${driverInfo.version}|${v}`;
        }
      }
      if (!metadataDocument.ifItFitsItSits("driver", driverInfo)) {
        throw new error_1.MongoInvalidArgumentError("Unable to include driverInfo name and version, metadata cannot exceed 512 bytes");
      }
      let runtimeInfo = getRuntimeInfo();
      for (const { platform = "" } of driverInfoList) {
        if (platform.length > 0) {
          runtimeInfo = `${runtimeInfo}|${platform}`;
        }
      }
      if (!metadataDocument.ifItFitsItSits("platform", runtimeInfo)) {
        throw new error_1.MongoInvalidArgumentError("Unable to include driverInfo platform, metadata cannot exceed 512 bytes");
      }
      const osInfo = (/* @__PURE__ */ new Map()).set("name", os.platform()).set("architecture", os.arch()).set("version", os.release()).set("type", os.type());
      if (!metadataDocument.ifItFitsItSits("os", osInfo)) {
        for (const key of osInfo.keys()) {
          osInfo.delete(key);
          if (osInfo.size === 0)
            break;
          if (metadataDocument.ifItFitsItSits("os", osInfo))
            break;
        }
      }
      const faasEnv = getFAASEnv();
      if (faasEnv != null) {
        if (!metadataDocument.ifItFitsItSits("env", faasEnv)) {
          for (const key of faasEnv.keys()) {
            faasEnv.delete(key);
            if (faasEnv.size === 0)
              break;
            if (metadataDocument.ifItFitsItSits("env", faasEnv))
              break;
          }
        }
      }
      return await addContainerMetadata(metadataDocument.toObject());
    }
    var dockerPromise;
    async function getContainerMetadata() {
      dockerPromise ??= (0, utils_1.fileIsAccessible)("/.dockerenv");
      const isDocker = await dockerPromise;
      const { KUBERNETES_SERVICE_HOST = "" } = process4.env;
      const isKubernetes = KUBERNETES_SERVICE_HOST.length > 0 ? true : false;
      const containerMetadata = {};
      if (isDocker)
        containerMetadata.runtime = "docker";
      if (isKubernetes)
        containerMetadata.orchestrator = "kubernetes";
      return containerMetadata;
    }
    async function addContainerMetadata(originalMetadata) {
      const containerMetadata = await getContainerMetadata();
      if (Object.keys(containerMetadata).length === 0)
        return originalMetadata;
      const extendedMetadata = new LimitedSizeDocument(512);
      const extendedEnvMetadata = {
        ...originalMetadata?.env,
        container: containerMetadata
      };
      for (const [key, val] of Object.entries(originalMetadata)) {
        if (key !== "env") {
          extendedMetadata.ifItFitsItSits(key, val);
        } else {
          if (!extendedMetadata.ifItFitsItSits("env", extendedEnvMetadata)) {
            extendedMetadata.ifItFitsItSits("env", val);
          }
        }
      }
      if (!("env" in originalMetadata)) {
        extendedMetadata.ifItFitsItSits("env", extendedEnvMetadata);
      }
      return extendedMetadata.toObject();
    }
    function getFAASEnv() {
      const { AWS_EXECUTION_ENV = "", AWS_LAMBDA_RUNTIME_API = "", FUNCTIONS_WORKER_RUNTIME = "", K_SERVICE = "", FUNCTION_NAME = "", VERCEL = "", AWS_LAMBDA_FUNCTION_MEMORY_SIZE = "", AWS_REGION = "", FUNCTION_MEMORY_MB = "", FUNCTION_REGION = "", FUNCTION_TIMEOUT_SEC = "", VERCEL_REGION = "" } = process4.env;
      const isAWSFaaS = AWS_EXECUTION_ENV.startsWith("AWS_Lambda_") || AWS_LAMBDA_RUNTIME_API.length > 0;
      const isAzureFaaS = FUNCTIONS_WORKER_RUNTIME.length > 0;
      const isGCPFaaS = K_SERVICE.length > 0 || FUNCTION_NAME.length > 0;
      const isVercelFaaS = VERCEL.length > 0;
      const faasEnv = /* @__PURE__ */ new Map();
      if (isVercelFaaS && !(isAzureFaaS || isGCPFaaS)) {
        if (VERCEL_REGION.length > 0) {
          faasEnv.set("region", VERCEL_REGION);
        }
        faasEnv.set("name", "vercel");
        return faasEnv;
      }
      if (isAWSFaaS && !(isAzureFaaS || isGCPFaaS || isVercelFaaS)) {
        if (AWS_REGION.length > 0) {
          faasEnv.set("region", AWS_REGION);
        }
        if (AWS_LAMBDA_FUNCTION_MEMORY_SIZE.length > 0 && Number.isInteger(+AWS_LAMBDA_FUNCTION_MEMORY_SIZE)) {
          faasEnv.set("memory_mb", new bson_1.Int32(AWS_LAMBDA_FUNCTION_MEMORY_SIZE));
        }
        faasEnv.set("name", "aws.lambda");
        return faasEnv;
      }
      if (isAzureFaaS && !(isGCPFaaS || isAWSFaaS || isVercelFaaS)) {
        faasEnv.set("name", "azure.func");
        return faasEnv;
      }
      if (isGCPFaaS && !(isAzureFaaS || isAWSFaaS || isVercelFaaS)) {
        if (FUNCTION_REGION.length > 0) {
          faasEnv.set("region", FUNCTION_REGION);
        }
        if (FUNCTION_MEMORY_MB.length > 0 && Number.isInteger(+FUNCTION_MEMORY_MB)) {
          faasEnv.set("memory_mb", new bson_1.Int32(FUNCTION_MEMORY_MB));
        }
        if (FUNCTION_TIMEOUT_SEC.length > 0 && Number.isInteger(+FUNCTION_TIMEOUT_SEC)) {
          faasEnv.set("timeout_sec", new bson_1.Int32(FUNCTION_TIMEOUT_SEC));
        }
        faasEnv.set("name", "gcp.func");
        return faasEnv;
      }
      return null;
    }
    function getRuntimeInfo() {
      const endianness = bson_1.NumberUtils.isBigEndian ? "BE" : "LE";
      if ("Deno" in globalThis) {
        const version2 = typeof Deno?.version?.deno === "string" ? Deno?.version?.deno : "0.0.0-unknown";
        return `Deno v${version2}, ${endianness}`;
      }
      if ("Bun" in globalThis) {
        const version2 = typeof Bun?.version === "string" ? Bun?.version : "0.0.0-unknown";
        return `Bun v${version2}, ${endianness}`;
      }
      return `Node.js ${process4.version}, ${endianness}`;
    }
  }
});

// node_modules/webidl-conversions/lib/index.js
var require_lib = __commonJS({
  "node_modules/webidl-conversions/lib/index.js"(exports2) {
    "use strict";
    function makeException(ErrorType, message, options) {
      if (options.globals) {
        ErrorType = options.globals[ErrorType.name];
      }
      return new ErrorType(`${options.context ? options.context : "Value"} ${message}.`);
    }
    function toNumber(value, options) {
      if (typeof value === "bigint") {
        throw makeException(TypeError, "is a BigInt which cannot be converted to a number", options);
      }
      if (!options.globals) {
        return Number(value);
      }
      return options.globals.Number(value);
    }
    function evenRound(x2) {
      if (x2 > 0 && x2 % 1 === 0.5 && (x2 & 1) === 0 || x2 < 0 && x2 % 1 === -0.5 && (x2 & 1) === 1) {
        return censorNegativeZero(Math.floor(x2));
      }
      return censorNegativeZero(Math.round(x2));
    }
    function integerPart(n) {
      return censorNegativeZero(Math.trunc(n));
    }
    function sign(x2) {
      return x2 < 0 ? -1 : 1;
    }
    function modulo(x2, y) {
      const signMightNotMatch = x2 % y;
      if (sign(y) !== sign(signMightNotMatch)) {
        return signMightNotMatch + y;
      }
      return signMightNotMatch;
    }
    function censorNegativeZero(x2) {
      return x2 === 0 ? 0 : x2;
    }
    function createIntegerConversion(bitLength, { unsigned }) {
      let lowerBound, upperBound;
      if (unsigned) {
        lowerBound = 0;
        upperBound = 2 ** bitLength - 1;
      } else {
        lowerBound = -(2 ** (bitLength - 1));
        upperBound = 2 ** (bitLength - 1) - 1;
      }
      const twoToTheBitLength = 2 ** bitLength;
      const twoToOneLessThanTheBitLength = 2 ** (bitLength - 1);
      return (value, options = {}) => {
        let x2 = toNumber(value, options);
        x2 = censorNegativeZero(x2);
        if (options.enforceRange) {
          if (!Number.isFinite(x2)) {
            throw makeException(TypeError, "is not a finite number", options);
          }
          x2 = integerPart(x2);
          if (x2 < lowerBound || x2 > upperBound) {
            throw makeException(
              TypeError,
              `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`,
              options
            );
          }
          return x2;
        }
        if (!Number.isNaN(x2) && options.clamp) {
          x2 = Math.min(Math.max(x2, lowerBound), upperBound);
          x2 = evenRound(x2);
          return x2;
        }
        if (!Number.isFinite(x2) || x2 === 0) {
          return 0;
        }
        x2 = integerPart(x2);
        if (x2 >= lowerBound && x2 <= upperBound) {
          return x2;
        }
        x2 = modulo(x2, twoToTheBitLength);
        if (!unsigned && x2 >= twoToOneLessThanTheBitLength) {
          return x2 - twoToTheBitLength;
        }
        return x2;
      };
    }
    function createLongLongConversion(bitLength, { unsigned }) {
      const upperBound = Number.MAX_SAFE_INTEGER;
      const lowerBound = unsigned ? 0 : Number.MIN_SAFE_INTEGER;
      const asBigIntN = unsigned ? BigInt.asUintN : BigInt.asIntN;
      return (value, options = {}) => {
        let x2 = toNumber(value, options);
        x2 = censorNegativeZero(x2);
        if (options.enforceRange) {
          if (!Number.isFinite(x2)) {
            throw makeException(TypeError, "is not a finite number", options);
          }
          x2 = integerPart(x2);
          if (x2 < lowerBound || x2 > upperBound) {
            throw makeException(
              TypeError,
              `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`,
              options
            );
          }
          return x2;
        }
        if (!Number.isNaN(x2) && options.clamp) {
          x2 = Math.min(Math.max(x2, lowerBound), upperBound);
          x2 = evenRound(x2);
          return x2;
        }
        if (!Number.isFinite(x2) || x2 === 0) {
          return 0;
        }
        let xBigInt = BigInt(integerPart(x2));
        xBigInt = asBigIntN(bitLength, xBigInt);
        return Number(xBigInt);
      };
    }
    exports2.any = (value) => {
      return value;
    };
    exports2.undefined = () => {
      return void 0;
    };
    exports2.boolean = (value) => {
      return Boolean(value);
    };
    exports2.byte = createIntegerConversion(8, { unsigned: false });
    exports2.octet = createIntegerConversion(8, { unsigned: true });
    exports2.short = createIntegerConversion(16, { unsigned: false });
    exports2["unsigned short"] = createIntegerConversion(16, { unsigned: true });
    exports2.long = createIntegerConversion(32, { unsigned: false });
    exports2["unsigned long"] = createIntegerConversion(32, { unsigned: true });
    exports2["long long"] = createLongLongConversion(64, { unsigned: false });
    exports2["unsigned long long"] = createLongLongConversion(64, { unsigned: true });
    exports2.double = (value, options = {}) => {
      const x2 = toNumber(value, options);
      if (!Number.isFinite(x2)) {
        throw makeException(TypeError, "is not a finite floating-point value", options);
      }
      return x2;
    };
    exports2["unrestricted double"] = (value, options = {}) => {
      const x2 = toNumber(value, options);
      return x2;
    };
    exports2.float = (value, options = {}) => {
      const x2 = toNumber(value, options);
      if (!Number.isFinite(x2)) {
        throw makeException(TypeError, "is not a finite floating-point value", options);
      }
      if (Object.is(x2, -0)) {
        return x2;
      }
      const y = Math.fround(x2);
      if (!Number.isFinite(y)) {
        throw makeException(TypeError, "is outside the range of a single-precision floating-point value", options);
      }
      return y;
    };
    exports2["unrestricted float"] = (value, options = {}) => {
      const x2 = toNumber(value, options);
      if (isNaN(x2)) {
        return x2;
      }
      if (Object.is(x2, -0)) {
        return x2;
      }
      return Math.fround(x2);
    };
    exports2.DOMString = (value, options = {}) => {
      if (options.treatNullAsEmptyString && value === null) {
        return "";
      }
      if (typeof value === "symbol") {
        throw makeException(TypeError, "is a symbol, which cannot be converted to a string", options);
      }
      const StringCtor = options.globals ? options.globals.String : String;
      return StringCtor(value);
    };
    exports2.ByteString = (value, options = {}) => {
      const x2 = exports2.DOMString(value, options);
      let c;
      for (let i2 = 0; (c = x2.codePointAt(i2)) !== void 0; ++i2) {
        if (c > 255) {
          throw makeException(TypeError, "is not a valid ByteString", options);
        }
      }
      return x2;
    };
    exports2.USVString = (value, options = {}) => {
      const S2 = exports2.DOMString(value, options);
      const n = S2.length;
      const U = [];
      for (let i2 = 0; i2 < n; ++i2) {
        const c = S2.charCodeAt(i2);
        if (c < 55296 || c > 57343) {
          U.push(String.fromCodePoint(c));
        } else if (56320 <= c && c <= 57343) {
          U.push(String.fromCodePoint(65533));
        } else if (i2 === n - 1) {
          U.push(String.fromCodePoint(65533));
        } else {
          const d = S2.charCodeAt(i2 + 1);
          if (56320 <= d && d <= 57343) {
            const a = c & 1023;
            const b = d & 1023;
            U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b));
            ++i2;
          } else {
            U.push(String.fromCodePoint(65533));
          }
        }
      }
      return U.join("");
    };
    exports2.object = (value, options = {}) => {
      if (value === null || typeof value !== "object" && typeof value !== "function") {
        throw makeException(TypeError, "is not an object", options);
      }
      return value;
    };
    var abByteLengthGetter = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
    var sabByteLengthGetter = typeof SharedArrayBuffer === "function" ? Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, "byteLength").get : null;
    function isNonSharedArrayBuffer(value) {
      try {
        abByteLengthGetter.call(value);
        return true;
      } catch {
        return false;
      }
    }
    function isSharedArrayBuffer(value) {
      try {
        sabByteLengthGetter.call(value);
        return true;
      } catch {
        return false;
      }
    }
    function isArrayBufferDetached(value) {
      try {
        new Uint8Array(value);
        return false;
      } catch {
        return true;
      }
    }
    exports2.ArrayBuffer = (value, options = {}) => {
      if (!isNonSharedArrayBuffer(value)) {
        if (options.allowShared && !isSharedArrayBuffer(value)) {
          throw makeException(TypeError, "is not an ArrayBuffer or SharedArrayBuffer", options);
        }
        throw makeException(TypeError, "is not an ArrayBuffer", options);
      }
      if (isArrayBufferDetached(value)) {
        throw makeException(TypeError, "is a detached ArrayBuffer", options);
      }
      return value;
    };
    var dvByteLengthGetter = Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get;
    exports2.DataView = (value, options = {}) => {
      try {
        dvByteLengthGetter.call(value);
      } catch (e2) {
        throw makeException(TypeError, "is not a DataView", options);
      }
      if (!options.allowShared && isSharedArrayBuffer(value.buffer)) {
        throw makeException(TypeError, "is backed by a SharedArrayBuffer, which is not allowed", options);
      }
      if (isArrayBufferDetached(value.buffer)) {
        throw makeException(TypeError, "is backed by a detached ArrayBuffer", options);
      }
      return value;
    };
    var typedArrayNameGetter = Object.getOwnPropertyDescriptor(
      Object.getPrototypeOf(Uint8Array).prototype,
      Symbol.toStringTag
    ).get;
    [
      Int8Array,
      Int16Array,
      Int32Array,
      Uint8Array,
      Uint16Array,
      Uint32Array,
      Uint8ClampedArray,
      Float32Array,
      Float64Array
    ].forEach((func) => {
      const { name } = func;
      const article = /^[AEIOU]/u.test(name) ? "an" : "a";
      exports2[name] = (value, options = {}) => {
        if (!ArrayBuffer.isView(value) || typedArrayNameGetter.call(value) !== name) {
          throw makeException(TypeError, `is not ${article} ${name} object`, options);
        }
        if (!options.allowShared && isSharedArrayBuffer(value.buffer)) {
          throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", options);
        }
        if (isArrayBufferDetached(value.buffer)) {
          throw makeException(TypeError, "is a view on a detached ArrayBuffer", options);
        }
        return value;
      };
    });
    exports2.ArrayBufferView = (value, options = {}) => {
      if (!ArrayBuffer.isView(value)) {
        throw makeException(TypeError, "is not a view on an ArrayBuffer or SharedArrayBuffer", options);
      }
      if (!options.allowShared && isSharedArrayBuffer(value.buffer)) {
        throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", options);
      }
      if (isArrayBufferDetached(value.buffer)) {
        throw makeException(TypeError, "is a view on a detached ArrayBuffer", options);
      }
      return value;
    };
    exports2.BufferSource = (value, options = {}) => {
      if (ArrayBuffer.isView(value)) {
        if (!options.allowShared && isSharedArrayBuffer(value.buffer)) {
          throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", options);
        }
        if (isArrayBufferDetached(value.buffer)) {
          throw makeException(TypeError, "is a view on a detached ArrayBuffer", options);
        }
        return value;
      }
      if (!options.allowShared && !isNonSharedArrayBuffer(value)) {
        throw makeException(TypeError, "is not an ArrayBuffer or a view on one", options);
      }
      if (options.allowShared && !isSharedArrayBuffer(value) && !isNonSharedArrayBuffer(value)) {
        throw makeException(TypeError, "is not an ArrayBuffer, SharedArrayBuffer, or a view on one", options);
      }
      if (isArrayBufferDetached(value)) {
        throw makeException(TypeError, "is a detached ArrayBuffer", options);
      }
      return value;
    };
    exports2.DOMTimeStamp = exports2["unsigned long long"];
  }
});

// node_modules/whatwg-url/lib/utils.js
var require_utils2 = __commonJS({
  "node_modules/whatwg-url/lib/utils.js"(exports2, module2) {
    "use strict";
    function isObject2(value) {
      return typeof value === "object" && value !== null || typeof value === "function";
    }
    var hasOwn = Function.prototype.call.bind(Object.prototype.hasOwnProperty);
    function define2(target, source) {
      for (const key of Reflect.ownKeys(source)) {
        const descriptor = Reflect.getOwnPropertyDescriptor(source, key);
        if (descriptor && !Reflect.defineProperty(target, key, descriptor)) {
          throw new TypeError(`Cannot redefine property: ${String(key)}`);
        }
      }
    }
    function newObjectInRealm(globalObject, object3) {
      const ctorRegistry = initCtorRegistry(globalObject);
      return Object.defineProperties(
        Object.create(ctorRegistry["%Object.prototype%"]),
        Object.getOwnPropertyDescriptors(object3)
      );
    }
    var wrapperSymbol = /* @__PURE__ */ Symbol("wrapper");
    var implSymbol = /* @__PURE__ */ Symbol("impl");
    var sameObjectCaches = /* @__PURE__ */ Symbol("SameObject caches");
    var ctorRegistrySymbol = /* @__PURE__ */ Symbol.for("[webidl2js] constructor registry");
    var AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {
    }).prototype);
    function initCtorRegistry(globalObject) {
      if (hasOwn(globalObject, ctorRegistrySymbol)) {
        return globalObject[ctorRegistrySymbol];
      }
      const ctorRegistry = /* @__PURE__ */ Object.create(null);
      ctorRegistry["%Object.prototype%"] = globalObject.Object.prototype;
      ctorRegistry["%IteratorPrototype%"] = Object.getPrototypeOf(
        Object.getPrototypeOf(new globalObject.Array()[Symbol.iterator]())
      );
      try {
        ctorRegistry["%AsyncIteratorPrototype%"] = Object.getPrototypeOf(
          Object.getPrototypeOf(
            globalObject.eval("(async function* () {})").prototype
          )
        );
      } catch {
        ctorRegistry["%AsyncIteratorPrototype%"] = AsyncIteratorPrototype;
      }
      globalObject[ctorRegistrySymbol] = ctorRegistry;
      return ctorRegistry;
    }
    function getSameObject(wrapper, prop, creator) {
      if (!wrapper[sameObjectCaches]) {
        wrapper[sameObjectCaches] = /* @__PURE__ */ Object.create(null);
      }
      if (prop in wrapper[sameObjectCaches]) {
        return wrapper[sameObjectCaches][prop];
      }
      wrapper[sameObjectCaches][prop] = creator();
      return wrapper[sameObjectCaches][prop];
    }
    function wrapperForImpl(impl) {
      return impl ? impl[wrapperSymbol] : null;
    }
    function implForWrapper(wrapper) {
      return wrapper ? wrapper[implSymbol] : null;
    }
    function tryWrapperForImpl(impl) {
      const wrapper = wrapperForImpl(impl);
      return wrapper ? wrapper : impl;
    }
    function tryImplForWrapper(wrapper) {
      const impl = implForWrapper(wrapper);
      return impl ? impl : wrapper;
    }
    var iterInternalSymbol = /* @__PURE__ */ Symbol("internal");
    function isArrayIndexPropName(P) {
      if (typeof P !== "string") {
        return false;
      }
      const i2 = P >>> 0;
      if (i2 === 2 ** 32 - 1) {
        return false;
      }
      const s2 = `${i2}`;
      if (P !== s2) {
        return false;
      }
      return true;
    }
    var byteLengthGetter = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
    function isArrayBuffer(value) {
      try {
        byteLengthGetter.call(value);
        return true;
      } catch (e2) {
        return false;
      }
    }
    function iteratorResult([key, value], kind) {
      let result;
      switch (kind) {
        case "key":
          result = key;
          break;
        case "value":
          result = value;
          break;
        case "key+value":
          result = [key, value];
          break;
      }
      return { value: result, done: false };
    }
    var supportsPropertyIndex = /* @__PURE__ */ Symbol("supports property index");
    var supportedPropertyIndices = /* @__PURE__ */ Symbol("supported property indices");
    var supportsPropertyName = /* @__PURE__ */ Symbol("supports property name");
    var supportedPropertyNames = /* @__PURE__ */ Symbol("supported property names");
    var indexedGet = /* @__PURE__ */ Symbol("indexed property get");
    var indexedSetNew = /* @__PURE__ */ Symbol("indexed property set new");
    var indexedSetExisting = /* @__PURE__ */ Symbol("indexed property set existing");
    var namedGet = /* @__PURE__ */ Symbol("named property get");
    var namedSetNew = /* @__PURE__ */ Symbol("named property set new");
    var namedSetExisting = /* @__PURE__ */ Symbol("named property set existing");
    var namedDelete = /* @__PURE__ */ Symbol("named property delete");
    var asyncIteratorNext = /* @__PURE__ */ Symbol("async iterator get the next iteration result");
    var asyncIteratorReturn = /* @__PURE__ */ Symbol("async iterator return steps");
    var asyncIteratorInit = /* @__PURE__ */ Symbol("async iterator initialization steps");
    var asyncIteratorEOI = /* @__PURE__ */ Symbol("async iterator end of iteration");
    module2.exports = exports2 = {
      isObject: isObject2,
      hasOwn,
      define: define2,
      newObjectInRealm,
      wrapperSymbol,
      implSymbol,
      getSameObject,
      ctorRegistrySymbol,
      initCtorRegistry,
      wrapperForImpl,
      implForWrapper,
      tryWrapperForImpl,
      tryImplForWrapper,
      iterInternalSymbol,
      isArrayBuffer,
      isArrayIndexPropName,
      supportsPropertyIndex,
      supportedPropertyIndices,
      supportsPropertyName,
      supportedPropertyNames,
      indexedGet,
      indexedSetNew,
      indexedSetExisting,
      namedGet,
      namedSetNew,
      namedSetExisting,
      namedDelete,
      asyncIteratorNext,
      asyncIteratorReturn,
      asyncIteratorInit,
      asyncIteratorEOI,
      iteratorResult
    };
  }
});

// node_modules/punycode/punycode.js
var require_punycode = __commonJS({
  "node_modules/punycode/punycode.js"(exports2, module2) {
    "use strict";
    var maxInt = 2147483647;
    var base = 36;
    var tMin = 1;
    var tMax = 26;
    var skew = 38;
    var damp = 700;
    var initialBias = 72;
    var initialN = 128;
    var delimiter = "-";
    var regexPunycode = /^xn--/;
    var regexNonASCII = /[^\0-\x7F]/;
    var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g;
    var errors = {
      "overflow": "Overflow: input needs wider integers to process",
      "not-basic": "Illegal input >= 0x80 (not a basic code point)",
      "invalid-input": "Invalid input"
    };
    var baseMinusTMin = base - tMin;
    var floor = Math.floor;
    var stringFromCharCode = String.fromCharCode;
    function error51(type) {
      throw new RangeError(errors[type]);
    }
    function map2(array2, callback) {
      const result = [];
      let length = array2.length;
      while (length--) {
        result[length] = callback(array2[length]);
      }
      return result;
    }
    function mapDomain(domain2, callback) {
      const parts = domain2.split("@");
      let result = "";
      if (parts.length > 1) {
        result = parts[0] + "@";
        domain2 = parts[1];
      }
      domain2 = domain2.replace(regexSeparators, ".");
      const labels = domain2.split(".");
      const encoded = map2(labels, callback).join(".");
      return result + encoded;
    }
    function ucs2decode(string4) {
      const output = [];
      let counter = 0;
      const length = string4.length;
      while (counter < length) {
        const value = string4.charCodeAt(counter++);
        if (value >= 55296 && value <= 56319 && counter < length) {
          const extra = string4.charCodeAt(counter++);
          if ((extra & 64512) == 56320) {
            output.push(((value & 1023) << 10) + (extra & 1023) + 65536);
          } else {
            output.push(value);
            counter--;
          }
        } else {
          output.push(value);
        }
      }
      return output;
    }
    var ucs2encode = (codePoints) => String.fromCodePoint(...codePoints);
    var basicToDigit = function(codePoint) {
      if (codePoint >= 48 && codePoint < 58) {
        return 26 + (codePoint - 48);
      }
      if (codePoint >= 65 && codePoint < 91) {
        return codePoint - 65;
      }
      if (codePoint >= 97 && codePoint < 123) {
        return codePoint - 97;
      }
      return base;
    };
    var digitToBasic = function(digit, flag) {
      return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
    };
    var adapt = function(delta, numPoints, firstTime) {
      let k = 0;
      delta = firstTime ? floor(delta / damp) : delta >> 1;
      delta += floor(delta / numPoints);
      for (; delta > baseMinusTMin * tMax >> 1; k += base) {
        delta = floor(delta / baseMinusTMin);
      }
      return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
    };
    var decode3 = function(input) {
      const output = [];
      const inputLength = input.length;
      let i2 = 0;
      let n = initialN;
      let bias = initialBias;
      let basic = input.lastIndexOf(delimiter);
      if (basic < 0) {
        basic = 0;
      }
      for (let j = 0; j < basic; ++j) {
        if (input.charCodeAt(j) >= 128) {
          error51("not-basic");
        }
        output.push(input.charCodeAt(j));
      }
      for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; ) {
        const oldi = i2;
        for (let w = 1, k = base; ; k += base) {
          if (index >= inputLength) {
            error51("invalid-input");
          }
          const digit = basicToDigit(input.charCodeAt(index++));
          if (digit >= base) {
            error51("invalid-input");
          }
          if (digit > floor((maxInt - i2) / w)) {
            error51("overflow");
          }
          i2 += digit * w;
          const t2 = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
          if (digit < t2) {
            break;
          }
          const baseMinusT = base - t2;
          if (w > floor(maxInt / baseMinusT)) {
            error51("overflow");
          }
          w *= baseMinusT;
        }
        const out = output.length + 1;
        bias = adapt(i2 - oldi, out, oldi == 0);
        if (floor(i2 / out) > maxInt - n) {
          error51("overflow");
        }
        n += floor(i2 / out);
        i2 %= out;
        output.splice(i2++, 0, n);
      }
      return String.fromCodePoint(...output);
    };
    var encode3 = function(input) {
      const output = [];
      input = ucs2decode(input);
      const inputLength = input.length;
      let n = initialN;
      let delta = 0;
      let bias = initialBias;
      for (const currentValue of input) {
        if (currentValue < 128) {
          output.push(stringFromCharCode(currentValue));
        }
      }
      const basicLength = output.length;
      let handledCPCount = basicLength;
      if (basicLength) {
        output.push(delimiter);
      }
      while (handledCPCount < inputLength) {
        let m2 = maxInt;
        for (const currentValue of input) {
          if (currentValue >= n && currentValue < m2) {
            m2 = currentValue;
          }
        }
        const handledCPCountPlusOne = handledCPCount + 1;
        if (m2 - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
          error51("overflow");
        }
        delta += (m2 - n) * handledCPCountPlusOne;
        n = m2;
        for (const currentValue of input) {
          if (currentValue < n && ++delta > maxInt) {
            error51("overflow");
          }
          if (currentValue === n) {
            let q = delta;
            for (let k = base; ; k += base) {
              const t2 = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
              if (q < t2) {
                break;
              }
              const qMinusT = q - t2;
              const baseMinusT = base - t2;
              output.push(
                stringFromCharCode(digitToBasic(t2 + qMinusT % baseMinusT, 0))
              );
              q = floor(qMinusT / baseMinusT);
            }
            output.push(stringFromCharCode(digitToBasic(q, 0)));
            bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength);
            delta = 0;
            ++handledCPCount;
          }
        }
        ++delta;
        ++n;
      }
      return output.join("");
    };
    var toUnicode = function(input) {
      return mapDomain(input, function(string4) {
        return regexPunycode.test(string4) ? decode3(string4.slice(4).toLowerCase()) : string4;
      });
    };
    var toASCII = function(input) {
      return mapDomain(input, function(string4) {
        return regexNonASCII.test(string4) ? "xn--" + encode3(string4) : string4;
      });
    };
    var punycode = {
      /**
       * A string representing the current Punycode.js version number.
       * @memberOf punycode
       * @type String
       */
      "version": "2.3.1",
      /**
       * An object of methods to convert from JavaScript's internal character
       * representation (UCS-2) to Unicode code points, and back.
       * @see <https://mathiasbynens.be/notes/javascript-encoding>
       * @memberOf punycode
       * @type Object
       */
      "ucs2": {
        "decode": ucs2decode,
        "encode": ucs2encode
      },
      "decode": decode3,
      "encode": encode3,
      "toASCII": toASCII,
      "toUnicode": toUnicode
    };
    module2.exports = punycode;
  }
});

// node_modules/tr46/lib/regexes.js
var require_regexes = __commonJS({
  "node_modules/tr46/lib/regexes.js"(exports2, module2) {
    "use strict";
    var combiningMarks = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10D69}-\u{10D6D}\u{10EAB}\u{10EAC}\u{10EFC}-\u{10EFF}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11000}-\u{11002}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11082}\u{110B0}-\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{11134}\u{11145}\u{11146}\u{11173}\u{11180}-\u{11182}\u{111B3}-\u{111C0}\u{111C9}-\u{111CC}\u{111CE}\u{111CF}\u{1122C}-\u{11237}\u{1123E}\u{11241}\u{112DF}-\u{112EA}\u{11300}-\u{11303}\u{1133B}\u{1133C}\u{1133E}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11357}\u{11362}\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{113B8}-\u{113C0}\u{113C2}\u{113C5}\u{113C7}-\u{113CA}\u{113CC}-\u{113D0}\u{113D2}\u{113E1}\u{113E2}\u{11435}-\u{11446}\u{1145E}\u{114B0}-\u{114C3}\u{115AF}-\u{115B5}\u{115B8}-\u{115C0}\u{115DC}\u{115DD}\u{11630}-\u{11640}\u{116AB}-\u{116B7}\u{1171D}-\u{1172B}\u{1182C}-\u{1183A}\u{11930}-\u{11935}\u{11937}\u{11938}\u{1193B}-\u{1193E}\u{11940}\u{11942}\u{11943}\u{119D1}-\u{119D7}\u{119DA}-\u{119E0}\u{119E4}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A39}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A5B}\u{11A8A}-\u{11A99}\u{11C2F}-\u{11C36}\u{11C38}-\u{11C3F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D8A}-\u{11D8E}\u{11D90}\u{11D91}\u{11D93}-\u{11D97}\u{11EF3}-\u{11EF6}\u{11F00}\u{11F01}\u{11F03}\u{11F34}-\u{11F3A}\u{11F3E}-\u{11F42}\u{11F5A}\u{13440}\u{13447}-\u{13455}\u{1611E}-\u{1612F}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F51}-\u{16F87}\u{16F8F}-\u{16F92}\u{16FE4}\u{16FF0}\u{16FF1}\u{1BC9D}\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D165}-\u{1D169}\u{1D16D}-\u{1D172}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E08F}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E4EC}-\u{1E4EF}\u{1E5EE}\u{1E5EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]/u;
    var combiningClassVirama = /[\u094D\u09CD\u0A4D\u0ACD\u0B4D\u0BCD\u0C4D\u0CCD\u0D3B\u0D3C\u0D4D\u0DCA\u0E3A\u0EBA\u0F84\u1039\u103A\u1714\u1715\u1734\u17D2\u1A60\u1B44\u1BAA\u1BAB\u1BF2\u1BF3\u2D7F\uA806\uA82C\uA8C4\uA953\uA9C0\uAAF6\uABED\u{10A3F}\u{11046}\u{11070}\u{1107F}\u{110B9}\u{11133}\u{11134}\u{111C0}\u{11235}\u{112EA}\u{1134D}\u{113CE}-\u{113D0}\u{11442}\u{114C2}\u{115BF}\u{1163F}\u{116B6}\u{1172B}\u{11839}\u{1193D}\u{1193E}\u{119E0}\u{11A34}\u{11A47}\u{11A99}\u{11C3F}\u{11D44}\u{11D45}\u{11D97}\u{11F41}\u{11F42}\u{1612F}]/u;
    var validZWNJ = /[\u0620\u0626\u0628\u062A-\u062E\u0633-\u063F\u0641-\u0647\u0649\u064A\u066E\u066F\u0678-\u0687\u069A-\u06BF\u06C1\u06C2\u06CC\u06CE\u06D0\u06D1\u06FA-\u06FC\u06FF\u0712-\u0714\u071A-\u071D\u071F-\u0727\u0729\u072B\u072D\u072E\u074E-\u0758\u075C-\u076A\u076D-\u0770\u0772\u0775-\u0777\u077A-\u077F\u07CA-\u07EA\u0841-\u0845\u0848\u084A-\u0853\u0855\u0860\u0862-\u0865\u0868\u0886\u0889-\u088D\u08A0-\u08A9\u08AF\u08B0\u08B3-\u08B8\u08BA-\u08C8\u1807\u1820-\u1878\u1887-\u18A8\u18AA\uA840-\uA872\u{10AC0}-\u{10AC4}\u{10ACD}\u{10AD3}-\u{10ADC}\u{10ADE}-\u{10AE0}\u{10AEB}-\u{10AEE}\u{10B80}\u{10B82}\u{10B86}-\u{10B88}\u{10B8A}\u{10B8B}\u{10B8D}\u{10B90}\u{10BAD}\u{10BAE}\u{10D00}-\u{10D21}\u{10D23}\u{10EC3}\u{10EC4}\u{10F30}-\u{10F32}\u{10F34}-\u{10F44}\u{10F51}-\u{10F53}\u{10F70}-\u{10F73}\u{10F76}-\u{10F81}\u{10FB0}\u{10FB2}\u{10FB3}\u{10FB8}\u{10FBB}\u{10FBC}\u{10FBE}\u{10FBF}\u{10FC1}\u{10FC4}\u{10FCA}\u{10FCB}\u{1E900}-\u{1E943}][\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA82C\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10D69}-\u{10D6D}\u{10EAB}\u{10EAC}\u{10EFC}-\u{10EFF}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11001}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{11241}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{113BB}-\u{113C0}\u{113CE}\u{113D0}\u{113D2}\u{113E1}\u{113E2}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{11F00}\u{11F01}\u{11F36}-\u{11F3A}\u{11F40}\u{11F42}\u{11F5A}\u{13430}-\u{13440}\u{13447}-\u{13455}\u{1611E}-\u{16129}\u{1612D}-\u{1612F}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E08F}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E4EC}-\u{1E4EF}\u{1E5EE}\u{1E5EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94B}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*\u200C[\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA82C\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10D69}-\u{10D6D}\u{10EAB}\u{10EAC}\u{10EFC}-\u{10EFF}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11001}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{11241}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{113BB}-\u{113C0}\u{113CE}\u{113D0}\u{113D2}\u{113E1}\u{113E2}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{11F00}\u{11F01}\u{11F36}-\u{11F3A}\u{11F40}\u{11F42}\u{11F5A}\u{13430}-\u{13440}\u{13447}-\u{13455}\u{1611E}-\u{16129}\u{1612D}-\u{1612F}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E08F}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E4EC}-\u{1E4EF}\u{1E5EE}\u{1E5EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94B}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*[\u0620\u0622-\u063F\u0641-\u064A\u066E\u066F\u0671-\u0673\u0675-\u06D3\u06D5\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u077F\u07CA-\u07EA\u0840-\u0858\u0860\u0862-\u0865\u0867-\u086A\u0870-\u0882\u0886\u0889-\u088E\u08A0-\u08AC\u08AE-\u08C8\u1807\u1820-\u1878\u1887-\u18A8\u18AA\uA840-\uA871\u{10AC0}-\u{10AC5}\u{10AC7}\u{10AC9}\u{10ACA}\u{10ACE}-\u{10AD6}\u{10AD8}-\u{10AE1}\u{10AE4}\u{10AEB}-\u{10AEF}\u{10B80}-\u{10B91}\u{10BA9}-\u{10BAE}\u{10D01}-\u{10D23}\u{10EC2}-\u{10EC4}\u{10F30}-\u{10F44}\u{10F51}-\u{10F54}\u{10F70}-\u{10F81}\u{10FB0}\u{10FB2}-\u{10FB6}\u{10FB8}-\u{10FBF}\u{10FC1}-\u{10FC4}\u{10FC9}\u{10FCA}\u{1E900}-\u{1E943}]/u;
    var bidiDomain = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u0870-\u088E\u0890\u0891\u08A0-\u08C9\u08E2\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10D30}-\u{10D39}\u{10D40}-\u{10D65}\u{10D6F}-\u{10D85}\u{10D8E}\u{10D8F}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10EC2}-\u{10EC4}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10F70}-\u{10F81}\u{10F86}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u;
    var bidiS1LTR = /[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u0589\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A76\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0AE6-\u0AF0\u0AF9\u0B02\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE\u0BBF\u0BC1\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7\u0BE6-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C66-\u0C6F\u0C77\u0C7F\u0C80\u0C82-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD-\u0CC4\u0CC6-\u0CC8\u0CCA\u0CCB\u0CD5\u0CD6\u0CDD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1-\u0CF3\u0D02-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D4F\u0D54-\u0D61\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E4F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F17\u0F1A-\u0F34\u0F36\u0F38\u0F3E-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u1000-\u102C\u1031\u1038\u103B\u103C\u103F-\u1057\u105A-\u105D\u1061-\u1070\u1075-\u1081\u1083\u1084\u1087-\u108C\u108E-\u109C\u109E-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u1711\u1715\u171F-\u1731\u1734-\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4C\u1B4E-\u1B6A\u1B74-\u1B7F\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u249C-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31BF\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7CD\uA7D0\uA7D1\uA7D3\uA7D5-\uA7DC\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FE\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BE-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB69\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{105C0}-\u{105F3}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11071}\u{11072}\u{11075}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11147}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C8}\u{111CD}\u{111CE}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{1123F}\u{11240}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11380}-\u{11389}\u{1138B}\u{1138E}\u{11390}-\u{113B5}\u{113B7}-\u{113BA}\u{113C2}\u{113C5}\u{113C7}-\u{113CA}\u{113CC}\u{113CD}\u{113CF}\u{113D1}\u{113D3}-\u{113D5}\u{113D7}\u{113D8}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{1145B}\u{1145D}\u{1145F}-\u{11461}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116B8}\u{116B9}\u{116C0}-\u{116C9}\u{116D0}-\u{116E3}\u{11700}-\u{1171A}\u{1171E}\u{11720}\u{11721}\u{11726}\u{11730}-\u{11746}\u{11800}-\u{1182E}\u{11838}\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193D}\u{1193F}-\u{11942}\u{11944}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D3}\u{119DC}-\u{119DF}\u{119E1}-\u{119E4}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A89}\u{11A97}\u{11A9A}-\u{11AA2}\u{11AB0}-\u{11AF8}\u{11B00}-\u{11B09}\u{11BC0}-\u{11BE1}\u{11BF0}-\u{11BF9}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D93}\u{11D94}\u{11D96}\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF2}\u{11EF5}-\u{11EF8}\u{11F02}-\u{11F10}\u{11F12}-\u{11F35}\u{11F3E}\u{11F3F}\u{11F41}\u{11F43}-\u{11F59}\u{11FB0}\u{11FC0}-\u{11FD4}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{12F90}-\u{12FF2}\u{13000}-\u{1343F}\u{13441}-\u{13446}\u{13460}-\u{143FA}\u{14400}-\u{14646}\u{16100}-\u{1611D}\u{1612A}-\u{1612C}\u{16130}-\u{16139}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}-\u{16ABE}\u{16AC0}-\u{16AC9}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16D40}-\u{16D79}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F50}-\u{16F87}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{16FE3}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18CFF}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B132}\u{1B150}-\u{1B152}\u{1B155}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1CCD6}-\u{1CCEF}\u{1CF50}-\u{1CFC3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D2C0}-\u{1D2D3}\u{1D2E0}-\u{1D2F3}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6C0}\u{1D6C2}-\u{1D6DA}\u{1D6DC}-\u{1D6FA}\u{1D6FC}-\u{1D714}\u{1D716}-\u{1D734}\u{1D736}-\u{1D74E}\u{1D750}-\u{1D76E}\u{1D770}-\u{1D788}\u{1D78A}-\u{1D7A8}\u{1D7AA}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D800}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1DF00}-\u{1DF1E}\u{1DF25}-\u{1DF2A}\u{1E030}-\u{1E06D}\u{1E100}-\u{1E12C}\u{1E137}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E290}-\u{1E2AD}\u{1E2C0}-\u{1E2EB}\u{1E2F0}-\u{1E2F9}\u{1E4D0}-\u{1E4EB}\u{1E4F0}-\u{1E4F9}\u{1E5D0}-\u{1E5ED}\u{1E5F0}-\u{1E5FA}\u{1E5FF}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B739}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2EBF0}-\u{2EE5D}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{31350}-\u{323AF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/u;
    var bidiS1RTL = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0608\u060B\u060D\u061B-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u0870-\u088E\u08A0-\u08C9\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10D4A}-\u{10D65}\u{10D6F}-\u{10D85}\u{10D8E}\u{10D8F}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10EC2}-\u{10EC4}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10F70}-\u{10F81}\u{10F86}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u;
    var bidiS2 = /^[\0-\x08\x0E-\x1B!-@\[-`\{-\x84\x86-\xA9\xAB-\xB4\xB6-\xB9\xBB-\xBF\xD7\xF7\u02B9\u02BA\u02C2-\u02CF\u02D2-\u02DF\u02E5-\u02ED\u02EF-\u036F\u0374\u0375\u037E\u0384\u0385\u0387\u03F6\u0483-\u0489\u058A\u058D-\u058F\u0591-\u05C7\u05D0-\u05EA\u05EF-\u05F4\u0600-\u070D\u070F-\u074A\u074D-\u07B1\u07C0-\u07FA\u07FD-\u082D\u0830-\u083E\u0840-\u085B\u085E\u0860-\u086A\u0870-\u088E\u0890\u0891\u0897-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09F2\u09F3\u09FB\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AF1\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0BF3-\u0BFA\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C78-\u0C7E\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E3F\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0F18\u0F19\u0F35\u0F37\u0F39-\u0F3D\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1390-\u1399\u1400\u169B\u169C\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DB\u17DD\u17F0-\u17F9\u1800-\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1940\u1944\u1945\u19DE-\u19FF\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u200B-\u200D\u200F-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2070\u2074-\u207E\u2080-\u208E\u20A0-\u20C0\u20D0-\u20F0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u2150-\u215F\u2189-\u218B\u2190-\u2335\u237B-\u2394\u2396-\u2429\u2440-\u244A\u2460-\u249B\u24EA-\u26AB\u26AD-\u27FF\u2900-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2CEF-\u2CF1\u2CF9-\u2CFF\u2D7F\u2DE0-\u2E5D\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3001-\u3004\u3008-\u3020\u302A-\u302D\u3030\u3036\u3037\u303D-\u303F\u3099-\u309C\u30A0\u30FB\u31C0-\u31E5\u31EF\u321D\u321E\u3250-\u325F\u327C-\u327E\u32B1-\u32BF\u32CC-\u32CF\u3377-\u337A\u33DE\u33DF\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA60D-\uA60F\uA66F-\uA67F\uA69E\uA69F\uA6F0\uA6F1\uA700-\uA721\uA788\uA802\uA806\uA80B\uA825\uA826\uA828-\uA82C\uA838\uA839\uA874-\uA877\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uAB6A\uAB6B\uABE5\uABE8\uABED\uFB1D-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD8F\uFD92-\uFDC7\uFDCF\uFDF0-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFE70-\uFE74\uFE76-\uFEFC\uFEFF\uFF01-\uFF20\uFF3B-\uFF40\uFF5B-\uFF65\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10101}\u{10140}-\u{1018C}\u{10190}-\u{1019C}\u{101A0}\u{101FD}\u{102E0}-\u{102FB}\u{10376}-\u{1037A}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{1091F}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A38}-\u{10A3A}\u{10A3F}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE6}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B39}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D27}\u{10D30}-\u{10D39}\u{10D40}-\u{10D65}\u{10D69}-\u{10D85}\u{10D8E}\u{10D8F}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAB}-\u{10EAD}\u{10EB0}\u{10EB1}\u{10EC2}-\u{10EC4}\u{10EFC}-\u{10F27}\u{10F30}-\u{10F59}\u{10F70}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{11001}\u{11038}-\u{11046}\u{11052}-\u{11065}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{11241}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{113BB}-\u{113C0}\u{113CE}\u{113D0}\u{113D2}\u{113E1}\u{113E2}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{11660}-\u{1166C}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{11F00}\u{11F01}\u{11F36}-\u{11F3A}\u{11F40}\u{11F42}\u{11F5A}\u{11FD5}-\u{11FF1}\u{13440}\u{13447}-\u{13455}\u{1611E}-\u{16129}\u{1612D}-\u{1612F}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE2}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1CC00}-\u{1CCD5}\u{1CCF0}-\u{1CCF9}\u{1CD00}-\u{1CEB3}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D1E9}\u{1D1EA}\u{1D200}-\u{1D245}\u{1D300}-\u{1D356}\u{1D6C1}\u{1D6DB}\u{1D6FB}\u{1D715}\u{1D735}\u{1D74F}\u{1D76F}\u{1D789}\u{1D7A9}\u{1D7C3}\u{1D7CE}-\u{1D7FF}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E08F}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E2FF}\u{1E4EC}-\u{1E4EF}\u{1E5EE}\u{1E5EF}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8D6}\u{1E900}-\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F100}-\u{1F10F}\u{1F12F}\u{1F16A}-\u{1F16F}\u{1F1AD}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D7}\u{1F6DC}-\u{1F6EC}\u{1F6F0}-\u{1F6FC}\u{1F700}-\u{1F776}\u{1F77B}-\u{1F7D9}\u{1F7E0}-\u{1F7EB}\u{1F7F0}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F8B0}-\u{1F8BB}\u{1F8C0}\u{1F8C1}\u{1F900}-\u{1FA53}\u{1FA60}-\u{1FA6D}\u{1FA70}-\u{1FA7C}\u{1FA80}-\u{1FA89}\u{1FA8F}-\u{1FAC6}\u{1FACE}-\u{1FADC}\u{1FADF}-\u{1FAE9}\u{1FAF0}-\u{1FAF8}\u{1FB00}-\u{1FB92}\u{1FB94}-\u{1FBF9}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*$/u;
    var bidiS3 = /[0-9\xB2\xB3\xB9\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u0870-\u088E\u0890\u0891\u08A0-\u08C9\u08E2\u200F\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\u{102E1}-\u{102FB}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10D30}-\u{10D39}\u{10D40}-\u{10D65}\u{10D6F}-\u{10D85}\u{10D8E}\u{10D8F}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10EC2}-\u{10EC4}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10F70}-\u{10F81}\u{10F86}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1CCF0}-\u{1CCF9}\u{1D7CE}-\u{1D7FF}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{1F100}-\u{1F10A}\u{1FBF0}-\u{1FBF9}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA82C\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10D69}-\u{10D6D}\u{10EAB}\u{10EAC}\u{10EFC}-\u{10EFF}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11001}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{11241}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{113BB}-\u{113C0}\u{113CE}\u{113D0}\u{113D2}\u{113E1}\u{113E2}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{11F00}\u{11F01}\u{11F36}-\u{11F3A}\u{11F40}\u{11F42}\u{11F5A}\u{13440}\u{13447}-\u{13455}\u{1611E}-\u{16129}\u{1612D}-\u{1612F}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E08F}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E4EC}-\u{1E4EF}\u{1E5EE}\u{1E5EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u;
    var bidiS4EN = /[0-9\xB2\xB3\xB9\u06F0-\u06F9\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFF10-\uFF19\u{102E1}-\u{102FB}\u{1CCF0}-\u{1CCF9}\u{1D7CE}-\u{1D7FF}\u{1F100}-\u{1F10A}\u{1FBF0}-\u{1FBF9}]/u;
    var bidiS4AN = /[\u0600-\u0605\u0660-\u0669\u066B\u066C\u06DD\u0890\u0891\u08E2\u{10D30}-\u{10D39}\u{10D40}-\u{10D49}\u{10E60}-\u{10E7E}]/u;
    var bidiS5 = /^[\0-\x08\x0E-\x1B!-\x84\x86-\u0377\u037A-\u037F\u0384-\u038A\u038C\u038E-\u03A1\u03A3-\u052F\u0531-\u0556\u0559-\u058A\u058D-\u058F\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0606\u0607\u0609\u060A\u060C\u060E-\u061A\u064B-\u065F\u066A\u0670\u06D6-\u06DC\u06DE-\u06E4\u06E7-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07F6-\u07F9\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09FE\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A76\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AF1\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B77\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BFA\u0C00-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3C-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C5D\u0C60-\u0C63\u0C66-\u0C6F\u0C77-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDD\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1-\u0CF3\u0D00-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4F\u0D54-\u0D63\u0D66-\u0D7F\u0D81-\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E3A\u0E3F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECE\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F47\u0F49-\u0F6C\u0F71-\u0F97\u0F99-\u0FBC\u0FBE-\u0FCC\u0FCE-\u0FDA\u1000-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u137C\u1380-\u1399\u13A0-\u13F5\u13F8-\u13FD\u1400-\u167F\u1681-\u169C\u16A0-\u16F8\u1700-\u1715\u171F-\u1736\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17DD\u17E0-\u17E9\u17F0-\u17F9\u1800-\u1819\u1820-\u1878\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1940\u1944-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u19DE-\u1A1B\u1A1E-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1AB0-\u1ACE\u1B00-\u1B4C\u1B4E-\u1BF3\u1BFC-\u1C37\u1C3B-\u1C49\u1C4D-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD0-\u1CFA\u1D00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FC4\u1FC6-\u1FD3\u1FD6-\u1FDB\u1FDD-\u1FEF\u1FF2-\u1FF4\u1FF6-\u1FFE\u200B-\u200E\u2010-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2071\u2074-\u208E\u2090-\u209C\u20A0-\u20C0\u20D0-\u20F0\u2100-\u218B\u2190-\u2429\u2440-\u244A\u2460-\u2B73\u2B76-\u2B95\u2B97-\u2CF3\u2CF9-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2E5D\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3001-\u303F\u3041-\u3096\u3099-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31E5\u31EF-\u321E\u3220-\uA48C\uA490-\uA4C6\uA4D0-\uA62B\uA640-\uA6F7\uA700-\uA7CD\uA7D0\uA7D1\uA7D3\uA7D5-\uA7DC\uA7F2-\uA82C\uA830-\uA839\uA840-\uA877\uA880-\uA8C5\uA8CE-\uA8D9\uA8E0-\uA953\uA95F-\uA97C\uA980-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA5C-\uAAC2\uAADB-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB6B\uAB70-\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1E\uFB29\uFD3E-\uFD4F\uFDCF\uFDFD-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFEFF\uFF01-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}-\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1018E}\u{10190}-\u{1019C}\u{101A0}\u{101D0}-\u{101FD}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E0}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{1037A}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{105C0}-\u{105F3}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{1091F}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10B39}-\u{10B3F}\u{10D24}-\u{10D27}\u{10D69}-\u{10D6E}\u{10EAB}\u{10EAC}\u{10EFC}-\u{10EFF}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11000}-\u{1104D}\u{11052}-\u{11075}\u{1107F}-\u{110C2}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11100}-\u{11134}\u{11136}-\u{11147}\u{11150}-\u{11176}\u{11180}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{11241}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112EA}\u{112F0}-\u{112F9}\u{11300}-\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133B}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11380}-\u{11389}\u{1138B}\u{1138E}\u{11390}-\u{113B5}\u{113B7}-\u{113C0}\u{113C2}\u{113C5}\u{113C7}-\u{113CA}\u{113CC}-\u{113D5}\u{113D7}\u{113D8}\u{113E1}\u{113E2}\u{11400}-\u{1145B}\u{1145D}-\u{11461}\u{11480}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B5}\u{115B8}-\u{115DD}\u{11600}-\u{11644}\u{11650}-\u{11659}\u{11660}-\u{1166C}\u{11680}-\u{116B9}\u{116C0}-\u{116C9}\u{116D0}-\u{116E3}\u{11700}-\u{1171A}\u{1171D}-\u{1172B}\u{11730}-\u{11746}\u{11800}-\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193B}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D7}\u{119DA}-\u{119E4}\u{11A00}-\u{11A47}\u{11A50}-\u{11AA2}\u{11AB0}-\u{11AF8}\u{11B00}-\u{11B09}\u{11BC0}-\u{11BE1}\u{11BF0}-\u{11BF9}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C36}\u{11C38}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D47}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D90}\u{11D91}\u{11D93}-\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF8}\u{11F00}-\u{11F10}\u{11F12}-\u{11F3A}\u{11F3E}-\u{11F5A}\u{11FB0}\u{11FC0}-\u{11FF1}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{12F90}-\u{12FF2}\u{13000}-\u{13455}\u{13460}-\u{143FA}\u{14400}-\u{14646}\u{16100}-\u{16139}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}-\u{16ABE}\u{16AC0}-\u{16AC9}\u{16AD0}-\u{16AED}\u{16AF0}-\u{16AF5}\u{16B00}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16D40}-\u{16D79}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F4F}-\u{16F87}\u{16F8F}-\u{16F9F}\u{16FE0}-\u{16FE4}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18CFF}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B132}\u{1B150}-\u{1B152}\u{1B155}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}-\u{1BCA3}\u{1CC00}-\u{1CCF9}\u{1CD00}-\u{1CEB3}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1CF50}-\u{1CFC3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D1EA}\u{1D200}-\u{1D245}\u{1D2C0}-\u{1D2D3}\u{1D2E0}-\u{1D2F3}\u{1D300}-\u{1D356}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D7CB}\u{1D7CE}-\u{1DA8B}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1DF00}-\u{1DF1E}\u{1DF25}-\u{1DF2A}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E030}-\u{1E06D}\u{1E08F}\u{1E100}-\u{1E12C}\u{1E130}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E290}-\u{1E2AE}\u{1E2C0}-\u{1E2F9}\u{1E2FF}\u{1E4D0}-\u{1E4F9}\u{1E5D0}-\u{1E5FA}\u{1E5FF}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F100}-\u{1F1AD}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D7}\u{1F6DC}-\u{1F6EC}\u{1F6F0}-\u{1F6FC}\u{1F700}-\u{1F776}\u{1F77B}-\u{1F7D9}\u{1F7E0}-\u{1F7EB}\u{1F7F0}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F8B0}-\u{1F8BB}\u{1F8C0}\u{1F8C1}\u{1F900}-\u{1FA53}\u{1FA60}-\u{1FA6D}\u{1FA70}-\u{1FA7C}\u{1FA80}-\u{1FA89}\u{1FA8F}-\u{1FAC6}\u{1FACE}-\u{1FADC}\u{1FADF}-\u{1FAE9}\u{1FAF0}-\u{1FAF8}\u{1FB00}-\u{1FB92}\u{1FB94}-\u{1FBF9}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B739}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2EBF0}-\u{2EE5D}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{31350}-\u{323AF}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]*$/u;
    var bidiS6 = /[0-9A-Za-z\xAA\xB2\xB3\xB5\xB9\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u0589\u06F0-\u06F9\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A76\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0AE6-\u0AF0\u0AF9\u0B02\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE\u0BBF\u0BC1\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7\u0BE6-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C66-\u0C6F\u0C77\u0C7F\u0C80\u0C82-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD-\u0CC4\u0CC6-\u0CC8\u0CCA\u0CCB\u0CD5\u0CD6\u0CDD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1-\u0CF3\u0D02-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D4F\u0D54-\u0D61\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E4F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F17\u0F1A-\u0F34\u0F36\u0F38\u0F3E-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u1000-\u102C\u1031\u1038\u103B\u103C\u103F-\u1057\u105A-\u105D\u1061-\u1070\u1075-\u1081\u1083\u1084\u1087-\u108C\u108E-\u109C\u109E-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u1711\u1715\u171F-\u1731\u1734-\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4C\u1B4E-\u1B6A\u1B74-\u1B7F\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2070\u2071\u2074-\u2079\u207F-\u2089\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u2488-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31BF\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7CD\uA7D0\uA7D1\uA7D3\uA7D5-\uA7DC\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FE\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BE-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB69\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E1}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{105C0}-\u{105F3}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11071}\u{11072}\u{11075}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11147}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C8}\u{111CD}\u{111CE}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{1123F}\u{11240}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11380}-\u{11389}\u{1138B}\u{1138E}\u{11390}-\u{113B5}\u{113B7}-\u{113BA}\u{113C2}\u{113C5}\u{113C7}-\u{113CA}\u{113CC}\u{113CD}\u{113CF}\u{113D1}\u{113D3}-\u{113D5}\u{113D7}\u{113D8}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{1145B}\u{1145D}\u{1145F}-\u{11461}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116B8}\u{116B9}\u{116C0}-\u{116C9}\u{116D0}-\u{116E3}\u{11700}-\u{1171A}\u{1171E}\u{11720}\u{11721}\u{11726}\u{11730}-\u{11746}\u{11800}-\u{1182E}\u{11838}\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193D}\u{1193F}-\u{11942}\u{11944}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D3}\u{119DC}-\u{119DF}\u{119E1}-\u{119E4}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A89}\u{11A97}\u{11A9A}-\u{11AA2}\u{11AB0}-\u{11AF8}\u{11B00}-\u{11B09}\u{11BC0}-\u{11BE1}\u{11BF0}-\u{11BF9}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D93}\u{11D94}\u{11D96}\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF2}\u{11EF5}-\u{11EF8}\u{11F02}-\u{11F10}\u{11F12}-\u{11F35}\u{11F3E}\u{11F3F}\u{11F41}\u{11F43}-\u{11F59}\u{11FB0}\u{11FC0}-\u{11FD4}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{12F90}-\u{12FF2}\u{13000}-\u{1343F}\u{13441}-\u{13446}\u{13460}-\u{143FA}\u{14400}-\u{14646}\u{16100}-\u{1611D}\u{1612A}-\u{1612C}\u{16130}-\u{16139}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}-\u{16ABE}\u{16AC0}-\u{16AC9}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16D40}-\u{16D79}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F50}-\u{16F87}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{16FE3}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18CFF}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B132}\u{1B150}-\u{1B152}\u{1B155}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1CCD6}-\u{1CCF9}\u{1CF50}-\u{1CFC3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D2C0}-\u{1D2D3}\u{1D2E0}-\u{1D2F3}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6C0}\u{1D6C2}-\u{1D6DA}\u{1D6DC}-\u{1D6FA}\u{1D6FC}-\u{1D714}\u{1D716}-\u{1D734}\u{1D736}-\u{1D74E}\u{1D750}-\u{1D76E}\u{1D770}-\u{1D788}\u{1D78A}-\u{1D7A8}\u{1D7AA}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D7CE}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1DF00}-\u{1DF1E}\u{1DF25}-\u{1DF2A}\u{1E030}-\u{1E06D}\u{1E100}-\u{1E12C}\u{1E137}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E290}-\u{1E2AD}\u{1E2C0}-\u{1E2EB}\u{1E2F0}-\u{1E2F9}\u{1E4D0}-\u{1E4EB}\u{1E4F0}-\u{1E4F9}\u{1E5D0}-\u{1E5ED}\u{1E5F0}-\u{1E5FA}\u{1E5FF}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1F100}-\u{1F10A}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{1FBF0}-\u{1FBF9}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B739}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2EBF0}-\u{2EE5D}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{31350}-\u{323AF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA82C\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10D69}-\u{10D6D}\u{10EAB}\u{10EAC}\u{10EFC}-\u{10EFF}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11001}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{11241}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{113BB}-\u{113C0}\u{113CE}\u{113D0}\u{113D2}\u{113E1}\u{113E2}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{11F00}\u{11F01}\u{11F36}-\u{11F3A}\u{11F40}\u{11F42}\u{11F5A}\u{13440}\u{13447}-\u{13455}\u{1611E}-\u{16129}\u{1612D}-\u{1612F}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E08F}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E4EC}-\u{1E4EF}\u{1E5EE}\u{1E5EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u;
    module2.exports = {
      combiningMarks,
      combiningClassVirama,
      validZWNJ,
      bidiDomain,
      bidiS1LTR,
      bidiS1RTL,
      bidiS2,
      bidiS3,
      bidiS4EN,
      bidiS4AN,
      bidiS5,
      bidiS6
    };
  }
});

// node_modules/tr46/lib/mappingTable.json
var require_mappingTable = __commonJS({
  "node_modules/tr46/lib/mappingTable.json"(exports2, module2) {
    module2.exports = [[[0, 44], 2], [[45, 46], 2], [47, 2], [[48, 57], 2], [[58, 64], 2], [65, 1, "a"], [66, 1, "b"], [67, 1, "c"], [68, 1, "d"], [69, 1, "e"], [70, 1, "f"], [71, 1, "g"], [72, 1, "h"], [73, 1, "i"], [74, 1, "j"], [75, 1, "k"], [76, 1, "l"], [77, 1, "m"], [78, 1, "n"], [79, 1, "o"], [80, 1, "p"], [81, 1, "q"], [82, 1, "r"], [83, 1, "s"], [84, 1, "t"], [85, 1, "u"], [86, 1, "v"], [87, 1, "w"], [88, 1, "x"], [89, 1, "y"], [90, 1, "z"], [[91, 96], 2], [[97, 122], 2], [[123, 127], 2], [[128, 159], 3], [160, 1, " "], [[161, 167], 2], [168, 1, " \u0308"], [169, 2], [170, 1, "a"], [[171, 172], 2], [173, 7], [174, 2], [175, 1, " \u0304"], [[176, 177], 2], [178, 1, "2"], [179, 1, "3"], [180, 1, " \u0301"], [181, 1, "\u03BC"], [182, 2], [183, 2], [184, 1, " \u0327"], [185, 1, "1"], [186, 1, "o"], [187, 2], [188, 1, "1\u20444"], [189, 1, "1\u20442"], [190, 1, "3\u20444"], [191, 2], [192, 1, "\xE0"], [193, 1, "\xE1"], [194, 1, "\xE2"], [195, 1, "\xE3"], [196, 1, "\xE4"], [197, 1, "\xE5"], [198, 1, "\xE6"], [199, 1, "\xE7"], [200, 1, "\xE8"], [201, 1, "\xE9"], [202, 1, "\xEA"], [203, 1, "\xEB"], [204, 1, "\xEC"], [205, 1, "\xED"], [206, 1, "\xEE"], [207, 1, "\xEF"], [208, 1, "\xF0"], [209, 1, "\xF1"], [210, 1, "\xF2"], [211, 1, "\xF3"], [212, 1, "\xF4"], [213, 1, "\xF5"], [214, 1, "\xF6"], [215, 2], [216, 1, "\xF8"], [217, 1, "\xF9"], [218, 1, "\xFA"], [219, 1, "\xFB"], [220, 1, "\xFC"], [221, 1, "\xFD"], [222, 1, "\xFE"], [223, 6, "ss"], [[224, 246], 2], [247, 2], [[248, 255], 2], [256, 1, "\u0101"], [257, 2], [258, 1, "\u0103"], [259, 2], [260, 1, "\u0105"], [261, 2], [262, 1, "\u0107"], [263, 2], [264, 1, "\u0109"], [265, 2], [266, 1, "\u010B"], [267, 2], [268, 1, "\u010D"], [269, 2], [270, 1, "\u010F"], [271, 2], [272, 1, "\u0111"], [273, 2], [274, 1, "\u0113"], [275, 2], [276, 1, "\u0115"], [277, 2], [278, 1, "\u0117"], [279, 2], [280, 1, "\u0119"], [281, 2], [282, 1, "\u011B"], [283, 2], [284, 1, "\u011D"], [285, 2], [286, 1, "\u011F"], [287, 2], [288, 1, "\u0121"], [289, 2], [290, 1, "\u0123"], [291, 2], [292, 1, "\u0125"], [293, 2], [294, 1, "\u0127"], [295, 2], [296, 1, "\u0129"], [297, 2], [298, 1, "\u012B"], [299, 2], [300, 1, "\u012D"], [301, 2], [302, 1, "\u012F"], [303, 2], [304, 1, "i\u0307"], [305, 2], [[306, 307], 1, "ij"], [308, 1, "\u0135"], [309, 2], [310, 1, "\u0137"], [[311, 312], 2], [313, 1, "\u013A"], [314, 2], [315, 1, "\u013C"], [316, 2], [317, 1, "\u013E"], [318, 2], [[319, 320], 1, "l\xB7"], [321, 1, "\u0142"], [322, 2], [323, 1, "\u0144"], [324, 2], [325, 1, "\u0146"], [326, 2], [327, 1, "\u0148"], [328, 2], [329, 1, "\u02BCn"], [330, 1, "\u014B"], [331, 2], [332, 1, "\u014D"], [333, 2], [334, 1, "\u014F"], [335, 2], [336, 1, "\u0151"], [337, 2], [338, 1, "\u0153"], [339, 2], [340, 1, "\u0155"], [341, 2], [342, 1, "\u0157"], [343, 2], [344, 1, "\u0159"], [345, 2], [346, 1, "\u015B"], [347, 2], [348, 1, "\u015D"], [349, 2], [350, 1, "\u015F"], [351, 2], [352, 1, "\u0161"], [353, 2], [354, 1, "\u0163"], [355, 2], [356, 1, "\u0165"], [357, 2], [358, 1, "\u0167"], [359, 2], [360, 1, "\u0169"], [361, 2], [362, 1, "\u016B"], [363, 2], [364, 1, "\u016D"], [365, 2], [366, 1, "\u016F"], [367, 2], [368, 1, "\u0171"], [369, 2], [370, 1, "\u0173"], [371, 2], [372, 1, "\u0175"], [373, 2], [374, 1, "\u0177"], [375, 2], [376, 1, "\xFF"], [377, 1, "\u017A"], [378, 2], [379, 1, "\u017C"], [380, 2], [381, 1, "\u017E"], [382, 2], [383, 1, "s"], [384, 2], [385, 1, "\u0253"], [386, 1, "\u0183"], [387, 2], [388, 1, "\u0185"], [389, 2], [390, 1, "\u0254"], [391, 1, "\u0188"], [392, 2], [393, 1, "\u0256"], [394, 1, "\u0257"], [395, 1, "\u018C"], [[396, 397], 2], [398, 1, "\u01DD"], [399, 1, "\u0259"], [400, 1, "\u025B"], [401, 1, "\u0192"], [402, 2], [403, 1, "\u0260"], [404, 1, "\u0263"], [405, 2], [406, 1, "\u0269"], [407, 1, "\u0268"], [408, 1, "\u0199"], [[409, 411], 2], [412, 1, "\u026F"], [413, 1, "\u0272"], [414, 2], [415, 1, "\u0275"], [416, 1, "\u01A1"], [417, 2], [418, 1, "\u01A3"], [419, 2], [420, 1, "\u01A5"], [421, 2], [422, 1, "\u0280"], [423, 1, "\u01A8"], [424, 2], [425, 1, "\u0283"], [[426, 427], 2], [428, 1, "\u01AD"], [429, 2], [430, 1, "\u0288"], [431, 1, "\u01B0"], [432, 2], [433, 1, "\u028A"], [434, 1, "\u028B"], [435, 1, "\u01B4"], [436, 2], [437, 1, "\u01B6"], [438, 2], [439, 1, "\u0292"], [440, 1, "\u01B9"], [[441, 443], 2], [444, 1, "\u01BD"], [[445, 451], 2], [[452, 454], 1, "d\u017E"], [[455, 457], 1, "lj"], [[458, 460], 1, "nj"], [461, 1, "\u01CE"], [462, 2], [463, 1, "\u01D0"], [464, 2], [465, 1, "\u01D2"], [466, 2], [467, 1, "\u01D4"], [468, 2], [469, 1, "\u01D6"], [470, 2], [471, 1, "\u01D8"], [472, 2], [473, 1, "\u01DA"], [474, 2], [475, 1, "\u01DC"], [[476, 477], 2], [478, 1, "\u01DF"], [479, 2], [480, 1, "\u01E1"], [481, 2], [482, 1, "\u01E3"], [483, 2], [484, 1, "\u01E5"], [485, 2], [486, 1, "\u01E7"], [487, 2], [488, 1, "\u01E9"], [489, 2], [490, 1, "\u01EB"], [491, 2], [492, 1, "\u01ED"], [493, 2], [494, 1, "\u01EF"], [[495, 496], 2], [[497, 499], 1, "dz"], [500, 1, "\u01F5"], [501, 2], [502, 1, "\u0195"], [503, 1, "\u01BF"], [504, 1, "\u01F9"], [505, 2], [506, 1, "\u01FB"], [507, 2], [508, 1, "\u01FD"], [509, 2], [510, 1, "\u01FF"], [511, 2], [512, 1, "\u0201"], [513, 2], [514, 1, "\u0203"], [515, 2], [516, 1, "\u0205"], [517, 2], [518, 1, "\u0207"], [519, 2], [520, 1, "\u0209"], [521, 2], [522, 1, "\u020B"], [523, 2], [524, 1, "\u020D"], [525, 2], [526, 1, "\u020F"], [527, 2], [528, 1, "\u0211"], [529, 2], [530, 1, "\u0213"], [531, 2], [532, 1, "\u0215"], [533, 2], [534, 1, "\u0217"], [535, 2], [536, 1, "\u0219"], [537, 2], [538, 1, "\u021B"], [539, 2], [540, 1, "\u021D"], [541, 2], [542, 1, "\u021F"], [543, 2], [544, 1, "\u019E"], [545, 2], [546, 1, "\u0223"], [547, 2], [548, 1, "\u0225"], [549, 2], [550, 1, "\u0227"], [551, 2], [552, 1, "\u0229"], [553, 2], [554, 1, "\u022B"], [555, 2], [556, 1, "\u022D"], [557, 2], [558, 1, "\u022F"], [559, 2], [560, 1, "\u0231"], [561, 2], [562, 1, "\u0233"], [563, 2], [[564, 566], 2], [[567, 569], 2], [570, 1, "\u2C65"], [571, 1, "\u023C"], [572, 2], [573, 1, "\u019A"], [574, 1, "\u2C66"], [[575, 576], 2], [577, 1, "\u0242"], [578, 2], [579, 1, "\u0180"], [580, 1, "\u0289"], [581, 1, "\u028C"], [582, 1, "\u0247"], [583, 2], [584, 1, "\u0249"], [585, 2], [586, 1, "\u024B"], [587, 2], [588, 1, "\u024D"], [589, 2], [590, 1, "\u024F"], [591, 2], [[592, 680], 2], [[681, 685], 2], [[686, 687], 2], [688, 1, "h"], [689, 1, "\u0266"], [690, 1, "j"], [691, 1, "r"], [692, 1, "\u0279"], [693, 1, "\u027B"], [694, 1, "\u0281"], [695, 1, "w"], [696, 1, "y"], [[697, 705], 2], [[706, 709], 2], [[710, 721], 2], [[722, 727], 2], [728, 1, " \u0306"], [729, 1, " \u0307"], [730, 1, " \u030A"], [731, 1, " \u0328"], [732, 1, " \u0303"], [733, 1, " \u030B"], [734, 2], [735, 2], [736, 1, "\u0263"], [737, 1, "l"], [738, 1, "s"], [739, 1, "x"], [740, 1, "\u0295"], [[741, 745], 2], [[746, 747], 2], [748, 2], [749, 2], [750, 2], [[751, 767], 2], [[768, 831], 2], [832, 1, "\u0300"], [833, 1, "\u0301"], [834, 2], [835, 1, "\u0313"], [836, 1, "\u0308\u0301"], [837, 1, "\u03B9"], [[838, 846], 2], [847, 7], [[848, 855], 2], [[856, 860], 2], [[861, 863], 2], [[864, 865], 2], [866, 2], [[867, 879], 2], [880, 1, "\u0371"], [881, 2], [882, 1, "\u0373"], [883, 2], [884, 1, "\u02B9"], [885, 2], [886, 1, "\u0377"], [887, 2], [[888, 889], 3], [890, 1, " \u03B9"], [[891, 893], 2], [894, 1, ";"], [895, 1, "\u03F3"], [[896, 899], 3], [900, 1, " \u0301"], [901, 1, " \u0308\u0301"], [902, 1, "\u03AC"], [903, 1, "\xB7"], [904, 1, "\u03AD"], [905, 1, "\u03AE"], [906, 1, "\u03AF"], [907, 3], [908, 1, "\u03CC"], [909, 3], [910, 1, "\u03CD"], [911, 1, "\u03CE"], [912, 2], [913, 1, "\u03B1"], [914, 1, "\u03B2"], [915, 1, "\u03B3"], [916, 1, "\u03B4"], [917, 1, "\u03B5"], [918, 1, "\u03B6"], [919, 1, "\u03B7"], [920, 1, "\u03B8"], [921, 1, "\u03B9"], [922, 1, "\u03BA"], [923, 1, "\u03BB"], [924, 1, "\u03BC"], [925, 1, "\u03BD"], [926, 1, "\u03BE"], [927, 1, "\u03BF"], [928, 1, "\u03C0"], [929, 1, "\u03C1"], [930, 3], [931, 1, "\u03C3"], [932, 1, "\u03C4"], [933, 1, "\u03C5"], [934, 1, "\u03C6"], [935, 1, "\u03C7"], [936, 1, "\u03C8"], [937, 1, "\u03C9"], [938, 1, "\u03CA"], [939, 1, "\u03CB"], [[940, 961], 2], [962, 6, "\u03C3"], [[963, 974], 2], [975, 1, "\u03D7"], [976, 1, "\u03B2"], [977, 1, "\u03B8"], [978, 1, "\u03C5"], [979, 1, "\u03CD"], [980, 1, "\u03CB"], [981, 1, "\u03C6"], [982, 1, "\u03C0"], [983, 2], [984, 1, "\u03D9"], [985, 2], [986, 1, "\u03DB"], [987, 2], [988, 1, "\u03DD"], [989, 2], [990, 1, "\u03DF"], [991, 2], [992, 1, "\u03E1"], [993, 2], [994, 1, "\u03E3"], [995, 2], [996, 1, "\u03E5"], [997, 2], [998, 1, "\u03E7"], [999, 2], [1e3, 1, "\u03E9"], [1001, 2], [1002, 1, "\u03EB"], [1003, 2], [1004, 1, "\u03ED"], [1005, 2], [1006, 1, "\u03EF"], [1007, 2], [1008, 1, "\u03BA"], [1009, 1, "\u03C1"], [1010, 1, "\u03C3"], [1011, 2], [1012, 1, "\u03B8"], [1013, 1, "\u03B5"], [1014, 2], [1015, 1, "\u03F8"], [1016, 2], [1017, 1, "\u03C3"], [1018, 1, "\u03FB"], [1019, 2], [1020, 2], [1021, 1, "\u037B"], [1022, 1, "\u037C"], [1023, 1, "\u037D"], [1024, 1, "\u0450"], [1025, 1, "\u0451"], [1026, 1, "\u0452"], [1027, 1, "\u0453"], [1028, 1, "\u0454"], [1029, 1, "\u0455"], [1030, 1, "\u0456"], [1031, 1, "\u0457"], [1032, 1, "\u0458"], [1033, 1, "\u0459"], [1034, 1, "\u045A"], [1035, 1, "\u045B"], [1036, 1, "\u045C"], [1037, 1, "\u045D"], [1038, 1, "\u045E"], [1039, 1, "\u045F"], [1040, 1, "\u0430"], [1041, 1, "\u0431"], [1042, 1, "\u0432"], [1043, 1, "\u0433"], [1044, 1, "\u0434"], [1045, 1, "\u0435"], [1046, 1, "\u0436"], [1047, 1, "\u0437"], [1048, 1, "\u0438"], [1049, 1, "\u0439"], [1050, 1, "\u043A"], [1051, 1, "\u043B"], [1052, 1, "\u043C"], [1053, 1, "\u043D"], [1054, 1, "\u043E"], [1055, 1, "\u043F"], [1056, 1, "\u0440"], [1057, 1, "\u0441"], [1058, 1, "\u0442"], [1059, 1, "\u0443"], [1060, 1, "\u0444"], [1061, 1, "\u0445"], [1062, 1, "\u0446"], [1063, 1, "\u0447"], [1064, 1, "\u0448"], [1065, 1, "\u0449"], [1066, 1, "\u044A"], [1067, 1, "\u044B"], [1068, 1, "\u044C"], [1069, 1, "\u044D"], [1070, 1, "\u044E"], [1071, 1, "\u044F"], [[1072, 1103], 2], [1104, 2], [[1105, 1116], 2], [1117, 2], [[1118, 1119], 2], [1120, 1, "\u0461"], [1121, 2], [1122, 1, "\u0463"], [1123, 2], [1124, 1, "\u0465"], [1125, 2], [1126, 1, "\u0467"], [1127, 2], [1128, 1, "\u0469"], [1129, 2], [1130, 1, "\u046B"], [1131, 2], [1132, 1, "\u046D"], [1133, 2], [1134, 1, "\u046F"], [1135, 2], [1136, 1, "\u0471"], [1137, 2], [1138, 1, "\u0473"], [1139, 2], [1140, 1, "\u0475"], [1141, 2], [1142, 1, "\u0477"], [1143, 2], [1144, 1, "\u0479"], [1145, 2], [1146, 1, "\u047B"], [1147, 2], [1148, 1, "\u047D"], [1149, 2], [1150, 1, "\u047F"], [1151, 2], [1152, 1, "\u0481"], [1153, 2], [1154, 2], [[1155, 1158], 2], [1159, 2], [[1160, 1161], 2], [1162, 1, "\u048B"], [1163, 2], [1164, 1, "\u048D"], [1165, 2], [1166, 1, "\u048F"], [1167, 2], [1168, 1, "\u0491"], [1169, 2], [1170, 1, "\u0493"], [1171, 2], [1172, 1, "\u0495"], [1173, 2], [1174, 1, "\u0497"], [1175, 2], [1176, 1, "\u0499"], [1177, 2], [1178, 1, "\u049B"], [1179, 2], [1180, 1, "\u049D"], [1181, 2], [1182, 1, "\u049F"], [1183, 2], [1184, 1, "\u04A1"], [1185, 2], [1186, 1, "\u04A3"], [1187, 2], [1188, 1, "\u04A5"], [1189, 2], [1190, 1, "\u04A7"], [1191, 2], [1192, 1, "\u04A9"], [1193, 2], [1194, 1, "\u04AB"], [1195, 2], [1196, 1, "\u04AD"], [1197, 2], [1198, 1, "\u04AF"], [1199, 2], [1200, 1, "\u04B1"], [1201, 2], [1202, 1, "\u04B3"], [1203, 2], [1204, 1, "\u04B5"], [1205, 2], [1206, 1, "\u04B7"], [1207, 2], [1208, 1, "\u04B9"], [1209, 2], [1210, 1, "\u04BB"], [1211, 2], [1212, 1, "\u04BD"], [1213, 2], [1214, 1, "\u04BF"], [1215, 2], [1216, 1, "\u04CF"], [1217, 1, "\u04C2"], [1218, 2], [1219, 1, "\u04C4"], [1220, 2], [1221, 1, "\u04C6"], [1222, 2], [1223, 1, "\u04C8"], [1224, 2], [1225, 1, "\u04CA"], [1226, 2], [1227, 1, "\u04CC"], [1228, 2], [1229, 1, "\u04CE"], [1230, 2], [1231, 2], [1232, 1, "\u04D1"], [1233, 2], [1234, 1, "\u04D3"], [1235, 2], [1236, 1, "\u04D5"], [1237, 2], [1238, 1, "\u04D7"], [1239, 2], [1240, 1, "\u04D9"], [1241, 2], [1242, 1, "\u04DB"], [1243, 2], [1244, 1, "\u04DD"], [1245, 2], [1246, 1, "\u04DF"], [1247, 2], [1248, 1, "\u04E1"], [1249, 2], [1250, 1, "\u04E3"], [1251, 2], [1252, 1, "\u04E5"], [1253, 2], [1254, 1, "\u04E7"], [1255, 2], [1256, 1, "\u04E9"], [1257, 2], [1258, 1, "\u04EB"], [1259, 2], [1260, 1, "\u04ED"], [1261, 2], [1262, 1, "\u04EF"], [1263, 2], [1264, 1, "\u04F1"], [1265, 2], [1266, 1, "\u04F3"], [1267, 2], [1268, 1, "\u04F5"], [1269, 2], [1270, 1, "\u04F7"], [1271, 2], [1272, 1, "\u04F9"], [1273, 2], [1274, 1, "\u04FB"], [1275, 2], [1276, 1, "\u04FD"], [1277, 2], [1278, 1, "\u04FF"], [1279, 2], [1280, 1, "\u0501"], [1281, 2], [1282, 1, "\u0503"], [1283, 2], [1284, 1, "\u0505"], [1285, 2], [1286, 1, "\u0507"], [1287, 2], [1288, 1, "\u0509"], [1289, 2], [1290, 1, "\u050B"], [1291, 2], [1292, 1, "\u050D"], [1293, 2], [1294, 1, "\u050F"], [1295, 2], [1296, 1, "\u0511"], [1297, 2], [1298, 1, "\u0513"], [1299, 2], [1300, 1, "\u0515"], [1301, 2], [1302, 1, "\u0517"], [1303, 2], [1304, 1, "\u0519"], [1305, 2], [1306, 1, "\u051B"], [1307, 2], [1308, 1, "\u051D"], [1309, 2], [1310, 1, "\u051F"], [1311, 2], [1312, 1, "\u0521"], [1313, 2], [1314, 1, "\u0523"], [1315, 2], [1316, 1, "\u0525"], [1317, 2], [1318, 1, "\u0527"], [1319, 2], [1320, 1, "\u0529"], [1321, 2], [1322, 1, "\u052B"], [1323, 2], [1324, 1, "\u052D"], [1325, 2], [1326, 1, "\u052F"], [1327, 2], [1328, 3], [1329, 1, "\u0561"], [1330, 1, "\u0562"], [1331, 1, "\u0563"], [1332, 1, "\u0564"], [1333, 1, "\u0565"], [1334, 1, "\u0566"], [1335, 1, "\u0567"], [1336, 1, "\u0568"], [1337, 1, "\u0569"], [1338, 1, "\u056A"], [1339, 1, "\u056B"], [1340, 1, "\u056C"], [1341, 1, "\u056D"], [1342, 1, "\u056E"], [1343, 1, "\u056F"], [1344, 1, "\u0570"], [1345, 1, "\u0571"], [1346, 1, "\u0572"], [1347, 1, "\u0573"], [1348, 1, "\u0574"], [1349, 1, "\u0575"], [1350, 1, "\u0576"], [1351, 1, "\u0577"], [1352, 1, "\u0578"], [1353, 1, "\u0579"], [1354, 1, "\u057A"], [1355, 1, "\u057B"], [1356, 1, "\u057C"], [1357, 1, "\u057D"], [1358, 1, "\u057E"], [1359, 1, "\u057F"], [1360, 1, "\u0580"], [1361, 1, "\u0581"], [1362, 1, "\u0582"], [1363, 1, "\u0583"], [1364, 1, "\u0584"], [1365, 1, "\u0585"], [1366, 1, "\u0586"], [[1367, 1368], 3], [1369, 2], [[1370, 1375], 2], [1376, 2], [[1377, 1414], 2], [1415, 1, "\u0565\u0582"], [1416, 2], [1417, 2], [1418, 2], [[1419, 1420], 3], [[1421, 1422], 2], [1423, 2], [1424, 3], [[1425, 1441], 2], [1442, 2], [[1443, 1455], 2], [[1456, 1465], 2], [1466, 2], [[1467, 1469], 2], [1470, 2], [1471, 2], [1472, 2], [[1473, 1474], 2], [1475, 2], [1476, 2], [1477, 2], [1478, 2], [1479, 2], [[1480, 1487], 3], [[1488, 1514], 2], [[1515, 1518], 3], [1519, 2], [[1520, 1524], 2], [[1525, 1535], 3], [[1536, 1539], 3], [1540, 3], [1541, 3], [[1542, 1546], 2], [1547, 2], [1548, 2], [[1549, 1551], 2], [[1552, 1557], 2], [[1558, 1562], 2], [1563, 2], [1564, 3], [1565, 2], [1566, 2], [1567, 2], [1568, 2], [[1569, 1594], 2], [[1595, 1599], 2], [1600, 2], [[1601, 1618], 2], [[1619, 1621], 2], [[1622, 1624], 2], [[1625, 1630], 2], [1631, 2], [[1632, 1641], 2], [[1642, 1645], 2], [[1646, 1647], 2], [[1648, 1652], 2], [1653, 1, "\u0627\u0674"], [1654, 1, "\u0648\u0674"], [1655, 1, "\u06C7\u0674"], [1656, 1, "\u064A\u0674"], [[1657, 1719], 2], [[1720, 1721], 2], [[1722, 1726], 2], [1727, 2], [[1728, 1742], 2], [1743, 2], [[1744, 1747], 2], [1748, 2], [[1749, 1756], 2], [1757, 3], [1758, 2], [[1759, 1768], 2], [1769, 2], [[1770, 1773], 2], [[1774, 1775], 2], [[1776, 1785], 2], [[1786, 1790], 2], [1791, 2], [[1792, 1805], 2], [1806, 3], [1807, 3], [[1808, 1836], 2], [[1837, 1839], 2], [[1840, 1866], 2], [[1867, 1868], 3], [[1869, 1871], 2], [[1872, 1901], 2], [[1902, 1919], 2], [[1920, 1968], 2], [1969, 2], [[1970, 1983], 3], [[1984, 2037], 2], [[2038, 2042], 2], [[2043, 2044], 3], [2045, 2], [[2046, 2047], 2], [[2048, 2093], 2], [[2094, 2095], 3], [[2096, 2110], 2], [2111, 3], [[2112, 2139], 2], [[2140, 2141], 3], [2142, 2], [2143, 3], [[2144, 2154], 2], [[2155, 2159], 3], [[2160, 2183], 2], [2184, 2], [[2185, 2190], 2], [2191, 3], [[2192, 2193], 3], [[2194, 2198], 3], [2199, 2], [[2200, 2207], 2], [2208, 2], [2209, 2], [[2210, 2220], 2], [[2221, 2226], 2], [[2227, 2228], 2], [2229, 2], [[2230, 2237], 2], [[2238, 2247], 2], [[2248, 2258], 2], [2259, 2], [[2260, 2273], 2], [2274, 3], [2275, 2], [[2276, 2302], 2], [2303, 2], [2304, 2], [[2305, 2307], 2], [2308, 2], [[2309, 2361], 2], [[2362, 2363], 2], [[2364, 2381], 2], [2382, 2], [2383, 2], [[2384, 2388], 2], [2389, 2], [[2390, 2391], 2], [2392, 1, "\u0915\u093C"], [2393, 1, "\u0916\u093C"], [2394, 1, "\u0917\u093C"], [2395, 1, "\u091C\u093C"], [2396, 1, "\u0921\u093C"], [2397, 1, "\u0922\u093C"], [2398, 1, "\u092B\u093C"], [2399, 1, "\u092F\u093C"], [[2400, 2403], 2], [[2404, 2405], 2], [[2406, 2415], 2], [2416, 2], [[2417, 2418], 2], [[2419, 2423], 2], [2424, 2], [[2425, 2426], 2], [[2427, 2428], 2], [2429, 2], [[2430, 2431], 2], [2432, 2], [[2433, 2435], 2], [2436, 3], [[2437, 2444], 2], [[2445, 2446], 3], [[2447, 2448], 2], [[2449, 2450], 3], [[2451, 2472], 2], [2473, 3], [[2474, 2480], 2], [2481, 3], [2482, 2], [[2483, 2485], 3], [[2486, 2489], 2], [[2490, 2491], 3], [2492, 2], [2493, 2], [[2494, 2500], 2], [[2501, 2502], 3], [[2503, 2504], 2], [[2505, 2506], 3], [[2507, 2509], 2], [2510, 2], [[2511, 2518], 3], [2519, 2], [[2520, 2523], 3], [2524, 1, "\u09A1\u09BC"], [2525, 1, "\u09A2\u09BC"], [2526, 3], [2527, 1, "\u09AF\u09BC"], [[2528, 2531], 2], [[2532, 2533], 3], [[2534, 2545], 2], [[2546, 2554], 2], [2555, 2], [2556, 2], [2557, 2], [2558, 2], [[2559, 2560], 3], [2561, 2], [2562, 2], [2563, 2], [2564, 3], [[2565, 2570], 2], [[2571, 2574], 3], [[2575, 2576], 2], [[2577, 2578], 3], [[2579, 2600], 2], [2601, 3], [[2602, 2608], 2], [2609, 3], [2610, 2], [2611, 1, "\u0A32\u0A3C"], [2612, 3], [2613, 2], [2614, 1, "\u0A38\u0A3C"], [2615, 3], [[2616, 2617], 2], [[2618, 2619], 3], [2620, 2], [2621, 3], [[2622, 2626], 2], [[2627, 2630], 3], [[2631, 2632], 2], [[2633, 2634], 3], [[2635, 2637], 2], [[2638, 2640], 3], [2641, 2], [[2642, 2648], 3], [2649, 1, "\u0A16\u0A3C"], [2650, 1, "\u0A17\u0A3C"], [2651, 1, "\u0A1C\u0A3C"], [2652, 2], [2653, 3], [2654, 1, "\u0A2B\u0A3C"], [[2655, 2661], 3], [[2662, 2676], 2], [2677, 2], [2678, 2], [[2679, 2688], 3], [[2689, 2691], 2], [2692, 3], [[2693, 2699], 2], [2700, 2], [2701, 2], [2702, 3], [[2703, 2705], 2], [2706, 3], [[2707, 2728], 2], [2729, 3], [[2730, 2736], 2], [2737, 3], [[2738, 2739], 2], [2740, 3], [[2741, 2745], 2], [[2746, 2747], 3], [[2748, 2757], 2], [2758, 3], [[2759, 2761], 2], [2762, 3], [[2763, 2765], 2], [[2766, 2767], 3], [2768, 2], [[2769, 2783], 3], [2784, 2], [[2785, 2787], 2], [[2788, 2789], 3], [[2790, 2799], 2], [2800, 2], [2801, 2], [[2802, 2808], 3], [2809, 2], [[2810, 2815], 2], [2816, 3], [[2817, 2819], 2], [2820, 3], [[2821, 2828], 2], [[2829, 2830], 3], [[2831, 2832], 2], [[2833, 2834], 3], [[2835, 2856], 2], [2857, 3], [[2858, 2864], 2], [2865, 3], [[2866, 2867], 2], [2868, 3], [2869, 2], [[2870, 2873], 2], [[2874, 2875], 3], [[2876, 2883], 2], [2884, 2], [[2885, 2886], 3], [[2887, 2888], 2], [[2889, 2890], 3], [[2891, 2893], 2], [[2894, 2900], 3], [2901, 2], [[2902, 2903], 2], [[2904, 2907], 3], [2908, 1, "\u0B21\u0B3C"], [2909, 1, "\u0B22\u0B3C"], [2910, 3], [[2911, 2913], 2], [[2914, 2915], 2], [[2916, 2917], 3], [[2918, 2927], 2], [2928, 2], [2929, 2], [[2930, 2935], 2], [[2936, 2945], 3], [[2946, 2947], 2], [2948, 3], [[2949, 2954], 2], [[2955, 2957], 3], [[2958, 2960], 2], [2961, 3], [[2962, 2965], 2], [[2966, 2968], 3], [[2969, 2970], 2], [2971, 3], [2972, 2], [2973, 3], [[2974, 2975], 2], [[2976, 2978], 3], [[2979, 2980], 2], [[2981, 2983], 3], [[2984, 2986], 2], [[2987, 2989], 3], [[2990, 2997], 2], [2998, 2], [[2999, 3001], 2], [[3002, 3005], 3], [[3006, 3010], 2], [[3011, 3013], 3], [[3014, 3016], 2], [3017, 3], [[3018, 3021], 2], [[3022, 3023], 3], [3024, 2], [[3025, 3030], 3], [3031, 2], [[3032, 3045], 3], [3046, 2], [[3047, 3055], 2], [[3056, 3058], 2], [[3059, 3066], 2], [[3067, 3071], 3], [3072, 2], [[3073, 3075], 2], [3076, 2], [[3077, 3084], 2], [3085, 3], [[3086, 3088], 2], [3089, 3], [[3090, 3112], 2], [3113, 3], [[3114, 3123], 2], [3124, 2], [[3125, 3129], 2], [[3130, 3131], 3], [3132, 2], [3133, 2], [[3134, 3140], 2], [3141, 3], [[3142, 3144], 2], [3145, 3], [[3146, 3149], 2], [[3150, 3156], 3], [[3157, 3158], 2], [3159, 3], [[3160, 3161], 2], [3162, 2], [[3163, 3164], 3], [3165, 2], [[3166, 3167], 3], [[3168, 3169], 2], [[3170, 3171], 2], [[3172, 3173], 3], [[3174, 3183], 2], [[3184, 3190], 3], [3191, 2], [[3192, 3199], 2], [3200, 2], [3201, 2], [[3202, 3203], 2], [3204, 2], [[3205, 3212], 2], [3213, 3], [[3214, 3216], 2], [3217, 3], [[3218, 3240], 2], [3241, 3], [[3242, 3251], 2], [3252, 3], [[3253, 3257], 2], [[3258, 3259], 3], [[3260, 3261], 2], [[3262, 3268], 2], [3269, 3], [[3270, 3272], 2], [3273, 3], [[3274, 3277], 2], [[3278, 3284], 3], [[3285, 3286], 2], [[3287, 3292], 3], [3293, 2], [3294, 2], [3295, 3], [[3296, 3297], 2], [[3298, 3299], 2], [[3300, 3301], 3], [[3302, 3311], 2], [3312, 3], [[3313, 3314], 2], [3315, 2], [[3316, 3327], 3], [3328, 2], [3329, 2], [[3330, 3331], 2], [3332, 2], [[3333, 3340], 2], [3341, 3], [[3342, 3344], 2], [3345, 3], [[3346, 3368], 2], [3369, 2], [[3370, 3385], 2], [3386, 2], [[3387, 3388], 2], [3389, 2], [[3390, 3395], 2], [3396, 2], [3397, 3], [[3398, 3400], 2], [3401, 3], [[3402, 3405], 2], [3406, 2], [3407, 2], [[3408, 3411], 3], [[3412, 3414], 2], [3415, 2], [[3416, 3422], 2], [3423, 2], [[3424, 3425], 2], [[3426, 3427], 2], [[3428, 3429], 3], [[3430, 3439], 2], [[3440, 3445], 2], [[3446, 3448], 2], [3449, 2], [[3450, 3455], 2], [3456, 3], [3457, 2], [[3458, 3459], 2], [3460, 3], [[3461, 3478], 2], [[3479, 3481], 3], [[3482, 3505], 2], [3506, 3], [[3507, 3515], 2], [3516, 3], [3517, 2], [[3518, 3519], 3], [[3520, 3526], 2], [[3527, 3529], 3], [3530, 2], [[3531, 3534], 3], [[3535, 3540], 2], [3541, 3], [3542, 2], [3543, 3], [[3544, 3551], 2], [[3552, 3557], 3], [[3558, 3567], 2], [[3568, 3569], 3], [[3570, 3571], 2], [3572, 2], [[3573, 3584], 3], [[3585, 3634], 2], [3635, 1, "\u0E4D\u0E32"], [[3636, 3642], 2], [[3643, 3646], 3], [3647, 2], [[3648, 3662], 2], [3663, 2], [[3664, 3673], 2], [[3674, 3675], 2], [[3676, 3712], 3], [[3713, 3714], 2], [3715, 3], [3716, 2], [3717, 3], [3718, 2], [[3719, 3720], 2], [3721, 2], [3722, 2], [3723, 3], [3724, 2], [3725, 2], [[3726, 3731], 2], [[3732, 3735], 2], [3736, 2], [[3737, 3743], 2], [3744, 2], [[3745, 3747], 2], [3748, 3], [3749, 2], [3750, 3], [3751, 2], [[3752, 3753], 2], [[3754, 3755], 2], [3756, 2], [[3757, 3762], 2], [3763, 1, "\u0ECD\u0EB2"], [[3764, 3769], 2], [3770, 2], [[3771, 3773], 2], [[3774, 3775], 3], [[3776, 3780], 2], [3781, 3], [3782, 2], [3783, 3], [[3784, 3789], 2], [3790, 2], [3791, 3], [[3792, 3801], 2], [[3802, 3803], 3], [3804, 1, "\u0EAB\u0E99"], [3805, 1, "\u0EAB\u0EA1"], [[3806, 3807], 2], [[3808, 3839], 3], [3840, 2], [[3841, 3850], 2], [3851, 2], [3852, 1, "\u0F0B"], [[3853, 3863], 2], [[3864, 3865], 2], [[3866, 3871], 2], [[3872, 3881], 2], [[3882, 3892], 2], [3893, 2], [3894, 2], [3895, 2], [3896, 2], [3897, 2], [[3898, 3901], 2], [[3902, 3906], 2], [3907, 1, "\u0F42\u0FB7"], [[3908, 3911], 2], [3912, 3], [[3913, 3916], 2], [3917, 1, "\u0F4C\u0FB7"], [[3918, 3921], 2], [3922, 1, "\u0F51\u0FB7"], [[3923, 3926], 2], [3927, 1, "\u0F56\u0FB7"], [[3928, 3931], 2], [3932, 1, "\u0F5B\u0FB7"], [[3933, 3944], 2], [3945, 1, "\u0F40\u0FB5"], [3946, 2], [[3947, 3948], 2], [[3949, 3952], 3], [[3953, 3954], 2], [3955, 1, "\u0F71\u0F72"], [3956, 2], [3957, 1, "\u0F71\u0F74"], [3958, 1, "\u0FB2\u0F80"], [3959, 1, "\u0FB2\u0F71\u0F80"], [3960, 1, "\u0FB3\u0F80"], [3961, 1, "\u0FB3\u0F71\u0F80"], [[3962, 3968], 2], [3969, 1, "\u0F71\u0F80"], [[3970, 3972], 2], [3973, 2], [[3974, 3979], 2], [[3980, 3983], 2], [[3984, 3986], 2], [3987, 1, "\u0F92\u0FB7"], [[3988, 3989], 2], [3990, 2], [3991, 2], [3992, 3], [[3993, 3996], 2], [3997, 1, "\u0F9C\u0FB7"], [[3998, 4001], 2], [4002, 1, "\u0FA1\u0FB7"], [[4003, 4006], 2], [4007, 1, "\u0FA6\u0FB7"], [[4008, 4011], 2], [4012, 1, "\u0FAB\u0FB7"], [4013, 2], [[4014, 4016], 2], [[4017, 4023], 2], [4024, 2], [4025, 1, "\u0F90\u0FB5"], [[4026, 4028], 2], [4029, 3], [[4030, 4037], 2], [4038, 2], [[4039, 4044], 2], [4045, 3], [4046, 2], [4047, 2], [[4048, 4049], 2], [[4050, 4052], 2], [[4053, 4056], 2], [[4057, 4058], 2], [[4059, 4095], 3], [[4096, 4129], 2], [4130, 2], [[4131, 4135], 2], [4136, 2], [[4137, 4138], 2], [4139, 2], [[4140, 4146], 2], [[4147, 4149], 2], [[4150, 4153], 2], [[4154, 4159], 2], [[4160, 4169], 2], [[4170, 4175], 2], [[4176, 4185], 2], [[4186, 4249], 2], [[4250, 4253], 2], [[4254, 4255], 2], [4256, 1, "\u2D00"], [4257, 1, "\u2D01"], [4258, 1, "\u2D02"], [4259, 1, "\u2D03"], [4260, 1, "\u2D04"], [4261, 1, "\u2D05"], [4262, 1, "\u2D06"], [4263, 1, "\u2D07"], [4264, 1, "\u2D08"], [4265, 1, "\u2D09"], [4266, 1, "\u2D0A"], [4267, 1, "\u2D0B"], [4268, 1, "\u2D0C"], [4269, 1, "\u2D0D"], [4270, 1, "\u2D0E"], [4271, 1, "\u2D0F"], [4272, 1, "\u2D10"], [4273, 1, "\u2D11"], [4274, 1, "\u2D12"], [4275, 1, "\u2D13"], [4276, 1, "\u2D14"], [4277, 1, "\u2D15"], [4278, 1, "\u2D16"], [4279, 1, "\u2D17"], [4280, 1, "\u2D18"], [4281, 1, "\u2D19"], [4282, 1, "\u2D1A"], [4283, 1, "\u2D1B"], [4284, 1, "\u2D1C"], [4285, 1, "\u2D1D"], [4286, 1, "\u2D1E"], [4287, 1, "\u2D1F"], [4288, 1, "\u2D20"], [4289, 1, "\u2D21"], [4290, 1, "\u2D22"], [4291, 1, "\u2D23"], [4292, 1, "\u2D24"], [4293, 1, "\u2D25"], [4294, 3], [4295, 1, "\u2D27"], [[4296, 4300], 3], [4301, 1, "\u2D2D"], [[4302, 4303], 3], [[4304, 4342], 2], [[4343, 4344], 2], [[4345, 4346], 2], [4347, 2], [4348, 1, "\u10DC"], [[4349, 4351], 2], [[4352, 4441], 2], [[4442, 4446], 2], [[4447, 4448], 7], [[4449, 4514], 2], [[4515, 4519], 2], [[4520, 4601], 2], [[4602, 4607], 2], [[4608, 4614], 2], [4615, 2], [[4616, 4678], 2], [4679, 2], [4680, 2], [4681, 3], [[4682, 4685], 2], [[4686, 4687], 3], [[4688, 4694], 2], [4695, 3], [4696, 2], [4697, 3], [[4698, 4701], 2], [[4702, 4703], 3], [[4704, 4742], 2], [4743, 2], [4744, 2], [4745, 3], [[4746, 4749], 2], [[4750, 4751], 3], [[4752, 4782], 2], [4783, 2], [4784, 2], [4785, 3], [[4786, 4789], 2], [[4790, 4791], 3], [[4792, 4798], 2], [4799, 3], [4800, 2], [4801, 3], [[4802, 4805], 2], [[4806, 4807], 3], [[4808, 4814], 2], [4815, 2], [[4816, 4822], 2], [4823, 3], [[4824, 4846], 2], [4847, 2], [[4848, 4878], 2], [4879, 2], [4880, 2], [4881, 3], [[4882, 4885], 2], [[4886, 4887], 3], [[4888, 4894], 2], [4895, 2], [[4896, 4934], 2], [4935, 2], [[4936, 4954], 2], [[4955, 4956], 3], [[4957, 4958], 2], [4959, 2], [4960, 2], [[4961, 4988], 2], [[4989, 4991], 3], [[4992, 5007], 2], [[5008, 5017], 2], [[5018, 5023], 3], [[5024, 5108], 2], [5109, 2], [[5110, 5111], 3], [5112, 1, "\u13F0"], [5113, 1, "\u13F1"], [5114, 1, "\u13F2"], [5115, 1, "\u13F3"], [5116, 1, "\u13F4"], [5117, 1, "\u13F5"], [[5118, 5119], 3], [5120, 2], [[5121, 5740], 2], [[5741, 5742], 2], [[5743, 5750], 2], [[5751, 5759], 2], [5760, 3], [[5761, 5786], 2], [[5787, 5788], 2], [[5789, 5791], 3], [[5792, 5866], 2], [[5867, 5872], 2], [[5873, 5880], 2], [[5881, 5887], 3], [[5888, 5900], 2], [5901, 2], [[5902, 5908], 2], [5909, 2], [[5910, 5918], 3], [5919, 2], [[5920, 5940], 2], [[5941, 5942], 2], [[5943, 5951], 3], [[5952, 5971], 2], [[5972, 5983], 3], [[5984, 5996], 2], [5997, 3], [[5998, 6e3], 2], [6001, 3], [[6002, 6003], 2], [[6004, 6015], 3], [[6016, 6067], 2], [[6068, 6069], 7], [[6070, 6099], 2], [[6100, 6102], 2], [6103, 2], [[6104, 6107], 2], [6108, 2], [6109, 2], [[6110, 6111], 3], [[6112, 6121], 2], [[6122, 6127], 3], [[6128, 6137], 2], [[6138, 6143], 3], [[6144, 6154], 2], [[6155, 6158], 7], [6159, 7], [[6160, 6169], 2], [[6170, 6175], 3], [[6176, 6263], 2], [6264, 2], [[6265, 6271], 3], [[6272, 6313], 2], [6314, 2], [[6315, 6319], 3], [[6320, 6389], 2], [[6390, 6399], 3], [[6400, 6428], 2], [[6429, 6430], 2], [6431, 3], [[6432, 6443], 2], [[6444, 6447], 3], [[6448, 6459], 2], [[6460, 6463], 3], [6464, 2], [[6465, 6467], 3], [[6468, 6469], 2], [[6470, 6509], 2], [[6510, 6511], 3], [[6512, 6516], 2], [[6517, 6527], 3], [[6528, 6569], 2], [[6570, 6571], 2], [[6572, 6575], 3], [[6576, 6601], 2], [[6602, 6607], 3], [[6608, 6617], 2], [6618, 2], [[6619, 6621], 3], [[6622, 6623], 2], [[6624, 6655], 2], [[6656, 6683], 2], [[6684, 6685], 3], [[6686, 6687], 2], [[6688, 6750], 2], [6751, 3], [[6752, 6780], 2], [[6781, 6782], 3], [[6783, 6793], 2], [[6794, 6799], 3], [[6800, 6809], 2], [[6810, 6815], 3], [[6816, 6822], 2], [6823, 2], [[6824, 6829], 2], [[6830, 6831], 3], [[6832, 6845], 2], [6846, 2], [[6847, 6848], 2], [[6849, 6862], 2], [[6863, 6911], 3], [[6912, 6987], 2], [6988, 2], [6989, 3], [[6990, 6991], 2], [[6992, 7001], 2], [[7002, 7018], 2], [[7019, 7027], 2], [[7028, 7036], 2], [[7037, 7038], 2], [7039, 2], [[7040, 7082], 2], [[7083, 7085], 2], [[7086, 7097], 2], [[7098, 7103], 2], [[7104, 7155], 2], [[7156, 7163], 3], [[7164, 7167], 2], [[7168, 7223], 2], [[7224, 7226], 3], [[7227, 7231], 2], [[7232, 7241], 2], [[7242, 7244], 3], [[7245, 7293], 2], [[7294, 7295], 2], [7296, 1, "\u0432"], [7297, 1, "\u0434"], [7298, 1, "\u043E"], [7299, 1, "\u0441"], [[7300, 7301], 1, "\u0442"], [7302, 1, "\u044A"], [7303, 1, "\u0463"], [7304, 1, "\uA64B"], [7305, 1, "\u1C8A"], [7306, 2], [[7307, 7311], 3], [7312, 1, "\u10D0"], [7313, 1, "\u10D1"], [7314, 1, "\u10D2"], [7315, 1, "\u10D3"], [7316, 1, "\u10D4"], [7317, 1, "\u10D5"], [7318, 1, "\u10D6"], [7319, 1, "\u10D7"], [7320, 1, "\u10D8"], [7321, 1, "\u10D9"], [7322, 1, "\u10DA"], [7323, 1, "\u10DB"], [7324, 1, "\u10DC"], [7325, 1, "\u10DD"], [7326, 1, "\u10DE"], [7327, 1, "\u10DF"], [7328, 1, "\u10E0"], [7329, 1, "\u10E1"], [7330, 1, "\u10E2"], [7331, 1, "\u10E3"], [7332, 1, "\u10E4"], [7333, 1, "\u10E5"], [7334, 1, "\u10E6"], [7335, 1, "\u10E7"], [7336, 1, "\u10E8"], [7337, 1, "\u10E9"], [7338, 1, "\u10EA"], [7339, 1, "\u10EB"], [7340, 1, "\u10EC"], [7341, 1, "\u10ED"], [7342, 1, "\u10EE"], [7343, 1, "\u10EF"], [7344, 1, "\u10F0"], [7345, 1, "\u10F1"], [7346, 1, "\u10F2"], [7347, 1, "\u10F3"], [7348, 1, "\u10F4"], [7349, 1, "\u10F5"], [7350, 1, "\u10F6"], [7351, 1, "\u10F7"], [7352, 1, "\u10F8"], [7353, 1, "\u10F9"], [7354, 1, "\u10FA"], [[7355, 7356], 3], [7357, 1, "\u10FD"], [7358, 1, "\u10FE"], [7359, 1, "\u10FF"], [[7360, 7367], 2], [[7368, 7375], 3], [[7376, 7378], 2], [7379, 2], [[7380, 7410], 2], [[7411, 7414], 2], [7415, 2], [[7416, 7417], 2], [7418, 2], [[7419, 7423], 3], [[7424, 7467], 2], [7468, 1, "a"], [7469, 1, "\xE6"], [7470, 1, "b"], [7471, 2], [7472, 1, "d"], [7473, 1, "e"], [7474, 1, "\u01DD"], [7475, 1, "g"], [7476, 1, "h"], [7477, 1, "i"], [7478, 1, "j"], [7479, 1, "k"], [7480, 1, "l"], [7481, 1, "m"], [7482, 1, "n"], [7483, 2], [7484, 1, "o"], [7485, 1, "\u0223"], [7486, 1, "p"], [7487, 1, "r"], [7488, 1, "t"], [7489, 1, "u"], [7490, 1, "w"], [7491, 1, "a"], [7492, 1, "\u0250"], [7493, 1, "\u0251"], [7494, 1, "\u1D02"], [7495, 1, "b"], [7496, 1, "d"], [7497, 1, "e"], [7498, 1, "\u0259"], [7499, 1, "\u025B"], [7500, 1, "\u025C"], [7501, 1, "g"], [7502, 2], [7503, 1, "k"], [7504, 1, "m"], [7505, 1, "\u014B"], [7506, 1, "o"], [7507, 1, "\u0254"], [7508, 1, "\u1D16"], [7509, 1, "\u1D17"], [7510, 1, "p"], [7511, 1, "t"], [7512, 1, "u"], [7513, 1, "\u1D1D"], [7514, 1, "\u026F"], [7515, 1, "v"], [7516, 1, "\u1D25"], [7517, 1, "\u03B2"], [7518, 1, "\u03B3"], [7519, 1, "\u03B4"], [7520, 1, "\u03C6"], [7521, 1, "\u03C7"], [7522, 1, "i"], [7523, 1, "r"], [7524, 1, "u"], [7525, 1, "v"], [7526, 1, "\u03B2"], [7527, 1, "\u03B3"], [7528, 1, "\u03C1"], [7529, 1, "\u03C6"], [7530, 1, "\u03C7"], [7531, 2], [[7532, 7543], 2], [7544, 1, "\u043D"], [[7545, 7578], 2], [7579, 1, "\u0252"], [7580, 1, "c"], [7581, 1, "\u0255"], [7582, 1, "\xF0"], [7583, 1, "\u025C"], [7584, 1, "f"], [7585, 1, "\u025F"], [7586, 1, "\u0261"], [7587, 1, "\u0265"], [7588, 1, "\u0268"], [7589, 1, "\u0269"], [7590, 1, "\u026A"], [7591, 1, "\u1D7B"], [7592, 1, "\u029D"], [7593, 1, "\u026D"], [7594, 1, "\u1D85"], [7595, 1, "\u029F"], [7596, 1, "\u0271"], [7597, 1, "\u0270"], [7598, 1, "\u0272"], [7599, 1, "\u0273"], [7600, 1, "\u0274"], [7601, 1, "\u0275"], [7602, 1, "\u0278"], [7603, 1, "\u0282"], [7604, 1, "\u0283"], [7605, 1, "\u01AB"], [7606, 1, "\u0289"], [7607, 1, "\u028A"], [7608, 1, "\u1D1C"], [7609, 1, "\u028B"], [7610, 1, "\u028C"], [7611, 1, "z"], [7612, 1, "\u0290"], [7613, 1, "\u0291"], [7614, 1, "\u0292"], [7615, 1, "\u03B8"], [[7616, 7619], 2], [[7620, 7626], 2], [[7627, 7654], 2], [[7655, 7669], 2], [[7670, 7673], 2], [7674, 2], [7675, 2], [7676, 2], [7677, 2], [[7678, 7679], 2], [7680, 1, "\u1E01"], [7681, 2], [7682, 1, "\u1E03"], [7683, 2], [7684, 1, "\u1E05"], [7685, 2], [7686, 1, "\u1E07"], [7687, 2], [7688, 1, "\u1E09"], [7689, 2], [7690, 1, "\u1E0B"], [7691, 2], [7692, 1, "\u1E0D"], [7693, 2], [7694, 1, "\u1E0F"], [7695, 2], [7696, 1, "\u1E11"], [7697, 2], [7698, 1, "\u1E13"], [7699, 2], [7700, 1, "\u1E15"], [7701, 2], [7702, 1, "\u1E17"], [7703, 2], [7704, 1, "\u1E19"], [7705, 2], [7706, 1, "\u1E1B"], [7707, 2], [7708, 1, "\u1E1D"], [7709, 2], [7710, 1, "\u1E1F"], [7711, 2], [7712, 1, "\u1E21"], [7713, 2], [7714, 1, "\u1E23"], [7715, 2], [7716, 1, "\u1E25"], [7717, 2], [7718, 1, "\u1E27"], [7719, 2], [7720, 1, "\u1E29"], [7721, 2], [7722, 1, "\u1E2B"], [7723, 2], [7724, 1, "\u1E2D"], [7725, 2], [7726, 1, "\u1E2F"], [7727, 2], [7728, 1, "\u1E31"], [7729, 2], [7730, 1, "\u1E33"], [7731, 2], [7732, 1, "\u1E35"], [7733, 2], [7734, 1, "\u1E37"], [7735, 2], [7736, 1, "\u1E39"], [7737, 2], [7738, 1, "\u1E3B"], [7739, 2], [7740, 1, "\u1E3D"], [7741, 2], [7742, 1, "\u1E3F"], [7743, 2], [7744, 1, "\u1E41"], [7745, 2], [7746, 1, "\u1E43"], [7747, 2], [7748, 1, "\u1E45"], [7749, 2], [7750, 1, "\u1E47"], [7751, 2], [7752, 1, "\u1E49"], [7753, 2], [7754, 1, "\u1E4B"], [7755, 2], [7756, 1, "\u1E4D"], [7757, 2], [7758, 1, "\u1E4F"], [7759, 2], [7760, 1, "\u1E51"], [7761, 2], [7762, 1, "\u1E53"], [7763, 2], [7764, 1, "\u1E55"], [7765, 2], [7766, 1, "\u1E57"], [7767, 2], [7768, 1, "\u1E59"], [7769, 2], [7770, 1, "\u1E5B"], [7771, 2], [7772, 1, "\u1E5D"], [7773, 2], [7774, 1, "\u1E5F"], [7775, 2], [7776, 1, "\u1E61"], [7777, 2], [7778, 1, "\u1E63"], [7779, 2], [7780, 1, "\u1E65"], [7781, 2], [7782, 1, "\u1E67"], [7783, 2], [7784, 1, "\u1E69"], [7785, 2], [7786, 1, "\u1E6B"], [7787, 2], [7788, 1, "\u1E6D"], [7789, 2], [7790, 1, "\u1E6F"], [7791, 2], [7792, 1, "\u1E71"], [7793, 2], [7794, 1, "\u1E73"], [7795, 2], [7796, 1, "\u1E75"], [7797, 2], [7798, 1, "\u1E77"], [7799, 2], [7800, 1, "\u1E79"], [7801, 2], [7802, 1, "\u1E7B"], [7803, 2], [7804, 1, "\u1E7D"], [7805, 2], [7806, 1, "\u1E7F"], [7807, 2], [7808, 1, "\u1E81"], [7809, 2], [7810, 1, "\u1E83"], [7811, 2], [7812, 1, "\u1E85"], [7813, 2], [7814, 1, "\u1E87"], [7815, 2], [7816, 1, "\u1E89"], [7817, 2], [7818, 1, "\u1E8B"], [7819, 2], [7820, 1, "\u1E8D"], [7821, 2], [7822, 1, "\u1E8F"], [7823, 2], [7824, 1, "\u1E91"], [7825, 2], [7826, 1, "\u1E93"], [7827, 2], [7828, 1, "\u1E95"], [[7829, 7833], 2], [7834, 1, "a\u02BE"], [7835, 1, "\u1E61"], [[7836, 7837], 2], [7838, 1, "\xDF"], [7839, 2], [7840, 1, "\u1EA1"], [7841, 2], [7842, 1, "\u1EA3"], [7843, 2], [7844, 1, "\u1EA5"], [7845, 2], [7846, 1, "\u1EA7"], [7847, 2], [7848, 1, "\u1EA9"], [7849, 2], [7850, 1, "\u1EAB"], [7851, 2], [7852, 1, "\u1EAD"], [7853, 2], [7854, 1, "\u1EAF"], [7855, 2], [7856, 1, "\u1EB1"], [7857, 2], [7858, 1, "\u1EB3"], [7859, 2], [7860, 1, "\u1EB5"], [7861, 2], [7862, 1, "\u1EB7"], [7863, 2], [7864, 1, "\u1EB9"], [7865, 2], [7866, 1, "\u1EBB"], [7867, 2], [7868, 1, "\u1EBD"], [7869, 2], [7870, 1, "\u1EBF"], [7871, 2], [7872, 1, "\u1EC1"], [7873, 2], [7874, 1, "\u1EC3"], [7875, 2], [7876, 1, "\u1EC5"], [7877, 2], [7878, 1, "\u1EC7"], [7879, 2], [7880, 1, "\u1EC9"], [7881, 2], [7882, 1, "\u1ECB"], [7883, 2], [7884, 1, "\u1ECD"], [7885, 2], [7886, 1, "\u1ECF"], [7887, 2], [7888, 1, "\u1ED1"], [7889, 2], [7890, 1, "\u1ED3"], [7891, 2], [7892, 1, "\u1ED5"], [7893, 2], [7894, 1, "\u1ED7"], [7895, 2], [7896, 1, "\u1ED9"], [7897, 2], [7898, 1, "\u1EDB"], [7899, 2], [7900, 1, "\u1EDD"], [7901, 2], [7902, 1, "\u1EDF"], [7903, 2], [7904, 1, "\u1EE1"], [7905, 2], [7906, 1, "\u1EE3"], [7907, 2], [7908, 1, "\u1EE5"], [7909, 2], [7910, 1, "\u1EE7"], [7911, 2], [7912, 1, "\u1EE9"], [7913, 2], [7914, 1, "\u1EEB"], [7915, 2], [7916, 1, "\u1EED"], [7917, 2], [7918, 1, "\u1EEF"], [7919, 2], [7920, 1, "\u1EF1"], [7921, 2], [7922, 1, "\u1EF3"], [7923, 2], [7924, 1, "\u1EF5"], [7925, 2], [7926, 1, "\u1EF7"], [7927, 2], [7928, 1, "\u1EF9"], [7929, 2], [7930, 1, "\u1EFB"], [7931, 2], [7932, 1, "\u1EFD"], [7933, 2], [7934, 1, "\u1EFF"], [7935, 2], [[7936, 7943], 2], [7944, 1, "\u1F00"], [7945, 1, "\u1F01"], [7946, 1, "\u1F02"], [7947, 1, "\u1F03"], [7948, 1, "\u1F04"], [7949, 1, "\u1F05"], [7950, 1, "\u1F06"], [7951, 1, "\u1F07"], [[7952, 7957], 2], [[7958, 7959], 3], [7960, 1, "\u1F10"], [7961, 1, "\u1F11"], [7962, 1, "\u1F12"], [7963, 1, "\u1F13"], [7964, 1, "\u1F14"], [7965, 1, "\u1F15"], [[7966, 7967], 3], [[7968, 7975], 2], [7976, 1, "\u1F20"], [7977, 1, "\u1F21"], [7978, 1, "\u1F22"], [7979, 1, "\u1F23"], [7980, 1, "\u1F24"], [7981, 1, "\u1F25"], [7982, 1, "\u1F26"], [7983, 1, "\u1F27"], [[7984, 7991], 2], [7992, 1, "\u1F30"], [7993, 1, "\u1F31"], [7994, 1, "\u1F32"], [7995, 1, "\u1F33"], [7996, 1, "\u1F34"], [7997, 1, "\u1F35"], [7998, 1, "\u1F36"], [7999, 1, "\u1F37"], [[8e3, 8005], 2], [[8006, 8007], 3], [8008, 1, "\u1F40"], [8009, 1, "\u1F41"], [8010, 1, "\u1F42"], [8011, 1, "\u1F43"], [8012, 1, "\u1F44"], [8013, 1, "\u1F45"], [[8014, 8015], 3], [[8016, 8023], 2], [8024, 3], [8025, 1, "\u1F51"], [8026, 3], [8027, 1, "\u1F53"], [8028, 3], [8029, 1, "\u1F55"], [8030, 3], [8031, 1, "\u1F57"], [[8032, 8039], 2], [8040, 1, "\u1F60"], [8041, 1, "\u1F61"], [8042, 1, "\u1F62"], [8043, 1, "\u1F63"], [8044, 1, "\u1F64"], [8045, 1, "\u1F65"], [8046, 1, "\u1F66"], [8047, 1, "\u1F67"], [8048, 2], [8049, 1, "\u03AC"], [8050, 2], [8051, 1, "\u03AD"], [8052, 2], [8053, 1, "\u03AE"], [8054, 2], [8055, 1, "\u03AF"], [8056, 2], [8057, 1, "\u03CC"], [8058, 2], [8059, 1, "\u03CD"], [8060, 2], [8061, 1, "\u03CE"], [[8062, 8063], 3], [8064, 1, "\u1F00\u03B9"], [8065, 1, "\u1F01\u03B9"], [8066, 1, "\u1F02\u03B9"], [8067, 1, "\u1F03\u03B9"], [8068, 1, "\u1F04\u03B9"], [8069, 1, "\u1F05\u03B9"], [8070, 1, "\u1F06\u03B9"], [8071, 1, "\u1F07\u03B9"], [8072, 1, "\u1F00\u03B9"], [8073, 1, "\u1F01\u03B9"], [8074, 1, "\u1F02\u03B9"], [8075, 1, "\u1F03\u03B9"], [8076, 1, "\u1F04\u03B9"], [8077, 1, "\u1F05\u03B9"], [8078, 1, "\u1F06\u03B9"], [8079, 1, "\u1F07\u03B9"], [8080, 1, "\u1F20\u03B9"], [8081, 1, "\u1F21\u03B9"], [8082, 1, "\u1F22\u03B9"], [8083, 1, "\u1F23\u03B9"], [8084, 1, "\u1F24\u03B9"], [8085, 1, "\u1F25\u03B9"], [8086, 1, "\u1F26\u03B9"], [8087, 1, "\u1F27\u03B9"], [8088, 1, "\u1F20\u03B9"], [8089, 1, "\u1F21\u03B9"], [8090, 1, "\u1F22\u03B9"], [8091, 1, "\u1F23\u03B9"], [8092, 1, "\u1F24\u03B9"], [8093, 1, "\u1F25\u03B9"], [8094, 1, "\u1F26\u03B9"], [8095, 1, "\u1F27\u03B9"], [8096, 1, "\u1F60\u03B9"], [8097, 1, "\u1F61\u03B9"], [8098, 1, "\u1F62\u03B9"], [8099, 1, "\u1F63\u03B9"], [8100, 1, "\u1F64\u03B9"], [8101, 1, "\u1F65\u03B9"], [8102, 1, "\u1F66\u03B9"], [8103, 1, "\u1F67\u03B9"], [8104, 1, "\u1F60\u03B9"], [8105, 1, "\u1F61\u03B9"], [8106, 1, "\u1F62\u03B9"], [8107, 1, "\u1F63\u03B9"], [8108, 1, "\u1F64\u03B9"], [8109, 1, "\u1F65\u03B9"], [8110, 1, "\u1F66\u03B9"], [8111, 1, "\u1F67\u03B9"], [[8112, 8113], 2], [8114, 1, "\u1F70\u03B9"], [8115, 1, "\u03B1\u03B9"], [8116, 1, "\u03AC\u03B9"], [8117, 3], [8118, 2], [8119, 1, "\u1FB6\u03B9"], [8120, 1, "\u1FB0"], [8121, 1, "\u1FB1"], [8122, 1, "\u1F70"], [8123, 1, "\u03AC"], [8124, 1, "\u03B1\u03B9"], [8125, 1, " \u0313"], [8126, 1, "\u03B9"], [8127, 1, " \u0313"], [8128, 1, " \u0342"], [8129, 1, " \u0308\u0342"], [8130, 1, "\u1F74\u03B9"], [8131, 1, "\u03B7\u03B9"], [8132, 1, "\u03AE\u03B9"], [8133, 3], [8134, 2], [8135, 1, "\u1FC6\u03B9"], [8136, 1, "\u1F72"], [8137, 1, "\u03AD"], [8138, 1, "\u1F74"], [8139, 1, "\u03AE"], [8140, 1, "\u03B7\u03B9"], [8141, 1, " \u0313\u0300"], [8142, 1, " \u0313\u0301"], [8143, 1, " \u0313\u0342"], [[8144, 8146], 2], [8147, 1, "\u0390"], [[8148, 8149], 3], [[8150, 8151], 2], [8152, 1, "\u1FD0"], [8153, 1, "\u1FD1"], [8154, 1, "\u1F76"], [8155, 1, "\u03AF"], [8156, 3], [8157, 1, " \u0314\u0300"], [8158, 1, " \u0314\u0301"], [8159, 1, " \u0314\u0342"], [[8160, 8162], 2], [8163, 1, "\u03B0"], [[8164, 8167], 2], [8168, 1, "\u1FE0"], [8169, 1, "\u1FE1"], [8170, 1, "\u1F7A"], [8171, 1, "\u03CD"], [8172, 1, "\u1FE5"], [8173, 1, " \u0308\u0300"], [8174, 1, " \u0308\u0301"], [8175, 1, "`"], [[8176, 8177], 3], [8178, 1, "\u1F7C\u03B9"], [8179, 1, "\u03C9\u03B9"], [8180, 1, "\u03CE\u03B9"], [8181, 3], [8182, 2], [8183, 1, "\u1FF6\u03B9"], [8184, 1, "\u1F78"], [8185, 1, "\u03CC"], [8186, 1, "\u1F7C"], [8187, 1, "\u03CE"], [8188, 1, "\u03C9\u03B9"], [8189, 1, " \u0301"], [8190, 1, " \u0314"], [8191, 3], [[8192, 8202], 1, " "], [8203, 7], [[8204, 8205], 6, ""], [[8206, 8207], 3], [8208, 2], [8209, 1, "\u2010"], [[8210, 8214], 2], [8215, 1, " \u0333"], [[8216, 8227], 2], [[8228, 8230], 3], [8231, 2], [[8232, 8238], 3], [8239, 1, " "], [[8240, 8242], 2], [8243, 1, "\u2032\u2032"], [8244, 1, "\u2032\u2032\u2032"], [8245, 2], [8246, 1, "\u2035\u2035"], [8247, 1, "\u2035\u2035\u2035"], [[8248, 8251], 2], [8252, 1, "!!"], [8253, 2], [8254, 1, " \u0305"], [[8255, 8262], 2], [8263, 1, "??"], [8264, 1, "?!"], [8265, 1, "!?"], [[8266, 8269], 2], [[8270, 8274], 2], [[8275, 8276], 2], [[8277, 8278], 2], [8279, 1, "\u2032\u2032\u2032\u2032"], [[8280, 8286], 2], [8287, 1, " "], [[8288, 8291], 7], [8292, 7], [8293, 3], [[8294, 8297], 3], [[8298, 8303], 7], [8304, 1, "0"], [8305, 1, "i"], [[8306, 8307], 3], [8308, 1, "4"], [8309, 1, "5"], [8310, 1, "6"], [8311, 1, "7"], [8312, 1, "8"], [8313, 1, "9"], [8314, 1, "+"], [8315, 1, "\u2212"], [8316, 1, "="], [8317, 1, "("], [8318, 1, ")"], [8319, 1, "n"], [8320, 1, "0"], [8321, 1, "1"], [8322, 1, "2"], [8323, 1, "3"], [8324, 1, "4"], [8325, 1, "5"], [8326, 1, "6"], [8327, 1, "7"], [8328, 1, "8"], [8329, 1, "9"], [8330, 1, "+"], [8331, 1, "\u2212"], [8332, 1, "="], [8333, 1, "("], [8334, 1, ")"], [8335, 3], [8336, 1, "a"], [8337, 1, "e"], [8338, 1, "o"], [8339, 1, "x"], [8340, 1, "\u0259"], [8341, 1, "h"], [8342, 1, "k"], [8343, 1, "l"], [8344, 1, "m"], [8345, 1, "n"], [8346, 1, "p"], [8347, 1, "s"], [8348, 1, "t"], [[8349, 8351], 3], [[8352, 8359], 2], [8360, 1, "rs"], [[8361, 8362], 2], [8363, 2], [8364, 2], [[8365, 8367], 2], [[8368, 8369], 2], [[8370, 8373], 2], [[8374, 8376], 2], [8377, 2], [8378, 2], [[8379, 8381], 2], [8382, 2], [8383, 2], [8384, 2], [[8385, 8399], 3], [[8400, 8417], 2], [[8418, 8419], 2], [[8420, 8426], 2], [8427, 2], [[8428, 8431], 2], [8432, 2], [[8433, 8447], 3], [8448, 1, "a/c"], [8449, 1, "a/s"], [8450, 1, "c"], [8451, 1, "\xB0c"], [8452, 2], [8453, 1, "c/o"], [8454, 1, "c/u"], [8455, 1, "\u025B"], [8456, 2], [8457, 1, "\xB0f"], [8458, 1, "g"], [[8459, 8462], 1, "h"], [8463, 1, "\u0127"], [[8464, 8465], 1, "i"], [[8466, 8467], 1, "l"], [8468, 2], [8469, 1, "n"], [8470, 1, "no"], [[8471, 8472], 2], [8473, 1, "p"], [8474, 1, "q"], [[8475, 8477], 1, "r"], [[8478, 8479], 2], [8480, 1, "sm"], [8481, 1, "tel"], [8482, 1, "tm"], [8483, 2], [8484, 1, "z"], [8485, 2], [8486, 1, "\u03C9"], [8487, 2], [8488, 1, "z"], [8489, 2], [8490, 1, "k"], [8491, 1, "\xE5"], [8492, 1, "b"], [8493, 1, "c"], [8494, 2], [[8495, 8496], 1, "e"], [8497, 1, "f"], [8498, 1, "\u214E"], [8499, 1, "m"], [8500, 1, "o"], [8501, 1, "\u05D0"], [8502, 1, "\u05D1"], [8503, 1, "\u05D2"], [8504, 1, "\u05D3"], [8505, 1, "i"], [8506, 2], [8507, 1, "fax"], [8508, 1, "\u03C0"], [[8509, 8510], 1, "\u03B3"], [8511, 1, "\u03C0"], [8512, 1, "\u2211"], [[8513, 8516], 2], [[8517, 8518], 1, "d"], [8519, 1, "e"], [8520, 1, "i"], [8521, 1, "j"], [[8522, 8523], 2], [8524, 2], [8525, 2], [8526, 2], [8527, 2], [8528, 1, "1\u20447"], [8529, 1, "1\u20449"], [8530, 1, "1\u204410"], [8531, 1, "1\u20443"], [8532, 1, "2\u20443"], [8533, 1, "1\u20445"], [8534, 1, "2\u20445"], [8535, 1, "3\u20445"], [8536, 1, "4\u20445"], [8537, 1, "1\u20446"], [8538, 1, "5\u20446"], [8539, 1, "1\u20448"], [8540, 1, "3\u20448"], [8541, 1, "5\u20448"], [8542, 1, "7\u20448"], [8543, 1, "1\u2044"], [8544, 1, "i"], [8545, 1, "ii"], [8546, 1, "iii"], [8547, 1, "iv"], [8548, 1, "v"], [8549, 1, "vi"], [8550, 1, "vii"], [8551, 1, "viii"], [8552, 1, "ix"], [8553, 1, "x"], [8554, 1, "xi"], [8555, 1, "xii"], [8556, 1, "l"], [8557, 1, "c"], [8558, 1, "d"], [8559, 1, "m"], [8560, 1, "i"], [8561, 1, "ii"], [8562, 1, "iii"], [8563, 1, "iv"], [8564, 1, "v"], [8565, 1, "vi"], [8566, 1, "vii"], [8567, 1, "viii"], [8568, 1, "ix"], [8569, 1, "x"], [8570, 1, "xi"], [8571, 1, "xii"], [8572, 1, "l"], [8573, 1, "c"], [8574, 1, "d"], [8575, 1, "m"], [[8576, 8578], 2], [8579, 1, "\u2184"], [8580, 2], [[8581, 8584], 2], [8585, 1, "0\u20443"], [[8586, 8587], 2], [[8588, 8591], 3], [[8592, 8682], 2], [[8683, 8691], 2], [[8692, 8703], 2], [[8704, 8747], 2], [8748, 1, "\u222B\u222B"], [8749, 1, "\u222B\u222B\u222B"], [8750, 2], [8751, 1, "\u222E\u222E"], [8752, 1, "\u222E\u222E\u222E"], [[8753, 8945], 2], [[8946, 8959], 2], [8960, 2], [8961, 2], [[8962, 9e3], 2], [9001, 1, "\u3008"], [9002, 1, "\u3009"], [[9003, 9082], 2], [9083, 2], [9084, 2], [[9085, 9114], 2], [[9115, 9166], 2], [[9167, 9168], 2], [[9169, 9179], 2], [[9180, 9191], 2], [9192, 2], [[9193, 9203], 2], [[9204, 9210], 2], [[9211, 9214], 2], [9215, 2], [[9216, 9252], 2], [[9253, 9254], 2], [[9255, 9257], 2], [[9258, 9279], 3], [[9280, 9290], 2], [[9291, 9311], 3], [9312, 1, "1"], [9313, 1, "2"], [9314, 1, "3"], [9315, 1, "4"], [9316, 1, "5"], [9317, 1, "6"], [9318, 1, "7"], [9319, 1, "8"], [9320, 1, "9"], [9321, 1, "10"], [9322, 1, "11"], [9323, 1, "12"], [9324, 1, "13"], [9325, 1, "14"], [9326, 1, "15"], [9327, 1, "16"], [9328, 1, "17"], [9329, 1, "18"], [9330, 1, "19"], [9331, 1, "20"], [9332, 1, "(1)"], [9333, 1, "(2)"], [9334, 1, "(3)"], [9335, 1, "(4)"], [9336, 1, "(5)"], [9337, 1, "(6)"], [9338, 1, "(7)"], [9339, 1, "(8)"], [9340, 1, "(9)"], [9341, 1, "(10)"], [9342, 1, "(11)"], [9343, 1, "(12)"], [9344, 1, "(13)"], [9345, 1, "(14)"], [9346, 1, "(15)"], [9347, 1, "(16)"], [9348, 1, "(17)"], [9349, 1, "(18)"], [9350, 1, "(19)"], [9351, 1, "(20)"], [[9352, 9371], 3], [9372, 1, "(a)"], [9373, 1, "(b)"], [9374, 1, "(c)"], [9375, 1, "(d)"], [9376, 1, "(e)"], [9377, 1, "(f)"], [9378, 1, "(g)"], [9379, 1, "(h)"], [9380, 1, "(i)"], [9381, 1, "(j)"], [9382, 1, "(k)"], [9383, 1, "(l)"], [9384, 1, "(m)"], [9385, 1, "(n)"], [9386, 1, "(o)"], [9387, 1, "(p)"], [9388, 1, "(q)"], [9389, 1, "(r)"], [9390, 1, "(s)"], [9391, 1, "(t)"], [9392, 1, "(u)"], [9393, 1, "(v)"], [9394, 1, "(w)"], [9395, 1, "(x)"], [9396, 1, "(y)"], [9397, 1, "(z)"], [9398, 1, "a"], [9399, 1, "b"], [9400, 1, "c"], [9401, 1, "d"], [9402, 1, "e"], [9403, 1, "f"], [9404, 1, "g"], [9405, 1, "h"], [9406, 1, "i"], [9407, 1, "j"], [9408, 1, "k"], [9409, 1, "l"], [9410, 1, "m"], [9411, 1, "n"], [9412, 1, "o"], [9413, 1, "p"], [9414, 1, "q"], [9415, 1, "r"], [9416, 1, "s"], [9417, 1, "t"], [9418, 1, "u"], [9419, 1, "v"], [9420, 1, "w"], [9421, 1, "x"], [9422, 1, "y"], [9423, 1, "z"], [9424, 1, "a"], [9425, 1, "b"], [9426, 1, "c"], [9427, 1, "d"], [9428, 1, "e"], [9429, 1, "f"], [9430, 1, "g"], [9431, 1, "h"], [9432, 1, "i"], [9433, 1, "j"], [9434, 1, "k"], [9435, 1, "l"], [9436, 1, "m"], [9437, 1, "n"], [9438, 1, "o"], [9439, 1, "p"], [9440, 1, "q"], [9441, 1, "r"], [9442, 1, "s"], [9443, 1, "t"], [9444, 1, "u"], [9445, 1, "v"], [9446, 1, "w"], [9447, 1, "x"], [9448, 1, "y"], [9449, 1, "z"], [9450, 1, "0"], [[9451, 9470], 2], [9471, 2], [[9472, 9621], 2], [[9622, 9631], 2], [[9632, 9711], 2], [[9712, 9719], 2], [[9720, 9727], 2], [[9728, 9747], 2], [[9748, 9749], 2], [[9750, 9751], 2], [9752, 2], [9753, 2], [[9754, 9839], 2], [[9840, 9841], 2], [[9842, 9853], 2], [[9854, 9855], 2], [[9856, 9865], 2], [[9866, 9873], 2], [[9874, 9884], 2], [9885, 2], [[9886, 9887], 2], [[9888, 9889], 2], [[9890, 9905], 2], [9906, 2], [[9907, 9916], 2], [[9917, 9919], 2], [[9920, 9923], 2], [[9924, 9933], 2], [9934, 2], [[9935, 9953], 2], [9954, 2], [9955, 2], [[9956, 9959], 2], [[9960, 9983], 2], [9984, 2], [[9985, 9988], 2], [9989, 2], [[9990, 9993], 2], [[9994, 9995], 2], [[9996, 10023], 2], [10024, 2], [[10025, 10059], 2], [10060, 2], [10061, 2], [10062, 2], [[10063, 10066], 2], [[10067, 10069], 2], [10070, 2], [10071, 2], [[10072, 10078], 2], [[10079, 10080], 2], [[10081, 10087], 2], [[10088, 10101], 2], [[10102, 10132], 2], [[10133, 10135], 2], [[10136, 10159], 2], [10160, 2], [[10161, 10174], 2], [10175, 2], [[10176, 10182], 2], [[10183, 10186], 2], [10187, 2], [10188, 2], [10189, 2], [[10190, 10191], 2], [[10192, 10219], 2], [[10220, 10223], 2], [[10224, 10239], 2], [[10240, 10495], 2], [[10496, 10763], 2], [10764, 1, "\u222B\u222B\u222B\u222B"], [[10765, 10867], 2], [10868, 1, "::="], [10869, 1, "=="], [10870, 1, "==="], [[10871, 10971], 2], [10972, 1, "\u2ADD\u0338"], [[10973, 11007], 2], [[11008, 11021], 2], [[11022, 11027], 2], [[11028, 11034], 2], [[11035, 11039], 2], [[11040, 11043], 2], [[11044, 11084], 2], [[11085, 11087], 2], [[11088, 11092], 2], [[11093, 11097], 2], [[11098, 11123], 2], [[11124, 11125], 3], [[11126, 11157], 2], [11158, 3], [11159, 2], [[11160, 11193], 2], [[11194, 11196], 2], [[11197, 11208], 2], [11209, 2], [[11210, 11217], 2], [11218, 2], [[11219, 11243], 2], [[11244, 11247], 2], [[11248, 11262], 2], [11263, 2], [11264, 1, "\u2C30"], [11265, 1, "\u2C31"], [11266, 1, "\u2C32"], [11267, 1, "\u2C33"], [11268, 1, "\u2C34"], [11269, 1, "\u2C35"], [11270, 1, "\u2C36"], [11271, 1, "\u2C37"], [11272, 1, "\u2C38"], [11273, 1, "\u2C39"], [11274, 1, "\u2C3A"], [11275, 1, "\u2C3B"], [11276, 1, "\u2C3C"], [11277, 1, "\u2C3D"], [11278, 1, "\u2C3E"], [11279, 1, "\u2C3F"], [11280, 1, "\u2C40"], [11281, 1, "\u2C41"], [11282, 1, "\u2C42"], [11283, 1, "\u2C43"], [11284, 1, "\u2C44"], [11285, 1, "\u2C45"], [11286, 1, "\u2C46"], [11287, 1, "\u2C47"], [11288, 1, "\u2C48"], [11289, 1, "\u2C49"], [11290, 1, "\u2C4A"], [11291, 1, "\u2C4B"], [11292, 1, "\u2C4C"], [11293, 1, "\u2C4D"], [11294, 1, "\u2C4E"], [11295, 1, "\u2C4F"], [11296, 1, "\u2C50"], [11297, 1, "\u2C51"], [11298, 1, "\u2C52"], [11299, 1, "\u2C53"], [11300, 1, "\u2C54"], [11301, 1, "\u2C55"], [11302, 1, "\u2C56"], [11303, 1, "\u2C57"], [11304, 1, "\u2C58"], [11305, 1, "\u2C59"], [11306, 1, "\u2C5A"], [11307, 1, "\u2C5B"], [11308, 1, "\u2C5C"], [11309, 1, "\u2C5D"], [11310, 1, "\u2C5E"], [11311, 1, "\u2C5F"], [[11312, 11358], 2], [11359, 2], [11360, 1, "\u2C61"], [11361, 2], [11362, 1, "\u026B"], [11363, 1, "\u1D7D"], [11364, 1, "\u027D"], [[11365, 11366], 2], [11367, 1, "\u2C68"], [11368, 2], [11369, 1, "\u2C6A"], [11370, 2], [11371, 1, "\u2C6C"], [11372, 2], [11373, 1, "\u0251"], [11374, 1, "\u0271"], [11375, 1, "\u0250"], [11376, 1, "\u0252"], [11377, 2], [11378, 1, "\u2C73"], [11379, 2], [11380, 2], [11381, 1, "\u2C76"], [[11382, 11383], 2], [[11384, 11387], 2], [11388, 1, "j"], [11389, 1, "v"], [11390, 1, "\u023F"], [11391, 1, "\u0240"], [11392, 1, "\u2C81"], [11393, 2], [11394, 1, "\u2C83"], [11395, 2], [11396, 1, "\u2C85"], [11397, 2], [11398, 1, "\u2C87"], [11399, 2], [11400, 1, "\u2C89"], [11401, 2], [11402, 1, "\u2C8B"], [11403, 2], [11404, 1, "\u2C8D"], [11405, 2], [11406, 1, "\u2C8F"], [11407, 2], [11408, 1, "\u2C91"], [11409, 2], [11410, 1, "\u2C93"], [11411, 2], [11412, 1, "\u2C95"], [11413, 2], [11414, 1, "\u2C97"], [11415, 2], [11416, 1, "\u2C99"], [11417, 2], [11418, 1, "\u2C9B"], [11419, 2], [11420, 1, "\u2C9D"], [11421, 2], [11422, 1, "\u2C9F"], [11423, 2], [11424, 1, "\u2CA1"], [11425, 2], [11426, 1, "\u2CA3"], [11427, 2], [11428, 1, "\u2CA5"], [11429, 2], [11430, 1, "\u2CA7"], [11431, 2], [11432, 1, "\u2CA9"], [11433, 2], [11434, 1, "\u2CAB"], [11435, 2], [11436, 1, "\u2CAD"], [11437, 2], [11438, 1, "\u2CAF"], [11439, 2], [11440, 1, "\u2CB1"], [11441, 2], [11442, 1, "\u2CB3"], [11443, 2], [11444, 1, "\u2CB5"], [11445, 2], [11446, 1, "\u2CB7"], [11447, 2], [11448, 1, "\u2CB9"], [11449, 2], [11450, 1, "\u2CBB"], [11451, 2], [11452, 1, "\u2CBD"], [11453, 2], [11454, 1, "\u2CBF"], [11455, 2], [11456, 1, "\u2CC1"], [11457, 2], [11458, 1, "\u2CC3"], [11459, 2], [11460, 1, "\u2CC5"], [11461, 2], [11462, 1, "\u2CC7"], [11463, 2], [11464, 1, "\u2CC9"], [11465, 2], [11466, 1, "\u2CCB"], [11467, 2], [11468, 1, "\u2CCD"], [11469, 2], [11470, 1, "\u2CCF"], [11471, 2], [11472, 1, "\u2CD1"], [11473, 2], [11474, 1, "\u2CD3"], [11475, 2], [11476, 1, "\u2CD5"], [11477, 2], [11478, 1, "\u2CD7"], [11479, 2], [11480, 1, "\u2CD9"], [11481, 2], [11482, 1, "\u2CDB"], [11483, 2], [11484, 1, "\u2CDD"], [11485, 2], [11486, 1, "\u2CDF"], [11487, 2], [11488, 1, "\u2CE1"], [11489, 2], [11490, 1, "\u2CE3"], [[11491, 11492], 2], [[11493, 11498], 2], [11499, 1, "\u2CEC"], [11500, 2], [11501, 1, "\u2CEE"], [[11502, 11505], 2], [11506, 1, "\u2CF3"], [11507, 2], [[11508, 11512], 3], [[11513, 11519], 2], [[11520, 11557], 2], [11558, 3], [11559, 2], [[11560, 11564], 3], [11565, 2], [[11566, 11567], 3], [[11568, 11621], 2], [[11622, 11623], 2], [[11624, 11630], 3], [11631, 1, "\u2D61"], [11632, 2], [[11633, 11646], 3], [11647, 2], [[11648, 11670], 2], [[11671, 11679], 3], [[11680, 11686], 2], [11687, 3], [[11688, 11694], 2], [11695, 3], [[11696, 11702], 2], [11703, 3], [[11704, 11710], 2], [11711, 3], [[11712, 11718], 2], [11719, 3], [[11720, 11726], 2], [11727, 3], [[11728, 11734], 2], [11735, 3], [[11736, 11742], 2], [11743, 3], [[11744, 11775], 2], [[11776, 11799], 2], [[11800, 11803], 2], [[11804, 11805], 2], [[11806, 11822], 2], [11823, 2], [11824, 2], [11825, 2], [[11826, 11835], 2], [[11836, 11842], 2], [[11843, 11844], 2], [[11845, 11849], 2], [[11850, 11854], 2], [11855, 2], [[11856, 11858], 2], [[11859, 11869], 2], [[11870, 11903], 3], [[11904, 11929], 2], [11930, 3], [[11931, 11934], 2], [11935, 1, "\u6BCD"], [[11936, 12018], 2], [12019, 1, "\u9F9F"], [[12020, 12031], 3], [12032, 1, "\u4E00"], [12033, 1, "\u4E28"], [12034, 1, "\u4E36"], [12035, 1, "\u4E3F"], [12036, 1, "\u4E59"], [12037, 1, "\u4E85"], [12038, 1, "\u4E8C"], [12039, 1, "\u4EA0"], [12040, 1, "\u4EBA"], [12041, 1, "\u513F"], [12042, 1, "\u5165"], [12043, 1, "\u516B"], [12044, 1, "\u5182"], [12045, 1, "\u5196"], [12046, 1, "\u51AB"], [12047, 1, "\u51E0"], [12048, 1, "\u51F5"], [12049, 1, "\u5200"], [12050, 1, "\u529B"], [12051, 1, "\u52F9"], [12052, 1, "\u5315"], [12053, 1, "\u531A"], [12054, 1, "\u5338"], [12055, 1, "\u5341"], [12056, 1, "\u535C"], [12057, 1, "\u5369"], [12058, 1, "\u5382"], [12059, 1, "\u53B6"], [12060, 1, "\u53C8"], [12061, 1, "\u53E3"], [12062, 1, "\u56D7"], [12063, 1, "\u571F"], [12064, 1, "\u58EB"], [12065, 1, "\u5902"], [12066, 1, "\u590A"], [12067, 1, "\u5915"], [12068, 1, "\u5927"], [12069, 1, "\u5973"], [12070, 1, "\u5B50"], [12071, 1, "\u5B80"], [12072, 1, "\u5BF8"], [12073, 1, "\u5C0F"], [12074, 1, "\u5C22"], [12075, 1, "\u5C38"], [12076, 1, "\u5C6E"], [12077, 1, "\u5C71"], [12078, 1, "\u5DDB"], [12079, 1, "\u5DE5"], [12080, 1, "\u5DF1"], [12081, 1, "\u5DFE"], [12082, 1, "\u5E72"], [12083, 1, "\u5E7A"], [12084, 1, "\u5E7F"], [12085, 1, "\u5EF4"], [12086, 1, "\u5EFE"], [12087, 1, "\u5F0B"], [12088, 1, "\u5F13"], [12089, 1, "\u5F50"], [12090, 1, "\u5F61"], [12091, 1, "\u5F73"], [12092, 1, "\u5FC3"], [12093, 1, "\u6208"], [12094, 1, "\u6236"], [12095, 1, "\u624B"], [12096, 1, "\u652F"], [12097, 1, "\u6534"], [12098, 1, "\u6587"], [12099, 1, "\u6597"], [12100, 1, "\u65A4"], [12101, 1, "\u65B9"], [12102, 1, "\u65E0"], [12103, 1, "\u65E5"], [12104, 1, "\u66F0"], [12105, 1, "\u6708"], [12106, 1, "\u6728"], [12107, 1, "\u6B20"], [12108, 1, "\u6B62"], [12109, 1, "\u6B79"], [12110, 1, "\u6BB3"], [12111, 1, "\u6BCB"], [12112, 1, "\u6BD4"], [12113, 1, "\u6BDB"], [12114, 1, "\u6C0F"], [12115, 1, "\u6C14"], [12116, 1, "\u6C34"], [12117, 1, "\u706B"], [12118, 1, "\u722A"], [12119, 1, "\u7236"], [12120, 1, "\u723B"], [12121, 1, "\u723F"], [12122, 1, "\u7247"], [12123, 1, "\u7259"], [12124, 1, "\u725B"], [12125, 1, "\u72AC"], [12126, 1, "\u7384"], [12127, 1, "\u7389"], [12128, 1, "\u74DC"], [12129, 1, "\u74E6"], [12130, 1, "\u7518"], [12131, 1, "\u751F"], [12132, 1, "\u7528"], [12133, 1, "\u7530"], [12134, 1, "\u758B"], [12135, 1, "\u7592"], [12136, 1, "\u7676"], [12137, 1, "\u767D"], [12138, 1, "\u76AE"], [12139, 1, "\u76BF"], [12140, 1, "\u76EE"], [12141, 1, "\u77DB"], [12142, 1, "\u77E2"], [12143, 1, "\u77F3"], [12144, 1, "\u793A"], [12145, 1, "\u79B8"], [12146, 1, "\u79BE"], [12147, 1, "\u7A74"], [12148, 1, "\u7ACB"], [12149, 1, "\u7AF9"], [12150, 1, "\u7C73"], [12151, 1, "\u7CF8"], [12152, 1, "\u7F36"], [12153, 1, "\u7F51"], [12154, 1, "\u7F8A"], [12155, 1, "\u7FBD"], [12156, 1, "\u8001"], [12157, 1, "\u800C"], [12158, 1, "\u8012"], [12159, 1, "\u8033"], [12160, 1, "\u807F"], [12161, 1, "\u8089"], [12162, 1, "\u81E3"], [12163, 1, "\u81EA"], [12164, 1, "\u81F3"], [12165, 1, "\u81FC"], [12166, 1, "\u820C"], [12167, 1, "\u821B"], [12168, 1, "\u821F"], [12169, 1, "\u826E"], [12170, 1, "\u8272"], [12171, 1, "\u8278"], [12172, 1, "\u864D"], [12173, 1, "\u866B"], [12174, 1, "\u8840"], [12175, 1, "\u884C"], [12176, 1, "\u8863"], [12177, 1, "\u897E"], [12178, 1, "\u898B"], [12179, 1, "\u89D2"], [12180, 1, "\u8A00"], [12181, 1, "\u8C37"], [12182, 1, "\u8C46"], [12183, 1, "\u8C55"], [12184, 1, "\u8C78"], [12185, 1, "\u8C9D"], [12186, 1, "\u8D64"], [12187, 1, "\u8D70"], [12188, 1, "\u8DB3"], [12189, 1, "\u8EAB"], [12190, 1, "\u8ECA"], [12191, 1, "\u8F9B"], [12192, 1, "\u8FB0"], [12193, 1, "\u8FB5"], [12194, 1, "\u9091"], [12195, 1, "\u9149"], [12196, 1, "\u91C6"], [12197, 1, "\u91CC"], [12198, 1, "\u91D1"], [12199, 1, "\u9577"], [12200, 1, "\u9580"], [12201, 1, "\u961C"], [12202, 1, "\u96B6"], [12203, 1, "\u96B9"], [12204, 1, "\u96E8"], [12205, 1, "\u9751"], [12206, 1, "\u975E"], [12207, 1, "\u9762"], [12208, 1, "\u9769"], [12209, 1, "\u97CB"], [12210, 1, "\u97ED"], [12211, 1, "\u97F3"], [12212, 1, "\u9801"], [12213, 1, "\u98A8"], [12214, 1, "\u98DB"], [12215, 1, "\u98DF"], [12216, 1, "\u9996"], [12217, 1, "\u9999"], [12218, 1, "\u99AC"], [12219, 1, "\u9AA8"], [12220, 1, "\u9AD8"], [12221, 1, "\u9ADF"], [12222, 1, "\u9B25"], [12223, 1, "\u9B2F"], [12224, 1, "\u9B32"], [12225, 1, "\u9B3C"], [12226, 1, "\u9B5A"], [12227, 1, "\u9CE5"], [12228, 1, "\u9E75"], [12229, 1, "\u9E7F"], [12230, 1, "\u9EA5"], [12231, 1, "\u9EBB"], [12232, 1, "\u9EC3"], [12233, 1, "\u9ECD"], [12234, 1, "\u9ED1"], [12235, 1, "\u9EF9"], [12236, 1, "\u9EFD"], [12237, 1, "\u9F0E"], [12238, 1, "\u9F13"], [12239, 1, "\u9F20"], [12240, 1, "\u9F3B"], [12241, 1, "\u9F4A"], [12242, 1, "\u9F52"], [12243, 1, "\u9F8D"], [12244, 1, "\u9F9C"], [12245, 1, "\u9FA0"], [[12246, 12271], 3], [[12272, 12283], 3], [[12284, 12287], 3], [12288, 1, " "], [12289, 2], [12290, 1, "."], [[12291, 12292], 2], [[12293, 12295], 2], [[12296, 12329], 2], [[12330, 12333], 2], [[12334, 12341], 2], [12342, 1, "\u3012"], [12343, 2], [12344, 1, "\u5341"], [12345, 1, "\u5344"], [12346, 1, "\u5345"], [12347, 2], [12348, 2], [12349, 2], [12350, 2], [12351, 2], [12352, 3], [[12353, 12436], 2], [[12437, 12438], 2], [[12439, 12440], 3], [[12441, 12442], 2], [12443, 1, " \u3099"], [12444, 1, " \u309A"], [[12445, 12446], 2], [12447, 1, "\u3088\u308A"], [12448, 2], [[12449, 12542], 2], [12543, 1, "\u30B3\u30C8"], [[12544, 12548], 3], [[12549, 12588], 2], [12589, 2], [12590, 2], [12591, 2], [12592, 3], [12593, 1, "\u1100"], [12594, 1, "\u1101"], [12595, 1, "\u11AA"], [12596, 1, "\u1102"], [12597, 1, "\u11AC"], [12598, 1, "\u11AD"], [12599, 1, "\u1103"], [12600, 1, "\u1104"], [12601, 1, "\u1105"], [12602, 1, "\u11B0"], [12603, 1, "\u11B1"], [12604, 1, "\u11B2"], [12605, 1, "\u11B3"], [12606, 1, "\u11B4"], [12607, 1, "\u11B5"], [12608, 1, "\u111A"], [12609, 1, "\u1106"], [12610, 1, "\u1107"], [12611, 1, "\u1108"], [12612, 1, "\u1121"], [12613, 1, "\u1109"], [12614, 1, "\u110A"], [12615, 1, "\u110B"], [12616, 1, "\u110C"], [12617, 1, "\u110D"], [12618, 1, "\u110E"], [12619, 1, "\u110F"], [12620, 1, "\u1110"], [12621, 1, "\u1111"], [12622, 1, "\u1112"], [12623, 1, "\u1161"], [12624, 1, "\u1162"], [12625, 1, "\u1163"], [12626, 1, "\u1164"], [12627, 1, "\u1165"], [12628, 1, "\u1166"], [12629, 1, "\u1167"], [12630, 1, "\u1168"], [12631, 1, "\u1169"], [12632, 1, "\u116A"], [12633, 1, "\u116B"], [12634, 1, "\u116C"], [12635, 1, "\u116D"], [12636, 1, "\u116E"], [12637, 1, "\u116F"], [12638, 1, "\u1170"], [12639, 1, "\u1171"], [12640, 1, "\u1172"], [12641, 1, "\u1173"], [12642, 1, "\u1174"], [12643, 1, "\u1175"], [12644, 7], [12645, 1, "\u1114"], [12646, 1, "\u1115"], [12647, 1, "\u11C7"], [12648, 1, "\u11C8"], [12649, 1, "\u11CC"], [12650, 1, "\u11CE"], [12651, 1, "\u11D3"], [12652, 1, "\u11D7"], [12653, 1, "\u11D9"], [12654, 1, "\u111C"], [12655, 1, "\u11DD"], [12656, 1, "\u11DF"], [12657, 1, "\u111D"], [12658, 1, "\u111E"], [12659, 1, "\u1120"], [12660, 1, "\u1122"], [12661, 1, "\u1123"], [12662, 1, "\u1127"], [12663, 1, "\u1129"], [12664, 1, "\u112B"], [12665, 1, "\u112C"], [12666, 1, "\u112D"], [12667, 1, "\u112E"], [12668, 1, "\u112F"], [12669, 1, "\u1132"], [12670, 1, "\u1136"], [12671, 1, "\u1140"], [12672, 1, "\u1147"], [12673, 1, "\u114C"], [12674, 1, "\u11F1"], [12675, 1, "\u11F2"], [12676, 1, "\u1157"], [12677, 1, "\u1158"], [12678, 1, "\u1159"], [12679, 1, "\u1184"], [12680, 1, "\u1185"], [12681, 1, "\u1188"], [12682, 1, "\u1191"], [12683, 1, "\u1192"], [12684, 1, "\u1194"], [12685, 1, "\u119E"], [12686, 1, "\u11A1"], [12687, 3], [[12688, 12689], 2], [12690, 1, "\u4E00"], [12691, 1, "\u4E8C"], [12692, 1, "\u4E09"], [12693, 1, "\u56DB"], [12694, 1, "\u4E0A"], [12695, 1, "\u4E2D"], [12696, 1, "\u4E0B"], [12697, 1, "\u7532"], [12698, 1, "\u4E59"], [12699, 1, "\u4E19"], [12700, 1, "\u4E01"], [12701, 1, "\u5929"], [12702, 1, "\u5730"], [12703, 1, "\u4EBA"], [[12704, 12727], 2], [[12728, 12730], 2], [[12731, 12735], 2], [[12736, 12751], 2], [[12752, 12771], 2], [[12772, 12773], 2], [[12774, 12782], 3], [12783, 3], [[12784, 12799], 2], [12800, 1, "(\u1100)"], [12801, 1, "(\u1102)"], [12802, 1, "(\u1103)"], [12803, 1, "(\u1105)"], [12804, 1, "(\u1106)"], [12805, 1, "(\u1107)"], [12806, 1, "(\u1109)"], [12807, 1, "(\u110B)"], [12808, 1, "(\u110C)"], [12809, 1, "(\u110E)"], [12810, 1, "(\u110F)"], [12811, 1, "(\u1110)"], [12812, 1, "(\u1111)"], [12813, 1, "(\u1112)"], [12814, 1, "(\uAC00)"], [12815, 1, "(\uB098)"], [12816, 1, "(\uB2E4)"], [12817, 1, "(\uB77C)"], [12818, 1, "(\uB9C8)"], [12819, 1, "(\uBC14)"], [12820, 1, "(\uC0AC)"], [12821, 1, "(\uC544)"], [12822, 1, "(\uC790)"], [12823, 1, "(\uCC28)"], [12824, 1, "(\uCE74)"], [12825, 1, "(\uD0C0)"], [12826, 1, "(\uD30C)"], [12827, 1, "(\uD558)"], [12828, 1, "(\uC8FC)"], [12829, 1, "(\uC624\uC804)"], [12830, 1, "(\uC624\uD6C4)"], [12831, 3], [12832, 1, "(\u4E00)"], [12833, 1, "(\u4E8C)"], [12834, 1, "(\u4E09)"], [12835, 1, "(\u56DB)"], [12836, 1, "(\u4E94)"], [12837, 1, "(\u516D)"], [12838, 1, "(\u4E03)"], [12839, 1, "(\u516B)"], [12840, 1, "(\u4E5D)"], [12841, 1, "(\u5341)"], [12842, 1, "(\u6708)"], [12843, 1, "(\u706B)"], [12844, 1, "(\u6C34)"], [12845, 1, "(\u6728)"], [12846, 1, "(\u91D1)"], [12847, 1, "(\u571F)"], [12848, 1, "(\u65E5)"], [12849, 1, "(\u682A)"], [12850, 1, "(\u6709)"], [12851, 1, "(\u793E)"], [12852, 1, "(\u540D)"], [12853, 1, "(\u7279)"], [12854, 1, "(\u8CA1)"], [12855, 1, "(\u795D)"], [12856, 1, "(\u52B4)"], [12857, 1, "(\u4EE3)"], [12858, 1, "(\u547C)"], [12859, 1, "(\u5B66)"], [12860, 1, "(\u76E3)"], [12861, 1, "(\u4F01)"], [12862, 1, "(\u8CC7)"], [12863, 1, "(\u5354)"], [12864, 1, "(\u796D)"], [12865, 1, "(\u4F11)"], [12866, 1, "(\u81EA)"], [12867, 1, "(\u81F3)"], [12868, 1, "\u554F"], [12869, 1, "\u5E7C"], [12870, 1, "\u6587"], [12871, 1, "\u7B8F"], [[12872, 12879], 2], [12880, 1, "pte"], [12881, 1, "21"], [12882, 1, "22"], [12883, 1, "23"], [12884, 1, "24"], [12885, 1, "25"], [12886, 1, "26"], [12887, 1, "27"], [12888, 1, "28"], [12889, 1, "29"], [12890, 1, "30"], [12891, 1, "31"], [12892, 1, "32"], [12893, 1, "33"], [12894, 1, "34"], [12895, 1, "35"], [12896, 1, "\u1100"], [12897, 1, "\u1102"], [12898, 1, "\u1103"], [12899, 1, "\u1105"], [12900, 1, "\u1106"], [12901, 1, "\u1107"], [12902, 1, "\u1109"], [12903, 1, "\u110B"], [12904, 1, "\u110C"], [12905, 1, "\u110E"], [12906, 1, "\u110F"], [12907, 1, "\u1110"], [12908, 1, "\u1111"], [12909, 1, "\u1112"], [12910, 1, "\uAC00"], [12911, 1, "\uB098"], [12912, 1, "\uB2E4"], [12913, 1, "\uB77C"], [12914, 1, "\uB9C8"], [12915, 1, "\uBC14"], [12916, 1, "\uC0AC"], [12917, 1, "\uC544"], [12918, 1, "\uC790"], [12919, 1, "\uCC28"], [12920, 1, "\uCE74"], [12921, 1, "\uD0C0"], [12922, 1, "\uD30C"], [12923, 1, "\uD558"], [12924, 1, "\uCC38\uACE0"], [12925, 1, "\uC8FC\uC758"], [12926, 1, "\uC6B0"], [12927, 2], [12928, 1, "\u4E00"], [12929, 1, "\u4E8C"], [12930, 1, "\u4E09"], [12931, 1, "\u56DB"], [12932, 1, "\u4E94"], [12933, 1, "\u516D"], [12934, 1, "\u4E03"], [12935, 1, "\u516B"], [12936, 1, "\u4E5D"], [12937, 1, "\u5341"], [12938, 1, "\u6708"], [12939, 1, "\u706B"], [12940, 1, "\u6C34"], [12941, 1, "\u6728"], [12942, 1, "\u91D1"], [12943, 1, "\u571F"], [12944, 1, "\u65E5"], [12945, 1, "\u682A"], [12946, 1, "\u6709"], [12947, 1, "\u793E"], [12948, 1, "\u540D"], [12949, 1, "\u7279"], [12950, 1, "\u8CA1"], [12951, 1, "\u795D"], [12952, 1, "\u52B4"], [12953, 1, "\u79D8"], [12954, 1, "\u7537"], [12955, 1, "\u5973"], [12956, 1, "\u9069"], [12957, 1, "\u512A"], [12958, 1, "\u5370"], [12959, 1, "\u6CE8"], [12960, 1, "\u9805"], [12961, 1, "\u4F11"], [12962, 1, "\u5199"], [12963, 1, "\u6B63"], [12964, 1, "\u4E0A"], [12965, 1, "\u4E2D"], [12966, 1, "\u4E0B"], [12967, 1, "\u5DE6"], [12968, 1, "\u53F3"], [12969, 1, "\u533B"], [12970, 1, "\u5B97"], [12971, 1, "\u5B66"], [12972, 1, "\u76E3"], [12973, 1, "\u4F01"], [12974, 1, "\u8CC7"], [12975, 1, "\u5354"], [12976, 1, "\u591C"], [12977, 1, "36"], [12978, 1, "37"], [12979, 1, "38"], [12980, 1, "39"], [12981, 1, "40"], [12982, 1, "41"], [12983, 1, "42"], [12984, 1, "43"], [12985, 1, "44"], [12986, 1, "45"], [12987, 1, "46"], [12988, 1, "47"], [12989, 1, "48"], [12990, 1, "49"], [12991, 1, "50"], [12992, 1, "1\u6708"], [12993, 1, "2\u6708"], [12994, 1, "3\u6708"], [12995, 1, "4\u6708"], [12996, 1, "5\u6708"], [12997, 1, "6\u6708"], [12998, 1, "7\u6708"], [12999, 1, "8\u6708"], [13e3, 1, "9\u6708"], [13001, 1, "10\u6708"], [13002, 1, "11\u6708"], [13003, 1, "12\u6708"], [13004, 1, "hg"], [13005, 1, "erg"], [13006, 1, "ev"], [13007, 1, "ltd"], [13008, 1, "\u30A2"], [13009, 1, "\u30A4"], [13010, 1, "\u30A6"], [13011, 1, "\u30A8"], [13012, 1, "\u30AA"], [13013, 1, "\u30AB"], [13014, 1, "\u30AD"], [13015, 1, "\u30AF"], [13016, 1, "\u30B1"], [13017, 1, "\u30B3"], [13018, 1, "\u30B5"], [13019, 1, "\u30B7"], [13020, 1, "\u30B9"], [13021, 1, "\u30BB"], [13022, 1, "\u30BD"], [13023, 1, "\u30BF"], [13024, 1, "\u30C1"], [13025, 1, "\u30C4"], [13026, 1, "\u30C6"], [13027, 1, "\u30C8"], [13028, 1, "\u30CA"], [13029, 1, "\u30CB"], [13030, 1, "\u30CC"], [13031, 1, "\u30CD"], [13032, 1, "\u30CE"], [13033, 1, "\u30CF"], [13034, 1, "\u30D2"], [13035, 1, "\u30D5"], [13036, 1, "\u30D8"], [13037, 1, "\u30DB"], [13038, 1, "\u30DE"], [13039, 1, "\u30DF"], [13040, 1, "\u30E0"], [13041, 1, "\u30E1"], [13042, 1, "\u30E2"], [13043, 1, "\u30E4"], [13044, 1, "\u30E6"], [13045, 1, "\u30E8"], [13046, 1, "\u30E9"], [13047, 1, "\u30EA"], [13048, 1, "\u30EB"], [13049, 1, "\u30EC"], [13050, 1, "\u30ED"], [13051, 1, "\u30EF"], [13052, 1, "\u30F0"], [13053, 1, "\u30F1"], [13054, 1, "\u30F2"], [13055, 1, "\u4EE4\u548C"], [13056, 1, "\u30A2\u30D1\u30FC\u30C8"], [13057, 1, "\u30A2\u30EB\u30D5\u30A1"], [13058, 1, "\u30A2\u30F3\u30DA\u30A2"], [13059, 1, "\u30A2\u30FC\u30EB"], [13060, 1, "\u30A4\u30CB\u30F3\u30B0"], [13061, 1, "\u30A4\u30F3\u30C1"], [13062, 1, "\u30A6\u30A9\u30F3"], [13063, 1, "\u30A8\u30B9\u30AF\u30FC\u30C9"], [13064, 1, "\u30A8\u30FC\u30AB\u30FC"], [13065, 1, "\u30AA\u30F3\u30B9"], [13066, 1, "\u30AA\u30FC\u30E0"], [13067, 1, "\u30AB\u30A4\u30EA"], [13068, 1, "\u30AB\u30E9\u30C3\u30C8"], [13069, 1, "\u30AB\u30ED\u30EA\u30FC"], [13070, 1, "\u30AC\u30ED\u30F3"], [13071, 1, "\u30AC\u30F3\u30DE"], [13072, 1, "\u30AE\u30AC"], [13073, 1, "\u30AE\u30CB\u30FC"], [13074, 1, "\u30AD\u30E5\u30EA\u30FC"], [13075, 1, "\u30AE\u30EB\u30C0\u30FC"], [13076, 1, "\u30AD\u30ED"], [13077, 1, "\u30AD\u30ED\u30B0\u30E9\u30E0"], [13078, 1, "\u30AD\u30ED\u30E1\u30FC\u30C8\u30EB"], [13079, 1, "\u30AD\u30ED\u30EF\u30C3\u30C8"], [13080, 1, "\u30B0\u30E9\u30E0"], [13081, 1, "\u30B0\u30E9\u30E0\u30C8\u30F3"], [13082, 1, "\u30AF\u30EB\u30BC\u30A4\u30ED"], [13083, 1, "\u30AF\u30ED\u30FC\u30CD"], [13084, 1, "\u30B1\u30FC\u30B9"], [13085, 1, "\u30B3\u30EB\u30CA"], [13086, 1, "\u30B3\u30FC\u30DD"], [13087, 1, "\u30B5\u30A4\u30AF\u30EB"], [13088, 1, "\u30B5\u30F3\u30C1\u30FC\u30E0"], [13089, 1, "\u30B7\u30EA\u30F3\u30B0"], [13090, 1, "\u30BB\u30F3\u30C1"], [13091, 1, "\u30BB\u30F3\u30C8"], [13092, 1, "\u30C0\u30FC\u30B9"], [13093, 1, "\u30C7\u30B7"], [13094, 1, "\u30C9\u30EB"], [13095, 1, "\u30C8\u30F3"], [13096, 1, "\u30CA\u30CE"], [13097, 1, "\u30CE\u30C3\u30C8"], [13098, 1, "\u30CF\u30A4\u30C4"], [13099, 1, "\u30D1\u30FC\u30BB\u30F3\u30C8"], [13100, 1, "\u30D1\u30FC\u30C4"], [13101, 1, "\u30D0\u30FC\u30EC\u30EB"], [13102, 1, "\u30D4\u30A2\u30B9\u30C8\u30EB"], [13103, 1, "\u30D4\u30AF\u30EB"], [13104, 1, "\u30D4\u30B3"], [13105, 1, "\u30D3\u30EB"], [13106, 1, "\u30D5\u30A1\u30E9\u30C3\u30C9"], [13107, 1, "\u30D5\u30A3\u30FC\u30C8"], [13108, 1, "\u30D6\u30C3\u30B7\u30A7\u30EB"], [13109, 1, "\u30D5\u30E9\u30F3"], [13110, 1, "\u30D8\u30AF\u30BF\u30FC\u30EB"], [13111, 1, "\u30DA\u30BD"], [13112, 1, "\u30DA\u30CB\u30D2"], [13113, 1, "\u30D8\u30EB\u30C4"], [13114, 1, "\u30DA\u30F3\u30B9"], [13115, 1, "\u30DA\u30FC\u30B8"], [13116, 1, "\u30D9\u30FC\u30BF"], [13117, 1, "\u30DD\u30A4\u30F3\u30C8"], [13118, 1, "\u30DC\u30EB\u30C8"], [13119, 1, "\u30DB\u30F3"], [13120, 1, "\u30DD\u30F3\u30C9"], [13121, 1, "\u30DB\u30FC\u30EB"], [13122, 1, "\u30DB\u30FC\u30F3"], [13123, 1, "\u30DE\u30A4\u30AF\u30ED"], [13124, 1, "\u30DE\u30A4\u30EB"], [13125, 1, "\u30DE\u30C3\u30CF"], [13126, 1, "\u30DE\u30EB\u30AF"], [13127, 1, "\u30DE\u30F3\u30B7\u30E7\u30F3"], [13128, 1, "\u30DF\u30AF\u30ED\u30F3"], [13129, 1, "\u30DF\u30EA"], [13130, 1, "\u30DF\u30EA\u30D0\u30FC\u30EB"], [13131, 1, "\u30E1\u30AC"], [13132, 1, "\u30E1\u30AC\u30C8\u30F3"], [13133, 1, "\u30E1\u30FC\u30C8\u30EB"], [13134, 1, "\u30E4\u30FC\u30C9"], [13135, 1, "\u30E4\u30FC\u30EB"], [13136, 1, "\u30E6\u30A2\u30F3"], [13137, 1, "\u30EA\u30C3\u30C8\u30EB"], [13138, 1, "\u30EA\u30E9"], [13139, 1, "\u30EB\u30D4\u30FC"], [13140, 1, "\u30EB\u30FC\u30D6\u30EB"], [13141, 1, "\u30EC\u30E0"], [13142, 1, "\u30EC\u30F3\u30C8\u30B2\u30F3"], [13143, 1, "\u30EF\u30C3\u30C8"], [13144, 1, "0\u70B9"], [13145, 1, "1\u70B9"], [13146, 1, "2\u70B9"], [13147, 1, "3\u70B9"], [13148, 1, "4\u70B9"], [13149, 1, "5\u70B9"], [13150, 1, "6\u70B9"], [13151, 1, "7\u70B9"], [13152, 1, "8\u70B9"], [13153, 1, "9\u70B9"], [13154, 1, "10\u70B9"], [13155, 1, "11\u70B9"], [13156, 1, "12\u70B9"], [13157, 1, "13\u70B9"], [13158, 1, "14\u70B9"], [13159, 1, "15\u70B9"], [13160, 1, "16\u70B9"], [13161, 1, "17\u70B9"], [13162, 1, "18\u70B9"], [13163, 1, "19\u70B9"], [13164, 1, "20\u70B9"], [13165, 1, "21\u70B9"], [13166, 1, "22\u70B9"], [13167, 1, "23\u70B9"], [13168, 1, "24\u70B9"], [13169, 1, "hpa"], [13170, 1, "da"], [13171, 1, "au"], [13172, 1, "bar"], [13173, 1, "ov"], [13174, 1, "pc"], [13175, 1, "dm"], [13176, 1, "dm2"], [13177, 1, "dm3"], [13178, 1, "iu"], [13179, 1, "\u5E73\u6210"], [13180, 1, "\u662D\u548C"], [13181, 1, "\u5927\u6B63"], [13182, 1, "\u660E\u6CBB"], [13183, 1, "\u682A\u5F0F\u4F1A\u793E"], [13184, 1, "pa"], [13185, 1, "na"], [13186, 1, "\u03BCa"], [13187, 1, "ma"], [13188, 1, "ka"], [13189, 1, "kb"], [13190, 1, "mb"], [13191, 1, "gb"], [13192, 1, "cal"], [13193, 1, "kcal"], [13194, 1, "pf"], [13195, 1, "nf"], [13196, 1, "\u03BCf"], [13197, 1, "\u03BCg"], [13198, 1, "mg"], [13199, 1, "kg"], [13200, 1, "hz"], [13201, 1, "khz"], [13202, 1, "mhz"], [13203, 1, "ghz"], [13204, 1, "thz"], [13205, 1, "\u03BCl"], [13206, 1, "ml"], [13207, 1, "dl"], [13208, 1, "kl"], [13209, 1, "fm"], [13210, 1, "nm"], [13211, 1, "\u03BCm"], [13212, 1, "mm"], [13213, 1, "cm"], [13214, 1, "km"], [13215, 1, "mm2"], [13216, 1, "cm2"], [13217, 1, "m2"], [13218, 1, "km2"], [13219, 1, "mm3"], [13220, 1, "cm3"], [13221, 1, "m3"], [13222, 1, "km3"], [13223, 1, "m\u2215s"], [13224, 1, "m\u2215s2"], [13225, 1, "pa"], [13226, 1, "kpa"], [13227, 1, "mpa"], [13228, 1, "gpa"], [13229, 1, "rad"], [13230, 1, "rad\u2215s"], [13231, 1, "rad\u2215s2"], [13232, 1, "ps"], [13233, 1, "ns"], [13234, 1, "\u03BCs"], [13235, 1, "ms"], [13236, 1, "pv"], [13237, 1, "nv"], [13238, 1, "\u03BCv"], [13239, 1, "mv"], [13240, 1, "kv"], [13241, 1, "mv"], [13242, 1, "pw"], [13243, 1, "nw"], [13244, 1, "\u03BCw"], [13245, 1, "mw"], [13246, 1, "kw"], [13247, 1, "mw"], [13248, 1, "k\u03C9"], [13249, 1, "m\u03C9"], [13250, 3], [13251, 1, "bq"], [13252, 1, "cc"], [13253, 1, "cd"], [13254, 1, "c\u2215kg"], [13255, 3], [13256, 1, "db"], [13257, 1, "gy"], [13258, 1, "ha"], [13259, 1, "hp"], [13260, 1, "in"], [13261, 1, "kk"], [13262, 1, "km"], [13263, 1, "kt"], [13264, 1, "lm"], [13265, 1, "ln"], [13266, 1, "log"], [13267, 1, "lx"], [13268, 1, "mb"], [13269, 1, "mil"], [13270, 1, "mol"], [13271, 1, "ph"], [13272, 3], [13273, 1, "ppm"], [13274, 1, "pr"], [13275, 1, "sr"], [13276, 1, "sv"], [13277, 1, "wb"], [13278, 1, "v\u2215m"], [13279, 1, "a\u2215m"], [13280, 1, "1\u65E5"], [13281, 1, "2\u65E5"], [13282, 1, "3\u65E5"], [13283, 1, "4\u65E5"], [13284, 1, "5\u65E5"], [13285, 1, "6\u65E5"], [13286, 1, "7\u65E5"], [13287, 1, "8\u65E5"], [13288, 1, "9\u65E5"], [13289, 1, "10\u65E5"], [13290, 1, "11\u65E5"], [13291, 1, "12\u65E5"], [13292, 1, "13\u65E5"], [13293, 1, "14\u65E5"], [13294, 1, "15\u65E5"], [13295, 1, "16\u65E5"], [13296, 1, "17\u65E5"], [13297, 1, "18\u65E5"], [13298, 1, "19\u65E5"], [13299, 1, "20\u65E5"], [13300, 1, "21\u65E5"], [13301, 1, "22\u65E5"], [13302, 1, "23\u65E5"], [13303, 1, "24\u65E5"], [13304, 1, "25\u65E5"], [13305, 1, "26\u65E5"], [13306, 1, "27\u65E5"], [13307, 1, "28\u65E5"], [13308, 1, "29\u65E5"], [13309, 1, "30\u65E5"], [13310, 1, "31\u65E5"], [13311, 1, "gal"], [[13312, 19893], 2], [[19894, 19903], 2], [[19904, 19967], 2], [[19968, 40869], 2], [[40870, 40891], 2], [[40892, 40899], 2], [[40900, 40907], 2], [40908, 2], [[40909, 40917], 2], [[40918, 40938], 2], [[40939, 40943], 2], [[40944, 40956], 2], [[40957, 40959], 2], [[40960, 42124], 2], [[42125, 42127], 3], [[42128, 42145], 2], [[42146, 42147], 2], [[42148, 42163], 2], [42164, 2], [[42165, 42176], 2], [42177, 2], [[42178, 42180], 2], [42181, 2], [42182, 2], [[42183, 42191], 3], [[42192, 42237], 2], [[42238, 42239], 2], [[42240, 42508], 2], [[42509, 42511], 2], [[42512, 42539], 2], [[42540, 42559], 3], [42560, 1, "\uA641"], [42561, 2], [42562, 1, "\uA643"], [42563, 2], [42564, 1, "\uA645"], [42565, 2], [42566, 1, "\uA647"], [42567, 2], [42568, 1, "\uA649"], [42569, 2], [42570, 1, "\uA64B"], [42571, 2], [42572, 1, "\uA64D"], [42573, 2], [42574, 1, "\uA64F"], [42575, 2], [42576, 1, "\uA651"], [42577, 2], [42578, 1, "\uA653"], [42579, 2], [42580, 1, "\uA655"], [42581, 2], [42582, 1, "\uA657"], [42583, 2], [42584, 1, "\uA659"], [42585, 2], [42586, 1, "\uA65B"], [42587, 2], [42588, 1, "\uA65D"], [42589, 2], [42590, 1, "\uA65F"], [42591, 2], [42592, 1, "\uA661"], [42593, 2], [42594, 1, "\uA663"], [42595, 2], [42596, 1, "\uA665"], [42597, 2], [42598, 1, "\uA667"], [42599, 2], [42600, 1, "\uA669"], [42601, 2], [42602, 1, "\uA66B"], [42603, 2], [42604, 1, "\uA66D"], [[42605, 42607], 2], [[42608, 42611], 2], [[42612, 42619], 2], [[42620, 42621], 2], [42622, 2], [42623, 2], [42624, 1, "\uA681"], [42625, 2], [42626, 1, "\uA683"], [42627, 2], [42628, 1, "\uA685"], [42629, 2], [42630, 1, "\uA687"], [42631, 2], [42632, 1, "\uA689"], [42633, 2], [42634, 1, "\uA68B"], [42635, 2], [42636, 1, "\uA68D"], [42637, 2], [42638, 1, "\uA68F"], [42639, 2], [42640, 1, "\uA691"], [42641, 2], [42642, 1, "\uA693"], [42643, 2], [42644, 1, "\uA695"], [42645, 2], [42646, 1, "\uA697"], [42647, 2], [42648, 1, "\uA699"], [42649, 2], [42650, 1, "\uA69B"], [42651, 2], [42652, 1, "\u044A"], [42653, 1, "\u044C"], [42654, 2], [42655, 2], [[42656, 42725], 2], [[42726, 42735], 2], [[42736, 42737], 2], [[42738, 42743], 2], [[42744, 42751], 3], [[42752, 42774], 2], [[42775, 42778], 2], [[42779, 42783], 2], [[42784, 42785], 2], [42786, 1, "\uA723"], [42787, 2], [42788, 1, "\uA725"], [42789, 2], [42790, 1, "\uA727"], [42791, 2], [42792, 1, "\uA729"], [42793, 2], [42794, 1, "\uA72B"], [42795, 2], [42796, 1, "\uA72D"], [42797, 2], [42798, 1, "\uA72F"], [[42799, 42801], 2], [42802, 1, "\uA733"], [42803, 2], [42804, 1, "\uA735"], [42805, 2], [42806, 1, "\uA737"], [42807, 2], [42808, 1, "\uA739"], [42809, 2], [42810, 1, "\uA73B"], [42811, 2], [42812, 1, "\uA73D"], [42813, 2], [42814, 1, "\uA73F"], [42815, 2], [42816, 1, "\uA741"], [42817, 2], [42818, 1, "\uA743"], [42819, 2], [42820, 1, "\uA745"], [42821, 2], [42822, 1, "\uA747"], [42823, 2], [42824, 1, "\uA749"], [42825, 2], [42826, 1, "\uA74B"], [42827, 2], [42828, 1, "\uA74D"], [42829, 2], [42830, 1, "\uA74F"], [42831, 2], [42832, 1, "\uA751"], [42833, 2], [42834, 1, "\uA753"], [42835, 2], [42836, 1, "\uA755"], [42837, 2], [42838, 1, "\uA757"], [42839, 2], [42840, 1, "\uA759"], [42841, 2], [42842, 1, "\uA75B"], [42843, 2], [42844, 1, "\uA75D"], [42845, 2], [42846, 1, "\uA75F"], [42847, 2], [42848, 1, "\uA761"], [42849, 2], [42850, 1, "\uA763"], [42851, 2], [42852, 1, "\uA765"], [42853, 2], [42854, 1, "\uA767"], [42855, 2], [42856, 1, "\uA769"], [42857, 2], [42858, 1, "\uA76B"], [42859, 2], [42860, 1, "\uA76D"], [42861, 2], [42862, 1, "\uA76F"], [42863, 2], [42864, 1, "\uA76F"], [[42865, 42872], 2], [42873, 1, "\uA77A"], [42874, 2], [42875, 1, "\uA77C"], [42876, 2], [42877, 1, "\u1D79"], [42878, 1, "\uA77F"], [42879, 2], [42880, 1, "\uA781"], [42881, 2], [42882, 1, "\uA783"], [42883, 2], [42884, 1, "\uA785"], [42885, 2], [42886, 1, "\uA787"], [[42887, 42888], 2], [[42889, 42890], 2], [42891, 1, "\uA78C"], [42892, 2], [42893, 1, "\u0265"], [42894, 2], [42895, 2], [42896, 1, "\uA791"], [42897, 2], [42898, 1, "\uA793"], [42899, 2], [[42900, 42901], 2], [42902, 1, "\uA797"], [42903, 2], [42904, 1, "\uA799"], [42905, 2], [42906, 1, "\uA79B"], [42907, 2], [42908, 1, "\uA79D"], [42909, 2], [42910, 1, "\uA79F"], [42911, 2], [42912, 1, "\uA7A1"], [42913, 2], [42914, 1, "\uA7A3"], [42915, 2], [42916, 1, "\uA7A5"], [42917, 2], [42918, 1, "\uA7A7"], [42919, 2], [42920, 1, "\uA7A9"], [42921, 2], [42922, 1, "\u0266"], [42923, 1, "\u025C"], [42924, 1, "\u0261"], [42925, 1, "\u026C"], [42926, 1, "\u026A"], [42927, 2], [42928, 1, "\u029E"], [42929, 1, "\u0287"], [42930, 1, "\u029D"], [42931, 1, "\uAB53"], [42932, 1, "\uA7B5"], [42933, 2], [42934, 1, "\uA7B7"], [42935, 2], [42936, 1, "\uA7B9"], [42937, 2], [42938, 1, "\uA7BB"], [42939, 2], [42940, 1, "\uA7BD"], [42941, 2], [42942, 1, "\uA7BF"], [42943, 2], [42944, 1, "\uA7C1"], [42945, 2], [42946, 1, "\uA7C3"], [42947, 2], [42948, 1, "\uA794"], [42949, 1, "\u0282"], [42950, 1, "\u1D8E"], [42951, 1, "\uA7C8"], [42952, 2], [42953, 1, "\uA7CA"], [42954, 2], [42955, 1, "\u0264"], [42956, 1, "\uA7CD"], [42957, 2], [[42958, 42959], 3], [42960, 1, "\uA7D1"], [42961, 2], [42962, 3], [42963, 2], [42964, 3], [42965, 2], [42966, 1, "\uA7D7"], [42967, 2], [42968, 1, "\uA7D9"], [42969, 2], [42970, 1, "\uA7DB"], [42971, 2], [42972, 1, "\u019B"], [[42973, 42993], 3], [42994, 1, "c"], [42995, 1, "f"], [42996, 1, "q"], [42997, 1, "\uA7F6"], [42998, 2], [42999, 2], [43e3, 1, "\u0127"], [43001, 1, "\u0153"], [43002, 2], [[43003, 43007], 2], [[43008, 43047], 2], [[43048, 43051], 2], [43052, 2], [[43053, 43055], 3], [[43056, 43065], 2], [[43066, 43071], 3], [[43072, 43123], 2], [[43124, 43127], 2], [[43128, 43135], 3], [[43136, 43204], 2], [43205, 2], [[43206, 43213], 3], [[43214, 43215], 2], [[43216, 43225], 2], [[43226, 43231], 3], [[43232, 43255], 2], [[43256, 43258], 2], [43259, 2], [43260, 2], [43261, 2], [[43262, 43263], 2], [[43264, 43309], 2], [[43310, 43311], 2], [[43312, 43347], 2], [[43348, 43358], 3], [43359, 2], [[43360, 43388], 2], [[43389, 43391], 3], [[43392, 43456], 2], [[43457, 43469], 2], [43470, 3], [[43471, 43481], 2], [[43482, 43485], 3], [[43486, 43487], 2], [[43488, 43518], 2], [43519, 3], [[43520, 43574], 2], [[43575, 43583], 3], [[43584, 43597], 2], [[43598, 43599], 3], [[43600, 43609], 2], [[43610, 43611], 3], [[43612, 43615], 2], [[43616, 43638], 2], [[43639, 43641], 2], [[43642, 43643], 2], [[43644, 43647], 2], [[43648, 43714], 2], [[43715, 43738], 3], [[43739, 43741], 2], [[43742, 43743], 2], [[43744, 43759], 2], [[43760, 43761], 2], [[43762, 43766], 2], [[43767, 43776], 3], [[43777, 43782], 2], [[43783, 43784], 3], [[43785, 43790], 2], [[43791, 43792], 3], [[43793, 43798], 2], [[43799, 43807], 3], [[43808, 43814], 2], [43815, 3], [[43816, 43822], 2], [43823, 3], [[43824, 43866], 2], [43867, 2], [43868, 1, "\uA727"], [43869, 1, "\uAB37"], [43870, 1, "\u026B"], [43871, 1, "\uAB52"], [[43872, 43875], 2], [[43876, 43877], 2], [[43878, 43879], 2], [43880, 2], [43881, 1, "\u028D"], [[43882, 43883], 2], [[43884, 43887], 3], [43888, 1, "\u13A0"], [43889, 1, "\u13A1"], [43890, 1, "\u13A2"], [43891, 1, "\u13A3"], [43892, 1, "\u13A4"], [43893, 1, "\u13A5"], [43894, 1, "\u13A6"], [43895, 1, "\u13A7"], [43896, 1, "\u13A8"], [43897, 1, "\u13A9"], [43898, 1, "\u13AA"], [43899, 1, "\u13AB"], [43900, 1, "\u13AC"], [43901, 1, "\u13AD"], [43902, 1, "\u13AE"], [43903, 1, "\u13AF"], [43904, 1, "\u13B0"], [43905, 1, "\u13B1"], [43906, 1, "\u13B2"], [43907, 1, "\u13B3"], [43908, 1, "\u13B4"], [43909, 1, "\u13B5"], [43910, 1, "\u13B6"], [43911, 1, "\u13B7"], [43912, 1, "\u13B8"], [43913, 1, "\u13B9"], [43914, 1, "\u13BA"], [43915, 1, "\u13BB"], [43916, 1, "\u13BC"], [43917, 1, "\u13BD"], [43918, 1, "\u13BE"], [43919, 1, "\u13BF"], [43920, 1, "\u13C0"], [43921, 1, "\u13C1"], [43922, 1, "\u13C2"], [43923, 1, "\u13C3"], [43924, 1, "\u13C4"], [43925, 1, "\u13C5"], [43926, 1, "\u13C6"], [43927, 1, "\u13C7"], [43928, 1, "\u13C8"], [43929, 1, "\u13C9"], [43930, 1, "\u13CA"], [43931, 1, "\u13CB"], [43932, 1, "\u13CC"], [43933, 1, "\u13CD"], [43934, 1, "\u13CE"], [43935, 1, "\u13CF"], [43936, 1, "\u13D0"], [43937, 1, "\u13D1"], [43938, 1, "\u13D2"], [43939, 1, "\u13D3"], [43940, 1, "\u13D4"], [43941, 1, "\u13D5"], [43942, 1, "\u13D6"], [43943, 1, "\u13D7"], [43944, 1, "\u13D8"], [43945, 1, "\u13D9"], [43946, 1, "\u13DA"], [43947, 1, "\u13DB"], [43948, 1, "\u13DC"], [43949, 1, "\u13DD"], [43950, 1, "\u13DE"], [43951, 1, "\u13DF"], [43952, 1, "\u13E0"], [43953, 1, "\u13E1"], [43954, 1, "\u13E2"], [43955, 1, "\u13E3"], [43956, 1, "\u13E4"], [43957, 1, "\u13E5"], [43958, 1, "\u13E6"], [43959, 1, "\u13E7"], [43960, 1, "\u13E8"], [43961, 1, "\u13E9"], [43962, 1, "\u13EA"], [43963, 1, "\u13EB"], [43964, 1, "\u13EC"], [43965, 1, "\u13ED"], [43966, 1, "\u13EE"], [43967, 1, "\u13EF"], [[43968, 44010], 2], [44011, 2], [[44012, 44013], 2], [[44014, 44015], 3], [[44016, 44025], 2], [[44026, 44031], 3], [[44032, 55203], 2], [[55204, 55215], 3], [[55216, 55238], 2], [[55239, 55242], 3], [[55243, 55291], 2], [[55292, 55295], 3], [[55296, 57343], 3], [[57344, 63743], 3], [63744, 1, "\u8C48"], [63745, 1, "\u66F4"], [63746, 1, "\u8ECA"], [63747, 1, "\u8CC8"], [63748, 1, "\u6ED1"], [63749, 1, "\u4E32"], [63750, 1, "\u53E5"], [[63751, 63752], 1, "\u9F9C"], [63753, 1, "\u5951"], [63754, 1, "\u91D1"], [63755, 1, "\u5587"], [63756, 1, "\u5948"], [63757, 1, "\u61F6"], [63758, 1, "\u7669"], [63759, 1, "\u7F85"], [63760, 1, "\u863F"], [63761, 1, "\u87BA"], [63762, 1, "\u88F8"], [63763, 1, "\u908F"], [63764, 1, "\u6A02"], [63765, 1, "\u6D1B"], [63766, 1, "\u70D9"], [63767, 1, "\u73DE"], [63768, 1, "\u843D"], [63769, 1, "\u916A"], [63770, 1, "\u99F1"], [63771, 1, "\u4E82"], [63772, 1, "\u5375"], [63773, 1, "\u6B04"], [63774, 1, "\u721B"], [63775, 1, "\u862D"], [63776, 1, "\u9E1E"], [63777, 1, "\u5D50"], [63778, 1, "\u6FEB"], [63779, 1, "\u85CD"], [63780, 1, "\u8964"], [63781, 1, "\u62C9"], [63782, 1, "\u81D8"], [63783, 1, "\u881F"], [63784, 1, "\u5ECA"], [63785, 1, "\u6717"], [63786, 1, "\u6D6A"], [63787, 1, "\u72FC"], [63788, 1, "\u90CE"], [63789, 1, "\u4F86"], [63790, 1, "\u51B7"], [63791, 1, "\u52DE"], [63792, 1, "\u64C4"], [63793, 1, "\u6AD3"], [63794, 1, "\u7210"], [63795, 1, "\u76E7"], [63796, 1, "\u8001"], [63797, 1, "\u8606"], [63798, 1, "\u865C"], [63799, 1, "\u8DEF"], [63800, 1, "\u9732"], [63801, 1, "\u9B6F"], [63802, 1, "\u9DFA"], [63803, 1, "\u788C"], [63804, 1, "\u797F"], [63805, 1, "\u7DA0"], [63806, 1, "\u83C9"], [63807, 1, "\u9304"], [63808, 1, "\u9E7F"], [63809, 1, "\u8AD6"], [63810, 1, "\u58DF"], [63811, 1, "\u5F04"], [63812, 1, "\u7C60"], [63813, 1, "\u807E"], [63814, 1, "\u7262"], [63815, 1, "\u78CA"], [63816, 1, "\u8CC2"], [63817, 1, "\u96F7"], [63818, 1, "\u58D8"], [63819, 1, "\u5C62"], [63820, 1, "\u6A13"], [63821, 1, "\u6DDA"], [63822, 1, "\u6F0F"], [63823, 1, "\u7D2F"], [63824, 1, "\u7E37"], [63825, 1, "\u964B"], [63826, 1, "\u52D2"], [63827, 1, "\u808B"], [63828, 1, "\u51DC"], [63829, 1, "\u51CC"], [63830, 1, "\u7A1C"], [63831, 1, "\u7DBE"], [63832, 1, "\u83F1"], [63833, 1, "\u9675"], [63834, 1, "\u8B80"], [63835, 1, "\u62CF"], [63836, 1, "\u6A02"], [63837, 1, "\u8AFE"], [63838, 1, "\u4E39"], [63839, 1, "\u5BE7"], [63840, 1, "\u6012"], [63841, 1, "\u7387"], [63842, 1, "\u7570"], [63843, 1, "\u5317"], [63844, 1, "\u78FB"], [63845, 1, "\u4FBF"], [63846, 1, "\u5FA9"], [63847, 1, "\u4E0D"], [63848, 1, "\u6CCC"], [63849, 1, "\u6578"], [63850, 1, "\u7D22"], [63851, 1, "\u53C3"], [63852, 1, "\u585E"], [63853, 1, "\u7701"], [63854, 1, "\u8449"], [63855, 1, "\u8AAA"], [63856, 1, "\u6BBA"], [63857, 1, "\u8FB0"], [63858, 1, "\u6C88"], [63859, 1, "\u62FE"], [63860, 1, "\u82E5"], [63861, 1, "\u63A0"], [63862, 1, "\u7565"], [63863, 1, "\u4EAE"], [63864, 1, "\u5169"], [63865, 1, "\u51C9"], [63866, 1, "\u6881"], [63867, 1, "\u7CE7"], [63868, 1, "\u826F"], [63869, 1, "\u8AD2"], [63870, 1, "\u91CF"], [63871, 1, "\u52F5"], [63872, 1, "\u5442"], [63873, 1, "\u5973"], [63874, 1, "\u5EEC"], [63875, 1, "\u65C5"], [63876, 1, "\u6FFE"], [63877, 1, "\u792A"], [63878, 1, "\u95AD"], [63879, 1, "\u9A6A"], [63880, 1, "\u9E97"], [63881, 1, "\u9ECE"], [63882, 1, "\u529B"], [63883, 1, "\u66C6"], [63884, 1, "\u6B77"], [63885, 1, "\u8F62"], [63886, 1, "\u5E74"], [63887, 1, "\u6190"], [63888, 1, "\u6200"], [63889, 1, "\u649A"], [63890, 1, "\u6F23"], [63891, 1, "\u7149"], [63892, 1, "\u7489"], [63893, 1, "\u79CA"], [63894, 1, "\u7DF4"], [63895, 1, "\u806F"], [63896, 1, "\u8F26"], [63897, 1, "\u84EE"], [63898, 1, "\u9023"], [63899, 1, "\u934A"], [63900, 1, "\u5217"], [63901, 1, "\u52A3"], [63902, 1, "\u54BD"], [63903, 1, "\u70C8"], [63904, 1, "\u88C2"], [63905, 1, "\u8AAA"], [63906, 1, "\u5EC9"], [63907, 1, "\u5FF5"], [63908, 1, "\u637B"], [63909, 1, "\u6BAE"], [63910, 1, "\u7C3E"], [63911, 1, "\u7375"], [63912, 1, "\u4EE4"], [63913, 1, "\u56F9"], [63914, 1, "\u5BE7"], [63915, 1, "\u5DBA"], [63916, 1, "\u601C"], [63917, 1, "\u73B2"], [63918, 1, "\u7469"], [63919, 1, "\u7F9A"], [63920, 1, "\u8046"], [63921, 1, "\u9234"], [63922, 1, "\u96F6"], [63923, 1, "\u9748"], [63924, 1, "\u9818"], [63925, 1, "\u4F8B"], [63926, 1, "\u79AE"], [63927, 1, "\u91B4"], [63928, 1, "\u96B8"], [63929, 1, "\u60E1"], [63930, 1, "\u4E86"], [63931, 1, "\u50DA"], [63932, 1, "\u5BEE"], [63933, 1, "\u5C3F"], [63934, 1, "\u6599"], [63935, 1, "\u6A02"], [63936, 1, "\u71CE"], [63937, 1, "\u7642"], [63938, 1, "\u84FC"], [63939, 1, "\u907C"], [63940, 1, "\u9F8D"], [63941, 1, "\u6688"], [63942, 1, "\u962E"], [63943, 1, "\u5289"], [63944, 1, "\u677B"], [63945, 1, "\u67F3"], [63946, 1, "\u6D41"], [63947, 1, "\u6E9C"], [63948, 1, "\u7409"], [63949, 1, "\u7559"], [63950, 1, "\u786B"], [63951, 1, "\u7D10"], [63952, 1, "\u985E"], [63953, 1, "\u516D"], [63954, 1, "\u622E"], [63955, 1, "\u9678"], [63956, 1, "\u502B"], [63957, 1, "\u5D19"], [63958, 1, "\u6DEA"], [63959, 1, "\u8F2A"], [63960, 1, "\u5F8B"], [63961, 1, "\u6144"], [63962, 1, "\u6817"], [63963, 1, "\u7387"], [63964, 1, "\u9686"], [63965, 1, "\u5229"], [63966, 1, "\u540F"], [63967, 1, "\u5C65"], [63968, 1, "\u6613"], [63969, 1, "\u674E"], [63970, 1, "\u68A8"], [63971, 1, "\u6CE5"], [63972, 1, "\u7406"], [63973, 1, "\u75E2"], [63974, 1, "\u7F79"], [63975, 1, "\u88CF"], [63976, 1, "\u88E1"], [63977, 1, "\u91CC"], [63978, 1, "\u96E2"], [63979, 1, "\u533F"], [63980, 1, "\u6EBA"], [63981, 1, "\u541D"], [63982, 1, "\u71D0"], [63983, 1, "\u7498"], [63984, 1, "\u85FA"], [63985, 1, "\u96A3"], [63986, 1, "\u9C57"], [63987, 1, "\u9E9F"], [63988, 1, "\u6797"], [63989, 1, "\u6DCB"], [63990, 1, "\u81E8"], [63991, 1, "\u7ACB"], [63992, 1, "\u7B20"], [63993, 1, "\u7C92"], [63994, 1, "\u72C0"], [63995, 1, "\u7099"], [63996, 1, "\u8B58"], [63997, 1, "\u4EC0"], [63998, 1, "\u8336"], [63999, 1, "\u523A"], [64e3, 1, "\u5207"], [64001, 1, "\u5EA6"], [64002, 1, "\u62D3"], [64003, 1, "\u7CD6"], [64004, 1, "\u5B85"], [64005, 1, "\u6D1E"], [64006, 1, "\u66B4"], [64007, 1, "\u8F3B"], [64008, 1, "\u884C"], [64009, 1, "\u964D"], [64010, 1, "\u898B"], [64011, 1, "\u5ED3"], [64012, 1, "\u5140"], [64013, 1, "\u55C0"], [[64014, 64015], 2], [64016, 1, "\u585A"], [64017, 2], [64018, 1, "\u6674"], [[64019, 64020], 2], [64021, 1, "\u51DE"], [64022, 1, "\u732A"], [64023, 1, "\u76CA"], [64024, 1, "\u793C"], [64025, 1, "\u795E"], [64026, 1, "\u7965"], [64027, 1, "\u798F"], [64028, 1, "\u9756"], [64029, 1, "\u7CBE"], [64030, 1, "\u7FBD"], [64031, 2], [64032, 1, "\u8612"], [64033, 2], [64034, 1, "\u8AF8"], [[64035, 64036], 2], [64037, 1, "\u9038"], [64038, 1, "\u90FD"], [[64039, 64041], 2], [64042, 1, "\u98EF"], [64043, 1, "\u98FC"], [64044, 1, "\u9928"], [64045, 1, "\u9DB4"], [64046, 1, "\u90DE"], [64047, 1, "\u96B7"], [64048, 1, "\u4FAE"], [64049, 1, "\u50E7"], [64050, 1, "\u514D"], [64051, 1, "\u52C9"], [64052, 1, "\u52E4"], [64053, 1, "\u5351"], [64054, 1, "\u559D"], [64055, 1, "\u5606"], [64056, 1, "\u5668"], [64057, 1, "\u5840"], [64058, 1, "\u58A8"], [64059, 1, "\u5C64"], [64060, 1, "\u5C6E"], [64061, 1, "\u6094"], [64062, 1, "\u6168"], [64063, 1, "\u618E"], [64064, 1, "\u61F2"], [64065, 1, "\u654F"], [64066, 1, "\u65E2"], [64067, 1, "\u6691"], [64068, 1, "\u6885"], [64069, 1, "\u6D77"], [64070, 1, "\u6E1A"], [64071, 1, "\u6F22"], [64072, 1, "\u716E"], [64073, 1, "\u722B"], [64074, 1, "\u7422"], [64075, 1, "\u7891"], [64076, 1, "\u793E"], [64077, 1, "\u7949"], [64078, 1, "\u7948"], [64079, 1, "\u7950"], [64080, 1, "\u7956"], [64081, 1, "\u795D"], [64082, 1, "\u798D"], [64083, 1, "\u798E"], [64084, 1, "\u7A40"], [64085, 1, "\u7A81"], [64086, 1, "\u7BC0"], [64087, 1, "\u7DF4"], [64088, 1, "\u7E09"], [64089, 1, "\u7E41"], [64090, 1, "\u7F72"], [64091, 1, "\u8005"], [64092, 1, "\u81ED"], [[64093, 64094], 1, "\u8279"], [64095, 1, "\u8457"], [64096, 1, "\u8910"], [64097, 1, "\u8996"], [64098, 1, "\u8B01"], [64099, 1, "\u8B39"], [64100, 1, "\u8CD3"], [64101, 1, "\u8D08"], [64102, 1, "\u8FB6"], [64103, 1, "\u9038"], [64104, 1, "\u96E3"], [64105, 1, "\u97FF"], [64106, 1, "\u983B"], [64107, 1, "\u6075"], [64108, 1, "\u{242EE}"], [64109, 1, "\u8218"], [[64110, 64111], 3], [64112, 1, "\u4E26"], [64113, 1, "\u51B5"], [64114, 1, "\u5168"], [64115, 1, "\u4F80"], [64116, 1, "\u5145"], [64117, 1, "\u5180"], [64118, 1, "\u52C7"], [64119, 1, "\u52FA"], [64120, 1, "\u559D"], [64121, 1, "\u5555"], [64122, 1, "\u5599"], [64123, 1, "\u55E2"], [64124, 1, "\u585A"], [64125, 1, "\u58B3"], [64126, 1, "\u5944"], [64127, 1, "\u5954"], [64128, 1, "\u5A62"], [64129, 1, "\u5B28"], [64130, 1, "\u5ED2"], [64131, 1, "\u5ED9"], [64132, 1, "\u5F69"], [64133, 1, "\u5FAD"], [64134, 1, "\u60D8"], [64135, 1, "\u614E"], [64136, 1, "\u6108"], [64137, 1, "\u618E"], [64138, 1, "\u6160"], [64139, 1, "\u61F2"], [64140, 1, "\u6234"], [64141, 1, "\u63C4"], [64142, 1, "\u641C"], [64143, 1, "\u6452"], [64144, 1, "\u6556"], [64145, 1, "\u6674"], [64146, 1, "\u6717"], [64147, 1, "\u671B"], [64148, 1, "\u6756"], [64149, 1, "\u6B79"], [64150, 1, "\u6BBA"], [64151, 1, "\u6D41"], [64152, 1, "\u6EDB"], [64153, 1, "\u6ECB"], [64154, 1, "\u6F22"], [64155, 1, "\u701E"], [64156, 1, "\u716E"], [64157, 1, "\u77A7"], [64158, 1, "\u7235"], [64159, 1, "\u72AF"], [64160, 1, "\u732A"], [64161, 1, "\u7471"], [64162, 1, "\u7506"], [64163, 1, "\u753B"], [64164, 1, "\u761D"], [64165, 1, "\u761F"], [64166, 1, "\u76CA"], [64167, 1, "\u76DB"], [64168, 1, "\u76F4"], [64169, 1, "\u774A"], [64170, 1, "\u7740"], [64171, 1, "\u78CC"], [64172, 1, "\u7AB1"], [64173, 1, "\u7BC0"], [64174, 1, "\u7C7B"], [64175, 1, "\u7D5B"], [64176, 1, "\u7DF4"], [64177, 1, "\u7F3E"], [64178, 1, "\u8005"], [64179, 1, "\u8352"], [64180, 1, "\u83EF"], [64181, 1, "\u8779"], [64182, 1, "\u8941"], [64183, 1, "\u8986"], [64184, 1, "\u8996"], [64185, 1, "\u8ABF"], [64186, 1, "\u8AF8"], [64187, 1, "\u8ACB"], [64188, 1, "\u8B01"], [64189, 1, "\u8AFE"], [64190, 1, "\u8AED"], [64191, 1, "\u8B39"], [64192, 1, "\u8B8A"], [64193, 1, "\u8D08"], [64194, 1, "\u8F38"], [64195, 1, "\u9072"], [64196, 1, "\u9199"], [64197, 1, "\u9276"], [64198, 1, "\u967C"], [64199, 1, "\u96E3"], [64200, 1, "\u9756"], [64201, 1, "\u97DB"], [64202, 1, "\u97FF"], [64203, 1, "\u980B"], [64204, 1, "\u983B"], [64205, 1, "\u9B12"], [64206, 1, "\u9F9C"], [64207, 1, "\u{2284A}"], [64208, 1, "\u{22844}"], [64209, 1, "\u{233D5}"], [64210, 1, "\u3B9D"], [64211, 1, "\u4018"], [64212, 1, "\u4039"], [64213, 1, "\u{25249}"], [64214, 1, "\u{25CD0}"], [64215, 1, "\u{27ED3}"], [64216, 1, "\u9F43"], [64217, 1, "\u9F8E"], [[64218, 64255], 3], [64256, 1, "ff"], [64257, 1, "fi"], [64258, 1, "fl"], [64259, 1, "ffi"], [64260, 1, "ffl"], [[64261, 64262], 1, "st"], [[64263, 64274], 3], [64275, 1, "\u0574\u0576"], [64276, 1, "\u0574\u0565"], [64277, 1, "\u0574\u056B"], [64278, 1, "\u057E\u0576"], [64279, 1, "\u0574\u056D"], [[64280, 64284], 3], [64285, 1, "\u05D9\u05B4"], [64286, 2], [64287, 1, "\u05F2\u05B7"], [64288, 1, "\u05E2"], [64289, 1, "\u05D0"], [64290, 1, "\u05D3"], [64291, 1, "\u05D4"], [64292, 1, "\u05DB"], [64293, 1, "\u05DC"], [64294, 1, "\u05DD"], [64295, 1, "\u05E8"], [64296, 1, "\u05EA"], [64297, 1, "+"], [64298, 1, "\u05E9\u05C1"], [64299, 1, "\u05E9\u05C2"], [64300, 1, "\u05E9\u05BC\u05C1"], [64301, 1, "\u05E9\u05BC\u05C2"], [64302, 1, "\u05D0\u05B7"], [64303, 1, "\u05D0\u05B8"], [64304, 1, "\u05D0\u05BC"], [64305, 1, "\u05D1\u05BC"], [64306, 1, "\u05D2\u05BC"], [64307, 1, "\u05D3\u05BC"], [64308, 1, "\u05D4\u05BC"], [64309, 1, "\u05D5\u05BC"], [64310, 1, "\u05D6\u05BC"], [64311, 3], [64312, 1, "\u05D8\u05BC"], [64313, 1, "\u05D9\u05BC"], [64314, 1, "\u05DA\u05BC"], [64315, 1, "\u05DB\u05BC"], [64316, 1, "\u05DC\u05BC"], [64317, 3], [64318, 1, "\u05DE\u05BC"], [64319, 3], [64320, 1, "\u05E0\u05BC"], [64321, 1, "\u05E1\u05BC"], [64322, 3], [64323, 1, "\u05E3\u05BC"], [64324, 1, "\u05E4\u05BC"], [64325, 3], [64326, 1, "\u05E6\u05BC"], [64327, 1, "\u05E7\u05BC"], [64328, 1, "\u05E8\u05BC"], [64329, 1, "\u05E9\u05BC"], [64330, 1, "\u05EA\u05BC"], [64331, 1, "\u05D5\u05B9"], [64332, 1, "\u05D1\u05BF"], [64333, 1, "\u05DB\u05BF"], [64334, 1, "\u05E4\u05BF"], [64335, 1, "\u05D0\u05DC"], [[64336, 64337], 1, "\u0671"], [[64338, 64341], 1, "\u067B"], [[64342, 64345], 1, "\u067E"], [[64346, 64349], 1, "\u0680"], [[64350, 64353], 1, "\u067A"], [[64354, 64357], 1, "\u067F"], [[64358, 64361], 1, "\u0679"], [[64362, 64365], 1, "\u06A4"], [[64366, 64369], 1, "\u06A6"], [[64370, 64373], 1, "\u0684"], [[64374, 64377], 1, "\u0683"], [[64378, 64381], 1, "\u0686"], [[64382, 64385], 1, "\u0687"], [[64386, 64387], 1, "\u068D"], [[64388, 64389], 1, "\u068C"], [[64390, 64391], 1, "\u068E"], [[64392, 64393], 1, "\u0688"], [[64394, 64395], 1, "\u0698"], [[64396, 64397], 1, "\u0691"], [[64398, 64401], 1, "\u06A9"], [[64402, 64405], 1, "\u06AF"], [[64406, 64409], 1, "\u06B3"], [[64410, 64413], 1, "\u06B1"], [[64414, 64415], 1, "\u06BA"], [[64416, 64419], 1, "\u06BB"], [[64420, 64421], 1, "\u06C0"], [[64422, 64425], 1, "\u06C1"], [[64426, 64429], 1, "\u06BE"], [[64430, 64431], 1, "\u06D2"], [[64432, 64433], 1, "\u06D3"], [[64434, 64449], 2], [64450, 2], [[64451, 64466], 3], [[64467, 64470], 1, "\u06AD"], [[64471, 64472], 1, "\u06C7"], [[64473, 64474], 1, "\u06C6"], [[64475, 64476], 1, "\u06C8"], [64477, 1, "\u06C7\u0674"], [[64478, 64479], 1, "\u06CB"], [[64480, 64481], 1, "\u06C5"], [[64482, 64483], 1, "\u06C9"], [[64484, 64487], 1, "\u06D0"], [[64488, 64489], 1, "\u0649"], [[64490, 64491], 1, "\u0626\u0627"], [[64492, 64493], 1, "\u0626\u06D5"], [[64494, 64495], 1, "\u0626\u0648"], [[64496, 64497], 1, "\u0626\u06C7"], [[64498, 64499], 1, "\u0626\u06C6"], [[64500, 64501], 1, "\u0626\u06C8"], [[64502, 64504], 1, "\u0626\u06D0"], [[64505, 64507], 1, "\u0626\u0649"], [[64508, 64511], 1, "\u06CC"], [64512, 1, "\u0626\u062C"], [64513, 1, "\u0626\u062D"], [64514, 1, "\u0626\u0645"], [64515, 1, "\u0626\u0649"], [64516, 1, "\u0626\u064A"], [64517, 1, "\u0628\u062C"], [64518, 1, "\u0628\u062D"], [64519, 1, "\u0628\u062E"], [64520, 1, "\u0628\u0645"], [64521, 1, "\u0628\u0649"], [64522, 1, "\u0628\u064A"], [64523, 1, "\u062A\u062C"], [64524, 1, "\u062A\u062D"], [64525, 1, "\u062A\u062E"], [64526, 1, "\u062A\u0645"], [64527, 1, "\u062A\u0649"], [64528, 1, "\u062A\u064A"], [64529, 1, "\u062B\u062C"], [64530, 1, "\u062B\u0645"], [64531, 1, "\u062B\u0649"], [64532, 1, "\u062B\u064A"], [64533, 1, "\u062C\u062D"], [64534, 1, "\u062C\u0645"], [64535, 1, "\u062D\u062C"], [64536, 1, "\u062D\u0645"], [64537, 1, "\u062E\u062C"], [64538, 1, "\u062E\u062D"], [64539, 1, "\u062E\u0645"], [64540, 1, "\u0633\u062C"], [64541, 1, "\u0633\u062D"], [64542, 1, "\u0633\u062E"], [64543, 1, "\u0633\u0645"], [64544, 1, "\u0635\u062D"], [64545, 1, "\u0635\u0645"], [64546, 1, "\u0636\u062C"], [64547, 1, "\u0636\u062D"], [64548, 1, "\u0636\u062E"], [64549, 1, "\u0636\u0645"], [64550, 1, "\u0637\u062D"], [64551, 1, "\u0637\u0645"], [64552, 1, "\u0638\u0645"], [64553, 1, "\u0639\u062C"], [64554, 1, "\u0639\u0645"], [64555, 1, "\u063A\u062C"], [64556, 1, "\u063A\u0645"], [64557, 1, "\u0641\u062C"], [64558, 1, "\u0641\u062D"], [64559, 1, "\u0641\u062E"], [64560, 1, "\u0641\u0645"], [64561, 1, "\u0641\u0649"], [64562, 1, "\u0641\u064A"], [64563, 1, "\u0642\u062D"], [64564, 1, "\u0642\u0645"], [64565, 1, "\u0642\u0649"], [64566, 1, "\u0642\u064A"], [64567, 1, "\u0643\u0627"], [64568, 1, "\u0643\u062C"], [64569, 1, "\u0643\u062D"], [64570, 1, "\u0643\u062E"], [64571, 1, "\u0643\u0644"], [64572, 1, "\u0643\u0645"], [64573, 1, "\u0643\u0649"], [64574, 1, "\u0643\u064A"], [64575, 1, "\u0644\u062C"], [64576, 1, "\u0644\u062D"], [64577, 1, "\u0644\u062E"], [64578, 1, "\u0644\u0645"], [64579, 1, "\u0644\u0649"], [64580, 1, "\u0644\u064A"], [64581, 1, "\u0645\u062C"], [64582, 1, "\u0645\u062D"], [64583, 1, "\u0645\u062E"], [64584, 1, "\u0645\u0645"], [64585, 1, "\u0645\u0649"], [64586, 1, "\u0645\u064A"], [64587, 1, "\u0646\u062C"], [64588, 1, "\u0646\u062D"], [64589, 1, "\u0646\u062E"], [64590, 1, "\u0646\u0645"], [64591, 1, "\u0646\u0649"], [64592, 1, "\u0646\u064A"], [64593, 1, "\u0647\u062C"], [64594, 1, "\u0647\u0645"], [64595, 1, "\u0647\u0649"], [64596, 1, "\u0647\u064A"], [64597, 1, "\u064A\u062C"], [64598, 1, "\u064A\u062D"], [64599, 1, "\u064A\u062E"], [64600, 1, "\u064A\u0645"], [64601, 1, "\u064A\u0649"], [64602, 1, "\u064A\u064A"], [64603, 1, "\u0630\u0670"], [64604, 1, "\u0631\u0670"], [64605, 1, "\u0649\u0670"], [64606, 1, " \u064C\u0651"], [64607, 1, " \u064D\u0651"], [64608, 1, " \u064E\u0651"], [64609, 1, " \u064F\u0651"], [64610, 1, " \u0650\u0651"], [64611, 1, " \u0651\u0670"], [64612, 1, "\u0626\u0631"], [64613, 1, "\u0626\u0632"], [64614, 1, "\u0626\u0645"], [64615, 1, "\u0626\u0646"], [64616, 1, "\u0626\u0649"], [64617, 1, "\u0626\u064A"], [64618, 1, "\u0628\u0631"], [64619, 1, "\u0628\u0632"], [64620, 1, "\u0628\u0645"], [64621, 1, "\u0628\u0646"], [64622, 1, "\u0628\u0649"], [64623, 1, "\u0628\u064A"], [64624, 1, "\u062A\u0631"], [64625, 1, "\u062A\u0632"], [64626, 1, "\u062A\u0645"], [64627, 1, "\u062A\u0646"], [64628, 1, "\u062A\u0649"], [64629, 1, "\u062A\u064A"], [64630, 1, "\u062B\u0631"], [64631, 1, "\u062B\u0632"], [64632, 1, "\u062B\u0645"], [64633, 1, "\u062B\u0646"], [64634, 1, "\u062B\u0649"], [64635, 1, "\u062B\u064A"], [64636, 1, "\u0641\u0649"], [64637, 1, "\u0641\u064A"], [64638, 1, "\u0642\u0649"], [64639, 1, "\u0642\u064A"], [64640, 1, "\u0643\u0627"], [64641, 1, "\u0643\u0644"], [64642, 1, "\u0643\u0645"], [64643, 1, "\u0643\u0649"], [64644, 1, "\u0643\u064A"], [64645, 1, "\u0644\u0645"], [64646, 1, "\u0644\u0649"], [64647, 1, "\u0644\u064A"], [64648, 1, "\u0645\u0627"], [64649, 1, "\u0645\u0645"], [64650, 1, "\u0646\u0631"], [64651, 1, "\u0646\u0632"], [64652, 1, "\u0646\u0645"], [64653, 1, "\u0646\u0646"], [64654, 1, "\u0646\u0649"], [64655, 1, "\u0646\u064A"], [64656, 1, "\u0649\u0670"], [64657, 1, "\u064A\u0631"], [64658, 1, "\u064A\u0632"], [64659, 1, "\u064A\u0645"], [64660, 1, "\u064A\u0646"], [64661, 1, "\u064A\u0649"], [64662, 1, "\u064A\u064A"], [64663, 1, "\u0626\u062C"], [64664, 1, "\u0626\u062D"], [64665, 1, "\u0626\u062E"], [64666, 1, "\u0626\u0645"], [64667, 1, "\u0626\u0647"], [64668, 1, "\u0628\u062C"], [64669, 1, "\u0628\u062D"], [64670, 1, "\u0628\u062E"], [64671, 1, "\u0628\u0645"], [64672, 1, "\u0628\u0647"], [64673, 1, "\u062A\u062C"], [64674, 1, "\u062A\u062D"], [64675, 1, "\u062A\u062E"], [64676, 1, "\u062A\u0645"], [64677, 1, "\u062A\u0647"], [64678, 1, "\u062B\u0645"], [64679, 1, "\u062C\u062D"], [64680, 1, "\u062C\u0645"], [64681, 1, "\u062D\u062C"], [64682, 1, "\u062D\u0645"], [64683, 1, "\u062E\u062C"], [64684, 1, "\u062E\u0645"], [64685, 1, "\u0633\u062C"], [64686, 1, "\u0633\u062D"], [64687, 1, "\u0633\u062E"], [64688, 1, "\u0633\u0645"], [64689, 1, "\u0635\u062D"], [64690, 1, "\u0635\u062E"], [64691, 1, "\u0635\u0645"], [64692, 1, "\u0636\u062C"], [64693, 1, "\u0636\u062D"], [64694, 1, "\u0636\u062E"], [64695, 1, "\u0636\u0645"], [64696, 1, "\u0637\u062D"], [64697, 1, "\u0638\u0645"], [64698, 1, "\u0639\u062C"], [64699, 1, "\u0639\u0645"], [64700, 1, "\u063A\u062C"], [64701, 1, "\u063A\u0645"], [64702, 1, "\u0641\u062C"], [64703, 1, "\u0641\u062D"], [64704, 1, "\u0641\u062E"], [64705, 1, "\u0641\u0645"], [64706, 1, "\u0642\u062D"], [64707, 1, "\u0642\u0645"], [64708, 1, "\u0643\u062C"], [64709, 1, "\u0643\u062D"], [64710, 1, "\u0643\u062E"], [64711, 1, "\u0643\u0644"], [64712, 1, "\u0643\u0645"], [64713, 1, "\u0644\u062C"], [64714, 1, "\u0644\u062D"], [64715, 1, "\u0644\u062E"], [64716, 1, "\u0644\u0645"], [64717, 1, "\u0644\u0647"], [64718, 1, "\u0645\u062C"], [64719, 1, "\u0645\u062D"], [64720, 1, "\u0645\u062E"], [64721, 1, "\u0645\u0645"], [64722, 1, "\u0646\u062C"], [64723, 1, "\u0646\u062D"], [64724, 1, "\u0646\u062E"], [64725, 1, "\u0646\u0645"], [64726, 1, "\u0646\u0647"], [64727, 1, "\u0647\u062C"], [64728, 1, "\u0647\u0645"], [64729, 1, "\u0647\u0670"], [64730, 1, "\u064A\u062C"], [64731, 1, "\u064A\u062D"], [64732, 1, "\u064A\u062E"], [64733, 1, "\u064A\u0645"], [64734, 1, "\u064A\u0647"], [64735, 1, "\u0626\u0645"], [64736, 1, "\u0626\u0647"], [64737, 1, "\u0628\u0645"], [64738, 1, "\u0628\u0647"], [64739, 1, "\u062A\u0645"], [64740, 1, "\u062A\u0647"], [64741, 1, "\u062B\u0645"], [64742, 1, "\u062B\u0647"], [64743, 1, "\u0633\u0645"], [64744, 1, "\u0633\u0647"], [64745, 1, "\u0634\u0645"], [64746, 1, "\u0634\u0647"], [64747, 1, "\u0643\u0644"], [64748, 1, "\u0643\u0645"], [64749, 1, "\u0644\u0645"], [64750, 1, "\u0646\u0645"], [64751, 1, "\u0646\u0647"], [64752, 1, "\u064A\u0645"], [64753, 1, "\u064A\u0647"], [64754, 1, "\u0640\u064E\u0651"], [64755, 1, "\u0640\u064F\u0651"], [64756, 1, "\u0640\u0650\u0651"], [64757, 1, "\u0637\u0649"], [64758, 1, "\u0637\u064A"], [64759, 1, "\u0639\u0649"], [64760, 1, "\u0639\u064A"], [64761, 1, "\u063A\u0649"], [64762, 1, "\u063A\u064A"], [64763, 1, "\u0633\u0649"], [64764, 1, "\u0633\u064A"], [64765, 1, "\u0634\u0649"], [64766, 1, "\u0634\u064A"], [64767, 1, "\u062D\u0649"], [64768, 1, "\u062D\u064A"], [64769, 1, "\u062C\u0649"], [64770, 1, "\u062C\u064A"], [64771, 1, "\u062E\u0649"], [64772, 1, "\u062E\u064A"], [64773, 1, "\u0635\u0649"], [64774, 1, "\u0635\u064A"], [64775, 1, "\u0636\u0649"], [64776, 1, "\u0636\u064A"], [64777, 1, "\u0634\u062C"], [64778, 1, "\u0634\u062D"], [64779, 1, "\u0634\u062E"], [64780, 1, "\u0634\u0645"], [64781, 1, "\u0634\u0631"], [64782, 1, "\u0633\u0631"], [64783, 1, "\u0635\u0631"], [64784, 1, "\u0636\u0631"], [64785, 1, "\u0637\u0649"], [64786, 1, "\u0637\u064A"], [64787, 1, "\u0639\u0649"], [64788, 1, "\u0639\u064A"], [64789, 1, "\u063A\u0649"], [64790, 1, "\u063A\u064A"], [64791, 1, "\u0633\u0649"], [64792, 1, "\u0633\u064A"], [64793, 1, "\u0634\u0649"], [64794, 1, "\u0634\u064A"], [64795, 1, "\u062D\u0649"], [64796, 1, "\u062D\u064A"], [64797, 1, "\u062C\u0649"], [64798, 1, "\u062C\u064A"], [64799, 1, "\u062E\u0649"], [64800, 1, "\u062E\u064A"], [64801, 1, "\u0635\u0649"], [64802, 1, "\u0635\u064A"], [64803, 1, "\u0636\u0649"], [64804, 1, "\u0636\u064A"], [64805, 1, "\u0634\u062C"], [64806, 1, "\u0634\u062D"], [64807, 1, "\u0634\u062E"], [64808, 1, "\u0634\u0645"], [64809, 1, "\u0634\u0631"], [64810, 1, "\u0633\u0631"], [64811, 1, "\u0635\u0631"], [64812, 1, "\u0636\u0631"], [64813, 1, "\u0634\u062C"], [64814, 1, "\u0634\u062D"], [64815, 1, "\u0634\u062E"], [64816, 1, "\u0634\u0645"], [64817, 1, "\u0633\u0647"], [64818, 1, "\u0634\u0647"], [64819, 1, "\u0637\u0645"], [64820, 1, "\u0633\u062C"], [64821, 1, "\u0633\u062D"], [64822, 1, "\u0633\u062E"], [64823, 1, "\u0634\u062C"], [64824, 1, "\u0634\u062D"], [64825, 1, "\u0634\u062E"], [64826, 1, "\u0637\u0645"], [64827, 1, "\u0638\u0645"], [[64828, 64829], 1, "\u0627\u064B"], [[64830, 64831], 2], [[64832, 64847], 2], [64848, 1, "\u062A\u062C\u0645"], [[64849, 64850], 1, "\u062A\u062D\u062C"], [64851, 1, "\u062A\u062D\u0645"], [64852, 1, "\u062A\u062E\u0645"], [64853, 1, "\u062A\u0645\u062C"], [64854, 1, "\u062A\u0645\u062D"], [64855, 1, "\u062A\u0645\u062E"], [[64856, 64857], 1, "\u062C\u0645\u062D"], [64858, 1, "\u062D\u0645\u064A"], [64859, 1, "\u062D\u0645\u0649"], [64860, 1, "\u0633\u062D\u062C"], [64861, 1, "\u0633\u062C\u062D"], [64862, 1, "\u0633\u062C\u0649"], [[64863, 64864], 1, "\u0633\u0645\u062D"], [64865, 1, "\u0633\u0645\u062C"], [[64866, 64867], 1, "\u0633\u0645\u0645"], [[64868, 64869], 1, "\u0635\u062D\u062D"], [64870, 1, "\u0635\u0645\u0645"], [[64871, 64872], 1, "\u0634\u062D\u0645"], [64873, 1, "\u0634\u062C\u064A"], [[64874, 64875], 1, "\u0634\u0645\u062E"], [[64876, 64877], 1, "\u0634\u0645\u0645"], [64878, 1, "\u0636\u062D\u0649"], [[64879, 64880], 1, "\u0636\u062E\u0645"], [[64881, 64882], 1, "\u0637\u0645\u062D"], [64883, 1, "\u0637\u0645\u0645"], [64884, 1, "\u0637\u0645\u064A"], [64885, 1, "\u0639\u062C\u0645"], [[64886, 64887], 1, "\u0639\u0645\u0645"], [64888, 1, "\u0639\u0645\u0649"], [64889, 1, "\u063A\u0645\u0645"], [64890, 1, "\u063A\u0645\u064A"], [64891, 1, "\u063A\u0645\u0649"], [[64892, 64893], 1, "\u0641\u062E\u0645"], [64894, 1, "\u0642\u0645\u062D"], [64895, 1, "\u0642\u0645\u0645"], [64896, 1, "\u0644\u062D\u0645"], [64897, 1, "\u0644\u062D\u064A"], [64898, 1, "\u0644\u062D\u0649"], [[64899, 64900], 1, "\u0644\u062C\u062C"], [[64901, 64902], 1, "\u0644\u062E\u0645"], [[64903, 64904], 1, "\u0644\u0645\u062D"], [64905, 1, "\u0645\u062D\u062C"], [64906, 1, "\u0645\u062D\u0645"], [64907, 1, "\u0645\u062D\u064A"], [64908, 1, "\u0645\u062C\u062D"], [64909, 1, "\u0645\u062C\u0645"], [64910, 1, "\u0645\u062E\u062C"], [64911, 1, "\u0645\u062E\u0645"], [[64912, 64913], 3], [64914, 1, "\u0645\u062C\u062E"], [64915, 1, "\u0647\u0645\u062C"], [64916, 1, "\u0647\u0645\u0645"], [64917, 1, "\u0646\u062D\u0645"], [64918, 1, "\u0646\u062D\u0649"], [[64919, 64920], 1, "\u0646\u062C\u0645"], [64921, 1, "\u0646\u062C\u0649"], [64922, 1, "\u0646\u0645\u064A"], [64923, 1, "\u0646\u0645\u0649"], [[64924, 64925], 1, "\u064A\u0645\u0645"], [64926, 1, "\u0628\u062E\u064A"], [64927, 1, "\u062A\u062C\u064A"], [64928, 1, "\u062A\u062C\u0649"], [64929, 1, "\u062A\u062E\u064A"], [64930, 1, "\u062A\u062E\u0649"], [64931, 1, "\u062A\u0645\u064A"], [64932, 1, "\u062A\u0645\u0649"], [64933, 1, "\u062C\u0645\u064A"], [64934, 1, "\u062C\u062D\u0649"], [64935, 1, "\u062C\u0645\u0649"], [64936, 1, "\u0633\u062E\u0649"], [64937, 1, "\u0635\u062D\u064A"], [64938, 1, "\u0634\u062D\u064A"], [64939, 1, "\u0636\u062D\u064A"], [64940, 1, "\u0644\u062C\u064A"], [64941, 1, "\u0644\u0645\u064A"], [64942, 1, "\u064A\u062D\u064A"], [64943, 1, "\u064A\u062C\u064A"], [64944, 1, "\u064A\u0645\u064A"], [64945, 1, "\u0645\u0645\u064A"], [64946, 1, "\u0642\u0645\u064A"], [64947, 1, "\u0646\u062D\u064A"], [64948, 1, "\u0642\u0645\u062D"], [64949, 1, "\u0644\u062D\u0645"], [64950, 1, "\u0639\u0645\u064A"], [64951, 1, "\u0643\u0645\u064A"], [64952, 1, "\u0646\u062C\u062D"], [64953, 1, "\u0645\u062E\u064A"], [64954, 1, "\u0644\u062C\u0645"], [64955, 1, "\u0643\u0645\u0645"], [64956, 1, "\u0644\u062C\u0645"], [64957, 1, "\u0646\u062C\u062D"], [64958, 1, "\u062C\u062D\u064A"], [64959, 1, "\u062D\u062C\u064A"], [64960, 1, "\u0645\u062C\u064A"], [64961, 1, "\u0641\u0645\u064A"], [64962, 1, "\u0628\u062D\u064A"], [64963, 1, "\u0643\u0645\u0645"], [64964, 1, "\u0639\u062C\u0645"], [64965, 1, "\u0635\u0645\u0645"], [64966, 1, "\u0633\u062E\u064A"], [64967, 1, "\u0646\u062C\u064A"], [[64968, 64974], 3], [64975, 2], [[64976, 65007], 3], [65008, 1, "\u0635\u0644\u06D2"], [65009, 1, "\u0642\u0644\u06D2"], [65010, 1, "\u0627\u0644\u0644\u0647"], [65011, 1, "\u0627\u0643\u0628\u0631"], [65012, 1, "\u0645\u062D\u0645\u062F"], [65013, 1, "\u0635\u0644\u0639\u0645"], [65014, 1, "\u0631\u0633\u0648\u0644"], [65015, 1, "\u0639\u0644\u064A\u0647"], [65016, 1, "\u0648\u0633\u0644\u0645"], [65017, 1, "\u0635\u0644\u0649"], [65018, 1, "\u0635\u0644\u0649 \u0627\u0644\u0644\u0647 \u0639\u0644\u064A\u0647 \u0648\u0633\u0644\u0645"], [65019, 1, "\u062C\u0644 \u062C\u0644\u0627\u0644\u0647"], [65020, 1, "\u0631\u06CC\u0627\u0644"], [65021, 2], [[65022, 65023], 2], [[65024, 65039], 7], [65040, 1, ","], [65041, 1, "\u3001"], [65042, 3], [65043, 1, ":"], [65044, 1, ";"], [65045, 1, "!"], [65046, 1, "?"], [65047, 1, "\u3016"], [65048, 1, "\u3017"], [65049, 3], [[65050, 65055], 3], [[65056, 65059], 2], [[65060, 65062], 2], [[65063, 65069], 2], [[65070, 65071], 2], [65072, 3], [65073, 1, "\u2014"], [65074, 1, "\u2013"], [[65075, 65076], 1, "_"], [65077, 1, "("], [65078, 1, ")"], [65079, 1, "{"], [65080, 1, "}"], [65081, 1, "\u3014"], [65082, 1, "\u3015"], [65083, 1, "\u3010"], [65084, 1, "\u3011"], [65085, 1, "\u300A"], [65086, 1, "\u300B"], [65087, 1, "\u3008"], [65088, 1, "\u3009"], [65089, 1, "\u300C"], [65090, 1, "\u300D"], [65091, 1, "\u300E"], [65092, 1, "\u300F"], [[65093, 65094], 2], [65095, 1, "["], [65096, 1, "]"], [[65097, 65100], 1, " \u0305"], [[65101, 65103], 1, "_"], [65104, 1, ","], [65105, 1, "\u3001"], [65106, 3], [65107, 3], [65108, 1, ";"], [65109, 1, ":"], [65110, 1, "?"], [65111, 1, "!"], [65112, 1, "\u2014"], [65113, 1, "("], [65114, 1, ")"], [65115, 1, "{"], [65116, 1, "}"], [65117, 1, "\u3014"], [65118, 1, "\u3015"], [65119, 1, "#"], [65120, 1, "&"], [65121, 1, "*"], [65122, 1, "+"], [65123, 1, "-"], [65124, 1, "<"], [65125, 1, ">"], [65126, 1, "="], [65127, 3], [65128, 1, "\\"], [65129, 1, "$"], [65130, 1, "%"], [65131, 1, "@"], [[65132, 65135], 3], [65136, 1, " \u064B"], [65137, 1, "\u0640\u064B"], [65138, 1, " \u064C"], [65139, 2], [65140, 1, " \u064D"], [65141, 3], [65142, 1, " \u064E"], [65143, 1, "\u0640\u064E"], [65144, 1, " \u064F"], [65145, 1, "\u0640\u064F"], [65146, 1, " \u0650"], [65147, 1, "\u0640\u0650"], [65148, 1, " \u0651"], [65149, 1, "\u0640\u0651"], [65150, 1, " \u0652"], [65151, 1, "\u0640\u0652"], [65152, 1, "\u0621"], [[65153, 65154], 1, "\u0622"], [[65155, 65156], 1, "\u0623"], [[65157, 65158], 1, "\u0624"], [[65159, 65160], 1, "\u0625"], [[65161, 65164], 1, "\u0626"], [[65165, 65166], 1, "\u0627"], [[65167, 65170], 1, "\u0628"], [[65171, 65172], 1, "\u0629"], [[65173, 65176], 1, "\u062A"], [[65177, 65180], 1, "\u062B"], [[65181, 65184], 1, "\u062C"], [[65185, 65188], 1, "\u062D"], [[65189, 65192], 1, "\u062E"], [[65193, 65194], 1, "\u062F"], [[65195, 65196], 1, "\u0630"], [[65197, 65198], 1, "\u0631"], [[65199, 65200], 1, "\u0632"], [[65201, 65204], 1, "\u0633"], [[65205, 65208], 1, "\u0634"], [[65209, 65212], 1, "\u0635"], [[65213, 65216], 1, "\u0636"], [[65217, 65220], 1, "\u0637"], [[65221, 65224], 1, "\u0638"], [[65225, 65228], 1, "\u0639"], [[65229, 65232], 1, "\u063A"], [[65233, 65236], 1, "\u0641"], [[65237, 65240], 1, "\u0642"], [[65241, 65244], 1, "\u0643"], [[65245, 65248], 1, "\u0644"], [[65249, 65252], 1, "\u0645"], [[65253, 65256], 1, "\u0646"], [[65257, 65260], 1, "\u0647"], [[65261, 65262], 1, "\u0648"], [[65263, 65264], 1, "\u0649"], [[65265, 65268], 1, "\u064A"], [[65269, 65270], 1, "\u0644\u0622"], [[65271, 65272], 1, "\u0644\u0623"], [[65273, 65274], 1, "\u0644\u0625"], [[65275, 65276], 1, "\u0644\u0627"], [[65277, 65278], 3], [65279, 7], [65280, 3], [65281, 1, "!"], [65282, 1, '"'], [65283, 1, "#"], [65284, 1, "$"], [65285, 1, "%"], [65286, 1, "&"], [65287, 1, "'"], [65288, 1, "("], [65289, 1, ")"], [65290, 1, "*"], [65291, 1, "+"], [65292, 1, ","], [65293, 1, "-"], [65294, 1, "."], [65295, 1, "/"], [65296, 1, "0"], [65297, 1, "1"], [65298, 1, "2"], [65299, 1, "3"], [65300, 1, "4"], [65301, 1, "5"], [65302, 1, "6"], [65303, 1, "7"], [65304, 1, "8"], [65305, 1, "9"], [65306, 1, ":"], [65307, 1, ";"], [65308, 1, "<"], [65309, 1, "="], [65310, 1, ">"], [65311, 1, "?"], [65312, 1, "@"], [65313, 1, "a"], [65314, 1, "b"], [65315, 1, "c"], [65316, 1, "d"], [65317, 1, "e"], [65318, 1, "f"], [65319, 1, "g"], [65320, 1, "h"], [65321, 1, "i"], [65322, 1, "j"], [65323, 1, "k"], [65324, 1, "l"], [65325, 1, "m"], [65326, 1, "n"], [65327, 1, "o"], [65328, 1, "p"], [65329, 1, "q"], [65330, 1, "r"], [65331, 1, "s"], [65332, 1, "t"], [65333, 1, "u"], [65334, 1, "v"], [65335, 1, "w"], [65336, 1, "x"], [65337, 1, "y"], [65338, 1, "z"], [65339, 1, "["], [65340, 1, "\\"], [65341, 1, "]"], [65342, 1, "^"], [65343, 1, "_"], [65344, 1, "`"], [65345, 1, "a"], [65346, 1, "b"], [65347, 1, "c"], [65348, 1, "d"], [65349, 1, "e"], [65350, 1, "f"], [65351, 1, "g"], [65352, 1, "h"], [65353, 1, "i"], [65354, 1, "j"], [65355, 1, "k"], [65356, 1, "l"], [65357, 1, "m"], [65358, 1, "n"], [65359, 1, "o"], [65360, 1, "p"], [65361, 1, "q"], [65362, 1, "r"], [65363, 1, "s"], [65364, 1, "t"], [65365, 1, "u"], [65366, 1, "v"], [65367, 1, "w"], [65368, 1, "x"], [65369, 1, "y"], [65370, 1, "z"], [65371, 1, "{"], [65372, 1, "|"], [65373, 1, "}"], [65374, 1, "~"], [65375, 1, "\u2985"], [65376, 1, "\u2986"], [65377, 1, "."], [65378, 1, "\u300C"], [65379, 1, "\u300D"], [65380, 1, "\u3001"], [65381, 1, "\u30FB"], [65382, 1, "\u30F2"], [65383, 1, "\u30A1"], [65384, 1, "\u30A3"], [65385, 1, "\u30A5"], [65386, 1, "\u30A7"], [65387, 1, "\u30A9"], [65388, 1, "\u30E3"], [65389, 1, "\u30E5"], [65390, 1, "\u30E7"], [65391, 1, "\u30C3"], [65392, 1, "\u30FC"], [65393, 1, "\u30A2"], [65394, 1, "\u30A4"], [65395, 1, "\u30A6"], [65396, 1, "\u30A8"], [65397, 1, "\u30AA"], [65398, 1, "\u30AB"], [65399, 1, "\u30AD"], [65400, 1, "\u30AF"], [65401, 1, "\u30B1"], [65402, 1, "\u30B3"], [65403, 1, "\u30B5"], [65404, 1, "\u30B7"], [65405, 1, "\u30B9"], [65406, 1, "\u30BB"], [65407, 1, "\u30BD"], [65408, 1, "\u30BF"], [65409, 1, "\u30C1"], [65410, 1, "\u30C4"], [65411, 1, "\u30C6"], [65412, 1, "\u30C8"], [65413, 1, "\u30CA"], [65414, 1, "\u30CB"], [65415, 1, "\u30CC"], [65416, 1, "\u30CD"], [65417, 1, "\u30CE"], [65418, 1, "\u30CF"], [65419, 1, "\u30D2"], [65420, 1, "\u30D5"], [65421, 1, "\u30D8"], [65422, 1, "\u30DB"], [65423, 1, "\u30DE"], [65424, 1, "\u30DF"], [65425, 1, "\u30E0"], [65426, 1, "\u30E1"], [65427, 1, "\u30E2"], [65428, 1, "\u30E4"], [65429, 1, "\u30E6"], [65430, 1, "\u30E8"], [65431, 1, "\u30E9"], [65432, 1, "\u30EA"], [65433, 1, "\u30EB"], [65434, 1, "\u30EC"], [65435, 1, "\u30ED"], [65436, 1, "\u30EF"], [65437, 1, "\u30F3"], [65438, 1, "\u3099"], [65439, 1, "\u309A"], [65440, 7], [65441, 1, "\u1100"], [65442, 1, "\u1101"], [65443, 1, "\u11AA"], [65444, 1, "\u1102"], [65445, 1, "\u11AC"], [65446, 1, "\u11AD"], [65447, 1, "\u1103"], [65448, 1, "\u1104"], [65449, 1, "\u1105"], [65450, 1, "\u11B0"], [65451, 1, "\u11B1"], [65452, 1, "\u11B2"], [65453, 1, "\u11B3"], [65454, 1, "\u11B4"], [65455, 1, "\u11B5"], [65456, 1, "\u111A"], [65457, 1, "\u1106"], [65458, 1, "\u1107"], [65459, 1, "\u1108"], [65460, 1, "\u1121"], [65461, 1, "\u1109"], [65462, 1, "\u110A"], [65463, 1, "\u110B"], [65464, 1, "\u110C"], [65465, 1, "\u110D"], [65466, 1, "\u110E"], [65467, 1, "\u110F"], [65468, 1, "\u1110"], [65469, 1, "\u1111"], [65470, 1, "\u1112"], [[65471, 65473], 3], [65474, 1, "\u1161"], [65475, 1, "\u1162"], [65476, 1, "\u1163"], [65477, 1, "\u1164"], [65478, 1, "\u1165"], [65479, 1, "\u1166"], [[65480, 65481], 3], [65482, 1, "\u1167"], [65483, 1, "\u1168"], [65484, 1, "\u1169"], [65485, 1, "\u116A"], [65486, 1, "\u116B"], [65487, 1, "\u116C"], [[65488, 65489], 3], [65490, 1, "\u116D"], [65491, 1, "\u116E"], [65492, 1, "\u116F"], [65493, 1, "\u1170"], [65494, 1, "\u1171"], [65495, 1, "\u1172"], [[65496, 65497], 3], [65498, 1, "\u1173"], [65499, 1, "\u1174"], [65500, 1, "\u1175"], [[65501, 65503], 3], [65504, 1, "\xA2"], [65505, 1, "\xA3"], [65506, 1, "\xAC"], [65507, 1, " \u0304"], [65508, 1, "\xA6"], [65509, 1, "\xA5"], [65510, 1, "\u20A9"], [65511, 3], [65512, 1, "\u2502"], [65513, 1, "\u2190"], [65514, 1, "\u2191"], [65515, 1, "\u2192"], [65516, 1, "\u2193"], [65517, 1, "\u25A0"], [65518, 1, "\u25CB"], [[65519, 65528], 3], [[65529, 65531], 3], [65532, 3], [65533, 3], [[65534, 65535], 3], [[65536, 65547], 2], [65548, 3], [[65549, 65574], 2], [65575, 3], [[65576, 65594], 2], [65595, 3], [[65596, 65597], 2], [65598, 3], [[65599, 65613], 2], [[65614, 65615], 3], [[65616, 65629], 2], [[65630, 65663], 3], [[65664, 65786], 2], [[65787, 65791], 3], [[65792, 65794], 2], [[65795, 65798], 3], [[65799, 65843], 2], [[65844, 65846], 3], [[65847, 65855], 2], [[65856, 65930], 2], [[65931, 65932], 2], [[65933, 65934], 2], [65935, 3], [[65936, 65947], 2], [65948, 2], [[65949, 65951], 3], [65952, 2], [[65953, 65999], 3], [[66e3, 66044], 2], [66045, 2], [[66046, 66175], 3], [[66176, 66204], 2], [[66205, 66207], 3], [[66208, 66256], 2], [[66257, 66271], 3], [66272, 2], [[66273, 66299], 2], [[66300, 66303], 3], [[66304, 66334], 2], [66335, 2], [[66336, 66339], 2], [[66340, 66348], 3], [[66349, 66351], 2], [[66352, 66368], 2], [66369, 2], [[66370, 66377], 2], [66378, 2], [[66379, 66383], 3], [[66384, 66426], 2], [[66427, 66431], 3], [[66432, 66461], 2], [66462, 3], [66463, 2], [[66464, 66499], 2], [[66500, 66503], 3], [[66504, 66511], 2], [[66512, 66517], 2], [[66518, 66559], 3], [66560, 1, "\u{10428}"], [66561, 1, "\u{10429}"], [66562, 1, "\u{1042A}"], [66563, 1, "\u{1042B}"], [66564, 1, "\u{1042C}"], [66565, 1, "\u{1042D}"], [66566, 1, "\u{1042E}"], [66567, 1, "\u{1042F}"], [66568, 1, "\u{10430}"], [66569, 1, "\u{10431}"], [66570, 1, "\u{10432}"], [66571, 1, "\u{10433}"], [66572, 1, "\u{10434}"], [66573, 1, "\u{10435}"], [66574, 1, "\u{10436}"], [66575, 1, "\u{10437}"], [66576, 1, "\u{10438}"], [66577, 1, "\u{10439}"], [66578, 1, "\u{1043A}"], [66579, 1, "\u{1043B}"], [66580, 1, "\u{1043C}"], [66581, 1, "\u{1043D}"], [66582, 1, "\u{1043E}"], [66583, 1, "\u{1043F}"], [66584, 1, "\u{10440}"], [66585, 1, "\u{10441}"], [66586, 1, "\u{10442}"], [66587, 1, "\u{10443}"], [66588, 1, "\u{10444}"], [66589, 1, "\u{10445}"], [66590, 1, "\u{10446}"], [66591, 1, "\u{10447}"], [66592, 1, "\u{10448}"], [66593, 1, "\u{10449}"], [66594, 1, "\u{1044A}"], [66595, 1, "\u{1044B}"], [66596, 1, "\u{1044C}"], [66597, 1, "\u{1044D}"], [66598, 1, "\u{1044E}"], [66599, 1, "\u{1044F}"], [[66600, 66637], 2], [[66638, 66717], 2], [[66718, 66719], 3], [[66720, 66729], 2], [[66730, 66735], 3], [66736, 1, "\u{104D8}"], [66737, 1, "\u{104D9}"], [66738, 1, "\u{104DA}"], [66739, 1, "\u{104DB}"], [66740, 1, "\u{104DC}"], [66741, 1, "\u{104DD}"], [66742, 1, "\u{104DE}"], [66743, 1, "\u{104DF}"], [66744, 1, "\u{104E0}"], [66745, 1, "\u{104E1}"], [66746, 1, "\u{104E2}"], [66747, 1, "\u{104E3}"], [66748, 1, "\u{104E4}"], [66749, 1, "\u{104E5}"], [66750, 1, "\u{104E6}"], [66751, 1, "\u{104E7}"], [66752, 1, "\u{104E8}"], [66753, 1, "\u{104E9}"], [66754, 1, "\u{104EA}"], [66755, 1, "\u{104EB}"], [66756, 1, "\u{104EC}"], [66757, 1, "\u{104ED}"], [66758, 1, "\u{104EE}"], [66759, 1, "\u{104EF}"], [66760, 1, "\u{104F0}"], [66761, 1, "\u{104F1}"], [66762, 1, "\u{104F2}"], [66763, 1, "\u{104F3}"], [66764, 1, "\u{104F4}"], [66765, 1, "\u{104F5}"], [66766, 1, "\u{104F6}"], [66767, 1, "\u{104F7}"], [66768, 1, "\u{104F8}"], [66769, 1, "\u{104F9}"], [66770, 1, "\u{104FA}"], [66771, 1, "\u{104FB}"], [[66772, 66775], 3], [[66776, 66811], 2], [[66812, 66815], 3], [[66816, 66855], 2], [[66856, 66863], 3], [[66864, 66915], 2], [[66916, 66926], 3], [66927, 2], [66928, 1, "\u{10597}"], [66929, 1, "\u{10598}"], [66930, 1, "\u{10599}"], [66931, 1, "\u{1059A}"], [66932, 1, "\u{1059B}"], [66933, 1, "\u{1059C}"], [66934, 1, "\u{1059D}"], [66935, 1, "\u{1059E}"], [66936, 1, "\u{1059F}"], [66937, 1, "\u{105A0}"], [66938, 1, "\u{105A1}"], [66939, 3], [66940, 1, "\u{105A3}"], [66941, 1, "\u{105A4}"], [66942, 1, "\u{105A5}"], [66943, 1, "\u{105A6}"], [66944, 1, "\u{105A7}"], [66945, 1, "\u{105A8}"], [66946, 1, "\u{105A9}"], [66947, 1, "\u{105AA}"], [66948, 1, "\u{105AB}"], [66949, 1, "\u{105AC}"], [66950, 1, "\u{105AD}"], [66951, 1, "\u{105AE}"], [66952, 1, "\u{105AF}"], [66953, 1, "\u{105B0}"], [66954, 1, "\u{105B1}"], [66955, 3], [66956, 1, "\u{105B3}"], [66957, 1, "\u{105B4}"], [66958, 1, "\u{105B5}"], [66959, 1, "\u{105B6}"], [66960, 1, "\u{105B7}"], [66961, 1, "\u{105B8}"], [66962, 1, "\u{105B9}"], [66963, 3], [66964, 1, "\u{105BB}"], [66965, 1, "\u{105BC}"], [66966, 3], [[66967, 66977], 2], [66978, 3], [[66979, 66993], 2], [66994, 3], [[66995, 67001], 2], [67002, 3], [[67003, 67004], 2], [[67005, 67007], 3], [[67008, 67059], 2], [[67060, 67071], 3], [[67072, 67382], 2], [[67383, 67391], 3], [[67392, 67413], 2], [[67414, 67423], 3], [[67424, 67431], 2], [[67432, 67455], 3], [67456, 2], [67457, 1, "\u02D0"], [67458, 1, "\u02D1"], [67459, 1, "\xE6"], [67460, 1, "\u0299"], [67461, 1, "\u0253"], [67462, 3], [67463, 1, "\u02A3"], [67464, 1, "\uAB66"], [67465, 1, "\u02A5"], [67466, 1, "\u02A4"], [67467, 1, "\u0256"], [67468, 1, "\u0257"], [67469, 1, "\u1D91"], [67470, 1, "\u0258"], [67471, 1, "\u025E"], [67472, 1, "\u02A9"], [67473, 1, "\u0264"], [67474, 1, "\u0262"], [67475, 1, "\u0260"], [67476, 1, "\u029B"], [67477, 1, "\u0127"], [67478, 1, "\u029C"], [67479, 1, "\u0267"], [67480, 1, "\u0284"], [67481, 1, "\u02AA"], [67482, 1, "\u02AB"], [67483, 1, "\u026C"], [67484, 1, "\u{1DF04}"], [67485, 1, "\uA78E"], [67486, 1, "\u026E"], [67487, 1, "\u{1DF05}"], [67488, 1, "\u028E"], [67489, 1, "\u{1DF06}"], [67490, 1, "\xF8"], [67491, 1, "\u0276"], [67492, 1, "\u0277"], [67493, 1, "q"], [67494, 1, "\u027A"], [67495, 1, "\u{1DF08}"], [67496, 1, "\u027D"], [67497, 1, "\u027E"], [67498, 1, "\u0280"], [67499, 1, "\u02A8"], [67500, 1, "\u02A6"], [67501, 1, "\uAB67"], [67502, 1, "\u02A7"], [67503, 1, "\u0288"], [67504, 1, "\u2C71"], [67505, 3], [67506, 1, "\u028F"], [67507, 1, "\u02A1"], [67508, 1, "\u02A2"], [67509, 1, "\u0298"], [67510, 1, "\u01C0"], [67511, 1, "\u01C1"], [67512, 1, "\u01C2"], [67513, 1, "\u{1DF0A}"], [67514, 1, "\u{1DF1E}"], [[67515, 67583], 3], [[67584, 67589], 2], [[67590, 67591], 3], [67592, 2], [67593, 3], [[67594, 67637], 2], [67638, 3], [[67639, 67640], 2], [[67641, 67643], 3], [67644, 2], [[67645, 67646], 3], [67647, 2], [[67648, 67669], 2], [67670, 3], [[67671, 67679], 2], [[67680, 67702], 2], [[67703, 67711], 2], [[67712, 67742], 2], [[67743, 67750], 3], [[67751, 67759], 2], [[67760, 67807], 3], [[67808, 67826], 2], [67827, 3], [[67828, 67829], 2], [[67830, 67834], 3], [[67835, 67839], 2], [[67840, 67861], 2], [[67862, 67865], 2], [[67866, 67867], 2], [[67868, 67870], 3], [67871, 2], [[67872, 67897], 2], [[67898, 67902], 3], [67903, 2], [[67904, 67967], 3], [[67968, 68023], 2], [[68024, 68027], 3], [[68028, 68029], 2], [[68030, 68031], 2], [[68032, 68047], 2], [[68048, 68049], 3], [[68050, 68095], 2], [[68096, 68099], 2], [68100, 3], [[68101, 68102], 2], [[68103, 68107], 3], [[68108, 68115], 2], [68116, 3], [[68117, 68119], 2], [68120, 3], [[68121, 68147], 2], [[68148, 68149], 2], [[68150, 68151], 3], [[68152, 68154], 2], [[68155, 68158], 3], [68159, 2], [[68160, 68167], 2], [68168, 2], [[68169, 68175], 3], [[68176, 68184], 2], [[68185, 68191], 3], [[68192, 68220], 2], [[68221, 68223], 2], [[68224, 68252], 2], [[68253, 68255], 2], [[68256, 68287], 3], [[68288, 68295], 2], [68296, 2], [[68297, 68326], 2], [[68327, 68330], 3], [[68331, 68342], 2], [[68343, 68351], 3], [[68352, 68405], 2], [[68406, 68408], 3], [[68409, 68415], 2], [[68416, 68437], 2], [[68438, 68439], 3], [[68440, 68447], 2], [[68448, 68466], 2], [[68467, 68471], 3], [[68472, 68479], 2], [[68480, 68497], 2], [[68498, 68504], 3], [[68505, 68508], 2], [[68509, 68520], 3], [[68521, 68527], 2], [[68528, 68607], 3], [[68608, 68680], 2], [[68681, 68735], 3], [68736, 1, "\u{10CC0}"], [68737, 1, "\u{10CC1}"], [68738, 1, "\u{10CC2}"], [68739, 1, "\u{10CC3}"], [68740, 1, "\u{10CC4}"], [68741, 1, "\u{10CC5}"], [68742, 1, "\u{10CC6}"], [68743, 1, "\u{10CC7}"], [68744, 1, "\u{10CC8}"], [68745, 1, "\u{10CC9}"], [68746, 1, "\u{10CCA}"], [68747, 1, "\u{10CCB}"], [68748, 1, "\u{10CCC}"], [68749, 1, "\u{10CCD}"], [68750, 1, "\u{10CCE}"], [68751, 1, "\u{10CCF}"], [68752, 1, "\u{10CD0}"], [68753, 1, "\u{10CD1}"], [68754, 1, "\u{10CD2}"], [68755, 1, "\u{10CD3}"], [68756, 1, "\u{10CD4}"], [68757, 1, "\u{10CD5}"], [68758, 1, "\u{10CD6}"], [68759, 1, "\u{10CD7}"], [68760, 1, "\u{10CD8}"], [68761, 1, "\u{10CD9}"], [68762, 1, "\u{10CDA}"], [68763, 1, "\u{10CDB}"], [68764, 1, "\u{10CDC}"], [68765, 1, "\u{10CDD}"], [68766, 1, "\u{10CDE}"], [68767, 1, "\u{10CDF}"], [68768, 1, "\u{10CE0}"], [68769, 1, "\u{10CE1}"], [68770, 1, "\u{10CE2}"], [68771, 1, "\u{10CE3}"], [68772, 1, "\u{10CE4}"], [68773, 1, "\u{10CE5}"], [68774, 1, "\u{10CE6}"], [68775, 1, "\u{10CE7}"], [68776, 1, "\u{10CE8}"], [68777, 1, "\u{10CE9}"], [68778, 1, "\u{10CEA}"], [68779, 1, "\u{10CEB}"], [68780, 1, "\u{10CEC}"], [68781, 1, "\u{10CED}"], [68782, 1, "\u{10CEE}"], [68783, 1, "\u{10CEF}"], [68784, 1, "\u{10CF0}"], [68785, 1, "\u{10CF1}"], [68786, 1, "\u{10CF2}"], [[68787, 68799], 3], [[68800, 68850], 2], [[68851, 68857], 3], [[68858, 68863], 2], [[68864, 68903], 2], [[68904, 68911], 3], [[68912, 68921], 2], [[68922, 68927], 3], [[68928, 68943], 2], [68944, 1, "\u{10D70}"], [68945, 1, "\u{10D71}"], [68946, 1, "\u{10D72}"], [68947, 1, "\u{10D73}"], [68948, 1, "\u{10D74}"], [68949, 1, "\u{10D75}"], [68950, 1, "\u{10D76}"], [68951, 1, "\u{10D77}"], [68952, 1, "\u{10D78}"], [68953, 1, "\u{10D79}"], [68954, 1, "\u{10D7A}"], [68955, 1, "\u{10D7B}"], [68956, 1, "\u{10D7C}"], [68957, 1, "\u{10D7D}"], [68958, 1, "\u{10D7E}"], [68959, 1, "\u{10D7F}"], [68960, 1, "\u{10D80}"], [68961, 1, "\u{10D81}"], [68962, 1, "\u{10D82}"], [68963, 1, "\u{10D83}"], [68964, 1, "\u{10D84}"], [68965, 1, "\u{10D85}"], [[68966, 68968], 3], [[68969, 68973], 2], [68974, 2], [[68975, 68997], 2], [[68998, 69005], 3], [[69006, 69007], 2], [[69008, 69215], 3], [[69216, 69246], 2], [69247, 3], [[69248, 69289], 2], [69290, 3], [[69291, 69292], 2], [69293, 2], [[69294, 69295], 3], [[69296, 69297], 2], [[69298, 69313], 3], [[69314, 69316], 2], [[69317, 69371], 3], [69372, 2], [[69373, 69375], 2], [[69376, 69404], 2], [[69405, 69414], 2], [69415, 2], [[69416, 69423], 3], [[69424, 69456], 2], [[69457, 69465], 2], [[69466, 69487], 3], [[69488, 69509], 2], [[69510, 69513], 2], [[69514, 69551], 3], [[69552, 69572], 2], [[69573, 69579], 2], [[69580, 69599], 3], [[69600, 69622], 2], [[69623, 69631], 3], [[69632, 69702], 2], [[69703, 69709], 2], [[69710, 69713], 3], [[69714, 69733], 2], [[69734, 69743], 2], [[69744, 69749], 2], [[69750, 69758], 3], [69759, 2], [[69760, 69818], 2], [[69819, 69820], 2], [69821, 3], [[69822, 69825], 2], [69826, 2], [[69827, 69836], 3], [69837, 3], [[69838, 69839], 3], [[69840, 69864], 2], [[69865, 69871], 3], [[69872, 69881], 2], [[69882, 69887], 3], [[69888, 69940], 2], [69941, 3], [[69942, 69951], 2], [[69952, 69955], 2], [[69956, 69958], 2], [69959, 2], [[69960, 69967], 3], [[69968, 70003], 2], [[70004, 70005], 2], [70006, 2], [[70007, 70015], 3], [[70016, 70084], 2], [[70085, 70088], 2], [[70089, 70092], 2], [70093, 2], [[70094, 70095], 2], [[70096, 70105], 2], [70106, 2], [70107, 2], [70108, 2], [[70109, 70111], 2], [70112, 3], [[70113, 70132], 2], [[70133, 70143], 3], [[70144, 70161], 2], [70162, 3], [[70163, 70199], 2], [[70200, 70205], 2], [70206, 2], [[70207, 70209], 2], [[70210, 70271], 3], [[70272, 70278], 2], [70279, 3], [70280, 2], [70281, 3], [[70282, 70285], 2], [70286, 3], [[70287, 70301], 2], [70302, 3], [[70303, 70312], 2], [70313, 2], [[70314, 70319], 3], [[70320, 70378], 2], [[70379, 70383], 3], [[70384, 70393], 2], [[70394, 70399], 3], [70400, 2], [[70401, 70403], 2], [70404, 3], [[70405, 70412], 2], [[70413, 70414], 3], [[70415, 70416], 2], [[70417, 70418], 3], [[70419, 70440], 2], [70441, 3], [[70442, 70448], 2], [70449, 3], [[70450, 70451], 2], [70452, 3], [[70453, 70457], 2], [70458, 3], [70459, 2], [[70460, 70468], 2], [[70469, 70470], 3], [[70471, 70472], 2], [[70473, 70474], 3], [[70475, 70477], 2], [[70478, 70479], 3], [70480, 2], [[70481, 70486], 3], [70487, 2], [[70488, 70492], 3], [[70493, 70499], 2], [[70500, 70501], 3], [[70502, 70508], 2], [[70509, 70511], 3], [[70512, 70516], 2], [[70517, 70527], 3], [[70528, 70537], 2], [70538, 3], [70539, 2], [[70540, 70541], 3], [70542, 2], [70543, 3], [[70544, 70581], 2], [70582, 3], [[70583, 70592], 2], [70593, 3], [70594, 2], [[70595, 70596], 3], [70597, 2], [70598, 3], [[70599, 70602], 2], [70603, 3], [[70604, 70611], 2], [[70612, 70613], 2], [70614, 3], [[70615, 70616], 2], [[70617, 70624], 3], [[70625, 70626], 2], [[70627, 70655], 3], [[70656, 70730], 2], [[70731, 70735], 2], [[70736, 70745], 2], [70746, 2], [70747, 2], [70748, 3], [70749, 2], [70750, 2], [70751, 2], [[70752, 70753], 2], [[70754, 70783], 3], [[70784, 70853], 2], [70854, 2], [70855, 2], [[70856, 70863], 3], [[70864, 70873], 2], [[70874, 71039], 3], [[71040, 71093], 2], [[71094, 71095], 3], [[71096, 71104], 2], [[71105, 71113], 2], [[71114, 71127], 2], [[71128, 71133], 2], [[71134, 71167], 3], [[71168, 71232], 2], [[71233, 71235], 2], [71236, 2], [[71237, 71247], 3], [[71248, 71257], 2], [[71258, 71263], 3], [[71264, 71276], 2], [[71277, 71295], 3], [[71296, 71351], 2], [71352, 2], [71353, 2], [[71354, 71359], 3], [[71360, 71369], 2], [[71370, 71375], 3], [[71376, 71395], 2], [[71396, 71423], 3], [[71424, 71449], 2], [71450, 2], [[71451, 71452], 3], [[71453, 71467], 2], [[71468, 71471], 3], [[71472, 71481], 2], [[71482, 71487], 2], [[71488, 71494], 2], [[71495, 71679], 3], [[71680, 71738], 2], [71739, 2], [[71740, 71839], 3], [71840, 1, "\u{118C0}"], [71841, 1, "\u{118C1}"], [71842, 1, "\u{118C2}"], [71843, 1, "\u{118C3}"], [71844, 1, "\u{118C4}"], [71845, 1, "\u{118C5}"], [71846, 1, "\u{118C6}"], [71847, 1, "\u{118C7}"], [71848, 1, "\u{118C8}"], [71849, 1, "\u{118C9}"], [71850, 1, "\u{118CA}"], [71851, 1, "\u{118CB}"], [71852, 1, "\u{118CC}"], [71853, 1, "\u{118CD}"], [71854, 1, "\u{118CE}"], [71855, 1, "\u{118CF}"], [71856, 1, "\u{118D0}"], [71857, 1, "\u{118D1}"], [71858, 1, "\u{118D2}"], [71859, 1, "\u{118D3}"], [71860, 1, "\u{118D4}"], [71861, 1, "\u{118D5}"], [71862, 1, "\u{118D6}"], [71863, 1, "\u{118D7}"], [71864, 1, "\u{118D8}"], [71865, 1, "\u{118D9}"], [71866, 1, "\u{118DA}"], [71867, 1, "\u{118DB}"], [71868, 1, "\u{118DC}"], [71869, 1, "\u{118DD}"], [71870, 1, "\u{118DE}"], [71871, 1, "\u{118DF}"], [[71872, 71913], 2], [[71914, 71922], 2], [[71923, 71934], 3], [71935, 2], [[71936, 71942], 2], [[71943, 71944], 3], [71945, 2], [[71946, 71947], 3], [[71948, 71955], 2], [71956, 3], [[71957, 71958], 2], [71959, 3], [[71960, 71989], 2], [71990, 3], [[71991, 71992], 2], [[71993, 71994], 3], [[71995, 72003], 2], [[72004, 72006], 2], [[72007, 72015], 3], [[72016, 72025], 2], [[72026, 72095], 3], [[72096, 72103], 2], [[72104, 72105], 3], [[72106, 72151], 2], [[72152, 72153], 3], [[72154, 72161], 2], [72162, 2], [[72163, 72164], 2], [[72165, 72191], 3], [[72192, 72254], 2], [[72255, 72262], 2], [72263, 2], [[72264, 72271], 3], [[72272, 72323], 2], [[72324, 72325], 2], [[72326, 72345], 2], [[72346, 72348], 2], [72349, 2], [[72350, 72354], 2], [[72355, 72367], 3], [[72368, 72383], 2], [[72384, 72440], 2], [[72441, 72447], 3], [[72448, 72457], 2], [[72458, 72639], 3], [[72640, 72672], 2], [72673, 2], [[72674, 72687], 3], [[72688, 72697], 2], [[72698, 72703], 3], [[72704, 72712], 2], [72713, 3], [[72714, 72758], 2], [72759, 3], [[72760, 72768], 2], [[72769, 72773], 2], [[72774, 72783], 3], [[72784, 72793], 2], [[72794, 72812], 2], [[72813, 72815], 3], [[72816, 72817], 2], [[72818, 72847], 2], [[72848, 72849], 3], [[72850, 72871], 2], [72872, 3], [[72873, 72886], 2], [[72887, 72959], 3], [[72960, 72966], 2], [72967, 3], [[72968, 72969], 2], [72970, 3], [[72971, 73014], 2], [[73015, 73017], 3], [73018, 2], [73019, 3], [[73020, 73021], 2], [73022, 3], [[73023, 73031], 2], [[73032, 73039], 3], [[73040, 73049], 2], [[73050, 73055], 3], [[73056, 73061], 2], [73062, 3], [[73063, 73064], 2], [73065, 3], [[73066, 73102], 2], [73103, 3], [[73104, 73105], 2], [73106, 3], [[73107, 73112], 2], [[73113, 73119], 3], [[73120, 73129], 2], [[73130, 73439], 3], [[73440, 73462], 2], [[73463, 73464], 2], [[73465, 73471], 3], [[73472, 73488], 2], [73489, 3], [[73490, 73530], 2], [[73531, 73533], 3], [[73534, 73538], 2], [[73539, 73551], 2], [[73552, 73561], 2], [73562, 2], [[73563, 73647], 3], [73648, 2], [[73649, 73663], 3], [[73664, 73713], 2], [[73714, 73726], 3], [73727, 2], [[73728, 74606], 2], [[74607, 74648], 2], [74649, 2], [[74650, 74751], 3], [[74752, 74850], 2], [[74851, 74862], 2], [74863, 3], [[74864, 74867], 2], [74868, 2], [[74869, 74879], 3], [[74880, 75075], 2], [[75076, 77711], 3], [[77712, 77808], 2], [[77809, 77810], 2], [[77811, 77823], 3], [[77824, 78894], 2], [78895, 2], [[78896, 78904], 3], [[78905, 78911], 3], [[78912, 78933], 2], [[78934, 78943], 3], [[78944, 82938], 2], [[82939, 82943], 3], [[82944, 83526], 2], [[83527, 90367], 3], [[90368, 90425], 2], [[90426, 92159], 3], [[92160, 92728], 2], [[92729, 92735], 3], [[92736, 92766], 2], [92767, 3], [[92768, 92777], 2], [[92778, 92781], 3], [[92782, 92783], 2], [[92784, 92862], 2], [92863, 3], [[92864, 92873], 2], [[92874, 92879], 3], [[92880, 92909], 2], [[92910, 92911], 3], [[92912, 92916], 2], [92917, 2], [[92918, 92927], 3], [[92928, 92982], 2], [[92983, 92991], 2], [[92992, 92995], 2], [[92996, 92997], 2], [[92998, 93007], 3], [[93008, 93017], 2], [93018, 3], [[93019, 93025], 2], [93026, 3], [[93027, 93047], 2], [[93048, 93052], 3], [[93053, 93071], 2], [[93072, 93503], 3], [[93504, 93548], 2], [[93549, 93551], 2], [[93552, 93561], 2], [[93562, 93759], 3], [93760, 1, "\u{16E60}"], [93761, 1, "\u{16E61}"], [93762, 1, "\u{16E62}"], [93763, 1, "\u{16E63}"], [93764, 1, "\u{16E64}"], [93765, 1, "\u{16E65}"], [93766, 1, "\u{16E66}"], [93767, 1, "\u{16E67}"], [93768, 1, "\u{16E68}"], [93769, 1, "\u{16E69}"], [93770, 1, "\u{16E6A}"], [93771, 1, "\u{16E6B}"], [93772, 1, "\u{16E6C}"], [93773, 1, "\u{16E6D}"], [93774, 1, "\u{16E6E}"], [93775, 1, "\u{16E6F}"], [93776, 1, "\u{16E70}"], [93777, 1, "\u{16E71}"], [93778, 1, "\u{16E72}"], [93779, 1, "\u{16E73}"], [93780, 1, "\u{16E74}"], [93781, 1, "\u{16E75}"], [93782, 1, "\u{16E76}"], [93783, 1, "\u{16E77}"], [93784, 1, "\u{16E78}"], [93785, 1, "\u{16E79}"], [93786, 1, "\u{16E7A}"], [93787, 1, "\u{16E7B}"], [93788, 1, "\u{16E7C}"], [93789, 1, "\u{16E7D}"], [93790, 1, "\u{16E7E}"], [93791, 1, "\u{16E7F}"], [[93792, 93823], 2], [[93824, 93850], 2], [[93851, 93951], 3], [[93952, 94020], 2], [[94021, 94026], 2], [[94027, 94030], 3], [94031, 2], [[94032, 94078], 2], [[94079, 94087], 2], [[94088, 94094], 3], [[94095, 94111], 2], [[94112, 94175], 3], [94176, 2], [94177, 2], [94178, 2], [94179, 2], [94180, 2], [[94181, 94191], 3], [[94192, 94193], 2], [[94194, 94207], 3], [[94208, 100332], 2], [[100333, 100337], 2], [[100338, 100343], 2], [[100344, 100351], 3], [[100352, 101106], 2], [[101107, 101589], 2], [[101590, 101630], 3], [101631, 2], [[101632, 101640], 2], [[101641, 110575], 3], [[110576, 110579], 2], [110580, 3], [[110581, 110587], 2], [110588, 3], [[110589, 110590], 2], [110591, 3], [[110592, 110593], 2], [[110594, 110878], 2], [[110879, 110882], 2], [[110883, 110897], 3], [110898, 2], [[110899, 110927], 3], [[110928, 110930], 2], [[110931, 110932], 3], [110933, 2], [[110934, 110947], 3], [[110948, 110951], 2], [[110952, 110959], 3], [[110960, 111355], 2], [[111356, 113663], 3], [[113664, 113770], 2], [[113771, 113775], 3], [[113776, 113788], 2], [[113789, 113791], 3], [[113792, 113800], 2], [[113801, 113807], 3], [[113808, 113817], 2], [[113818, 113819], 3], [113820, 2], [[113821, 113822], 2], [113823, 2], [[113824, 113827], 7], [[113828, 117759], 3], [[117760, 117973], 2], [117974, 1, "a"], [117975, 1, "b"], [117976, 1, "c"], [117977, 1, "d"], [117978, 1, "e"], [117979, 1, "f"], [117980, 1, "g"], [117981, 1, "h"], [117982, 1, "i"], [117983, 1, "j"], [117984, 1, "k"], [117985, 1, "l"], [117986, 1, "m"], [117987, 1, "n"], [117988, 1, "o"], [117989, 1, "p"], [117990, 1, "q"], [117991, 1, "r"], [117992, 1, "s"], [117993, 1, "t"], [117994, 1, "u"], [117995, 1, "v"], [117996, 1, "w"], [117997, 1, "x"], [117998, 1, "y"], [117999, 1, "z"], [118e3, 1, "0"], [118001, 1, "1"], [118002, 1, "2"], [118003, 1, "3"], [118004, 1, "4"], [118005, 1, "5"], [118006, 1, "6"], [118007, 1, "7"], [118008, 1, "8"], [118009, 1, "9"], [[118010, 118015], 3], [[118016, 118451], 2], [[118452, 118527], 3], [[118528, 118573], 2], [[118574, 118575], 3], [[118576, 118598], 2], [[118599, 118607], 3], [[118608, 118723], 2], [[118724, 118783], 3], [[118784, 119029], 2], [[119030, 119039], 3], [[119040, 119078], 2], [[119079, 119080], 3], [119081, 2], [[119082, 119133], 2], [119134, 1, "\u{1D157}\u{1D165}"], [119135, 1, "\u{1D158}\u{1D165}"], [119136, 1, "\u{1D158}\u{1D165}\u{1D16E}"], [119137, 1, "\u{1D158}\u{1D165}\u{1D16F}"], [119138, 1, "\u{1D158}\u{1D165}\u{1D170}"], [119139, 1, "\u{1D158}\u{1D165}\u{1D171}"], [119140, 1, "\u{1D158}\u{1D165}\u{1D172}"], [[119141, 119154], 2], [[119155, 119162], 7], [[119163, 119226], 2], [119227, 1, "\u{1D1B9}\u{1D165}"], [119228, 1, "\u{1D1BA}\u{1D165}"], [119229, 1, "\u{1D1B9}\u{1D165}\u{1D16E}"], [119230, 1, "\u{1D1BA}\u{1D165}\u{1D16E}"], [119231, 1, "\u{1D1B9}\u{1D165}\u{1D16F}"], [119232, 1, "\u{1D1BA}\u{1D165}\u{1D16F}"], [[119233, 119261], 2], [[119262, 119272], 2], [[119273, 119274], 2], [[119275, 119295], 3], [[119296, 119365], 2], [[119366, 119487], 3], [[119488, 119507], 2], [[119508, 119519], 3], [[119520, 119539], 2], [[119540, 119551], 3], [[119552, 119638], 2], [[119639, 119647], 3], [[119648, 119665], 2], [[119666, 119672], 2], [[119673, 119807], 3], [119808, 1, "a"], [119809, 1, "b"], [119810, 1, "c"], [119811, 1, "d"], [119812, 1, "e"], [119813, 1, "f"], [119814, 1, "g"], [119815, 1, "h"], [119816, 1, "i"], [119817, 1, "j"], [119818, 1, "k"], [119819, 1, "l"], [119820, 1, "m"], [119821, 1, "n"], [119822, 1, "o"], [119823, 1, "p"], [119824, 1, "q"], [119825, 1, "r"], [119826, 1, "s"], [119827, 1, "t"], [119828, 1, "u"], [119829, 1, "v"], [119830, 1, "w"], [119831, 1, "x"], [119832, 1, "y"], [119833, 1, "z"], [119834, 1, "a"], [119835, 1, "b"], [119836, 1, "c"], [119837, 1, "d"], [119838, 1, "e"], [119839, 1, "f"], [119840, 1, "g"], [119841, 1, "h"], [119842, 1, "i"], [119843, 1, "j"], [119844, 1, "k"], [119845, 1, "l"], [119846, 1, "m"], [119847, 1, "n"], [119848, 1, "o"], [119849, 1, "p"], [119850, 1, "q"], [119851, 1, "r"], [119852, 1, "s"], [119853, 1, "t"], [119854, 1, "u"], [119855, 1, "v"], [119856, 1, "w"], [119857, 1, "x"], [119858, 1, "y"], [119859, 1, "z"], [119860, 1, "a"], [119861, 1, "b"], [119862, 1, "c"], [119863, 1, "d"], [119864, 1, "e"], [119865, 1, "f"], [119866, 1, "g"], [119867, 1, "h"], [119868, 1, "i"], [119869, 1, "j"], [119870, 1, "k"], [119871, 1, "l"], [119872, 1, "m"], [119873, 1, "n"], [119874, 1, "o"], [119875, 1, "p"], [119876, 1, "q"], [119877, 1, "r"], [119878, 1, "s"], [119879, 1, "t"], [119880, 1, "u"], [119881, 1, "v"], [119882, 1, "w"], [119883, 1, "x"], [119884, 1, "y"], [119885, 1, "z"], [119886, 1, "a"], [119887, 1, "b"], [119888, 1, "c"], [119889, 1, "d"], [119890, 1, "e"], [119891, 1, "f"], [119892, 1, "g"], [119893, 3], [119894, 1, "i"], [119895, 1, "j"], [119896, 1, "k"], [119897, 1, "l"], [119898, 1, "m"], [119899, 1, "n"], [119900, 1, "o"], [119901, 1, "p"], [119902, 1, "q"], [119903, 1, "r"], [119904, 1, "s"], [119905, 1, "t"], [119906, 1, "u"], [119907, 1, "v"], [119908, 1, "w"], [119909, 1, "x"], [119910, 1, "y"], [119911, 1, "z"], [119912, 1, "a"], [119913, 1, "b"], [119914, 1, "c"], [119915, 1, "d"], [119916, 1, "e"], [119917, 1, "f"], [119918, 1, "g"], [119919, 1, "h"], [119920, 1, "i"], [119921, 1, "j"], [119922, 1, "k"], [119923, 1, "l"], [119924, 1, "m"], [119925, 1, "n"], [119926, 1, "o"], [119927, 1, "p"], [119928, 1, "q"], [119929, 1, "r"], [119930, 1, "s"], [119931, 1, "t"], [119932, 1, "u"], [119933, 1, "v"], [119934, 1, "w"], [119935, 1, "x"], [119936, 1, "y"], [119937, 1, "z"], [119938, 1, "a"], [119939, 1, "b"], [119940, 1, "c"], [119941, 1, "d"], [119942, 1, "e"], [119943, 1, "f"], [119944, 1, "g"], [119945, 1, "h"], [119946, 1, "i"], [119947, 1, "j"], [119948, 1, "k"], [119949, 1, "l"], [119950, 1, "m"], [119951, 1, "n"], [119952, 1, "o"], [119953, 1, "p"], [119954, 1, "q"], [119955, 1, "r"], [119956, 1, "s"], [119957, 1, "t"], [119958, 1, "u"], [119959, 1, "v"], [119960, 1, "w"], [119961, 1, "x"], [119962, 1, "y"], [119963, 1, "z"], [119964, 1, "a"], [119965, 3], [119966, 1, "c"], [119967, 1, "d"], [[119968, 119969], 3], [119970, 1, "g"], [[119971, 119972], 3], [119973, 1, "j"], [119974, 1, "k"], [[119975, 119976], 3], [119977, 1, "n"], [119978, 1, "o"], [119979, 1, "p"], [119980, 1, "q"], [119981, 3], [119982, 1, "s"], [119983, 1, "t"], [119984, 1, "u"], [119985, 1, "v"], [119986, 1, "w"], [119987, 1, "x"], [119988, 1, "y"], [119989, 1, "z"], [119990, 1, "a"], [119991, 1, "b"], [119992, 1, "c"], [119993, 1, "d"], [119994, 3], [119995, 1, "f"], [119996, 3], [119997, 1, "h"], [119998, 1, "i"], [119999, 1, "j"], [12e4, 1, "k"], [120001, 1, "l"], [120002, 1, "m"], [120003, 1, "n"], [120004, 3], [120005, 1, "p"], [120006, 1, "q"], [120007, 1, "r"], [120008, 1, "s"], [120009, 1, "t"], [120010, 1, "u"], [120011, 1, "v"], [120012, 1, "w"], [120013, 1, "x"], [120014, 1, "y"], [120015, 1, "z"], [120016, 1, "a"], [120017, 1, "b"], [120018, 1, "c"], [120019, 1, "d"], [120020, 1, "e"], [120021, 1, "f"], [120022, 1, "g"], [120023, 1, "h"], [120024, 1, "i"], [120025, 1, "j"], [120026, 1, "k"], [120027, 1, "l"], [120028, 1, "m"], [120029, 1, "n"], [120030, 1, "o"], [120031, 1, "p"], [120032, 1, "q"], [120033, 1, "r"], [120034, 1, "s"], [120035, 1, "t"], [120036, 1, "u"], [120037, 1, "v"], [120038, 1, "w"], [120039, 1, "x"], [120040, 1, "y"], [120041, 1, "z"], [120042, 1, "a"], [120043, 1, "b"], [120044, 1, "c"], [120045, 1, "d"], [120046, 1, "e"], [120047, 1, "f"], [120048, 1, "g"], [120049, 1, "h"], [120050, 1, "i"], [120051, 1, "j"], [120052, 1, "k"], [120053, 1, "l"], [120054, 1, "m"], [120055, 1, "n"], [120056, 1, "o"], [120057, 1, "p"], [120058, 1, "q"], [120059, 1, "r"], [120060, 1, "s"], [120061, 1, "t"], [120062, 1, "u"], [120063, 1, "v"], [120064, 1, "w"], [120065, 1, "x"], [120066, 1, "y"], [120067, 1, "z"], [120068, 1, "a"], [120069, 1, "b"], [120070, 3], [120071, 1, "d"], [120072, 1, "e"], [120073, 1, "f"], [120074, 1, "g"], [[120075, 120076], 3], [120077, 1, "j"], [120078, 1, "k"], [120079, 1, "l"], [120080, 1, "m"], [120081, 1, "n"], [120082, 1, "o"], [120083, 1, "p"], [120084, 1, "q"], [120085, 3], [120086, 1, "s"], [120087, 1, "t"], [120088, 1, "u"], [120089, 1, "v"], [120090, 1, "w"], [120091, 1, "x"], [120092, 1, "y"], [120093, 3], [120094, 1, "a"], [120095, 1, "b"], [120096, 1, "c"], [120097, 1, "d"], [120098, 1, "e"], [120099, 1, "f"], [120100, 1, "g"], [120101, 1, "h"], [120102, 1, "i"], [120103, 1, "j"], [120104, 1, "k"], [120105, 1, "l"], [120106, 1, "m"], [120107, 1, "n"], [120108, 1, "o"], [120109, 1, "p"], [120110, 1, "q"], [120111, 1, "r"], [120112, 1, "s"], [120113, 1, "t"], [120114, 1, "u"], [120115, 1, "v"], [120116, 1, "w"], [120117, 1, "x"], [120118, 1, "y"], [120119, 1, "z"], [120120, 1, "a"], [120121, 1, "b"], [120122, 3], [120123, 1, "d"], [120124, 1, "e"], [120125, 1, "f"], [120126, 1, "g"], [120127, 3], [120128, 1, "i"], [120129, 1, "j"], [120130, 1, "k"], [120131, 1, "l"], [120132, 1, "m"], [120133, 3], [120134, 1, "o"], [[120135, 120137], 3], [120138, 1, "s"], [120139, 1, "t"], [120140, 1, "u"], [120141, 1, "v"], [120142, 1, "w"], [120143, 1, "x"], [120144, 1, "y"], [120145, 3], [120146, 1, "a"], [120147, 1, "b"], [120148, 1, "c"], [120149, 1, "d"], [120150, 1, "e"], [120151, 1, "f"], [120152, 1, "g"], [120153, 1, "h"], [120154, 1, "i"], [120155, 1, "j"], [120156, 1, "k"], [120157, 1, "l"], [120158, 1, "m"], [120159, 1, "n"], [120160, 1, "o"], [120161, 1, "p"], [120162, 1, "q"], [120163, 1, "r"], [120164, 1, "s"], [120165, 1, "t"], [120166, 1, "u"], [120167, 1, "v"], [120168, 1, "w"], [120169, 1, "x"], [120170, 1, "y"], [120171, 1, "z"], [120172, 1, "a"], [120173, 1, "b"], [120174, 1, "c"], [120175, 1, "d"], [120176, 1, "e"], [120177, 1, "f"], [120178, 1, "g"], [120179, 1, "h"], [120180, 1, "i"], [120181, 1, "j"], [120182, 1, "k"], [120183, 1, "l"], [120184, 1, "m"], [120185, 1, "n"], [120186, 1, "o"], [120187, 1, "p"], [120188, 1, "q"], [120189, 1, "r"], [120190, 1, "s"], [120191, 1, "t"], [120192, 1, "u"], [120193, 1, "v"], [120194, 1, "w"], [120195, 1, "x"], [120196, 1, "y"], [120197, 1, "z"], [120198, 1, "a"], [120199, 1, "b"], [120200, 1, "c"], [120201, 1, "d"], [120202, 1, "e"], [120203, 1, "f"], [120204, 1, "g"], [120205, 1, "h"], [120206, 1, "i"], [120207, 1, "j"], [120208, 1, "k"], [120209, 1, "l"], [120210, 1, "m"], [120211, 1, "n"], [120212, 1, "o"], [120213, 1, "p"], [120214, 1, "q"], [120215, 1, "r"], [120216, 1, "s"], [120217, 1, "t"], [120218, 1, "u"], [120219, 1, "v"], [120220, 1, "w"], [120221, 1, "x"], [120222, 1, "y"], [120223, 1, "z"], [120224, 1, "a"], [120225, 1, "b"], [120226, 1, "c"], [120227, 1, "d"], [120228, 1, "e"], [120229, 1, "f"], [120230, 1, "g"], [120231, 1, "h"], [120232, 1, "i"], [120233, 1, "j"], [120234, 1, "k"], [120235, 1, "l"], [120236, 1, "m"], [120237, 1, "n"], [120238, 1, "o"], [120239, 1, "p"], [120240, 1, "q"], [120241, 1, "r"], [120242, 1, "s"], [120243, 1, "t"], [120244, 1, "u"], [120245, 1, "v"], [120246, 1, "w"], [120247, 1, "x"], [120248, 1, "y"], [120249, 1, "z"], [120250, 1, "a"], [120251, 1, "b"], [120252, 1, "c"], [120253, 1, "d"], [120254, 1, "e"], [120255, 1, "f"], [120256, 1, "g"], [120257, 1, "h"], [120258, 1, "i"], [120259, 1, "j"], [120260, 1, "k"], [120261, 1, "l"], [120262, 1, "m"], [120263, 1, "n"], [120264, 1, "o"], [120265, 1, "p"], [120266, 1, "q"], [120267, 1, "r"], [120268, 1, "s"], [120269, 1, "t"], [120270, 1, "u"], [120271, 1, "v"], [120272, 1, "w"], [120273, 1, "x"], [120274, 1, "y"], [120275, 1, "z"], [120276, 1, "a"], [120277, 1, "b"], [120278, 1, "c"], [120279, 1, "d"], [120280, 1, "e"], [120281, 1, "f"], [120282, 1, "g"], [120283, 1, "h"], [120284, 1, "i"], [120285, 1, "j"], [120286, 1, "k"], [120287, 1, "l"], [120288, 1, "m"], [120289, 1, "n"], [120290, 1, "o"], [120291, 1, "p"], [120292, 1, "q"], [120293, 1, "r"], [120294, 1, "s"], [120295, 1, "t"], [120296, 1, "u"], [120297, 1, "v"], [120298, 1, "w"], [120299, 1, "x"], [120300, 1, "y"], [120301, 1, "z"], [120302, 1, "a"], [120303, 1, "b"], [120304, 1, "c"], [120305, 1, "d"], [120306, 1, "e"], [120307, 1, "f"], [120308, 1, "g"], [120309, 1, "h"], [120310, 1, "i"], [120311, 1, "j"], [120312, 1, "k"], [120313, 1, "l"], [120314, 1, "m"], [120315, 1, "n"], [120316, 1, "o"], [120317, 1, "p"], [120318, 1, "q"], [120319, 1, "r"], [120320, 1, "s"], [120321, 1, "t"], [120322, 1, "u"], [120323, 1, "v"], [120324, 1, "w"], [120325, 1, "x"], [120326, 1, "y"], [120327, 1, "z"], [120328, 1, "a"], [120329, 1, "b"], [120330, 1, "c"], [120331, 1, "d"], [120332, 1, "e"], [120333, 1, "f"], [120334, 1, "g"], [120335, 1, "h"], [120336, 1, "i"], [120337, 1, "j"], [120338, 1, "k"], [120339, 1, "l"], [120340, 1, "m"], [120341, 1, "n"], [120342, 1, "o"], [120343, 1, "p"], [120344, 1, "q"], [120345, 1, "r"], [120346, 1, "s"], [120347, 1, "t"], [120348, 1, "u"], [120349, 1, "v"], [120350, 1, "w"], [120351, 1, "x"], [120352, 1, "y"], [120353, 1, "z"], [120354, 1, "a"], [120355, 1, "b"], [120356, 1, "c"], [120357, 1, "d"], [120358, 1, "e"], [120359, 1, "f"], [120360, 1, "g"], [120361, 1, "h"], [120362, 1, "i"], [120363, 1, "j"], [120364, 1, "k"], [120365, 1, "l"], [120366, 1, "m"], [120367, 1, "n"], [120368, 1, "o"], [120369, 1, "p"], [120370, 1, "q"], [120371, 1, "r"], [120372, 1, "s"], [120373, 1, "t"], [120374, 1, "u"], [120375, 1, "v"], [120376, 1, "w"], [120377, 1, "x"], [120378, 1, "y"], [120379, 1, "z"], [120380, 1, "a"], [120381, 1, "b"], [120382, 1, "c"], [120383, 1, "d"], [120384, 1, "e"], [120385, 1, "f"], [120386, 1, "g"], [120387, 1, "h"], [120388, 1, "i"], [120389, 1, "j"], [120390, 1, "k"], [120391, 1, "l"], [120392, 1, "m"], [120393, 1, "n"], [120394, 1, "o"], [120395, 1, "p"], [120396, 1, "q"], [120397, 1, "r"], [120398, 1, "s"], [120399, 1, "t"], [120400, 1, "u"], [120401, 1, "v"], [120402, 1, "w"], [120403, 1, "x"], [120404, 1, "y"], [120405, 1, "z"], [120406, 1, "a"], [120407, 1, "b"], [120408, 1, "c"], [120409, 1, "d"], [120410, 1, "e"], [120411, 1, "f"], [120412, 1, "g"], [120413, 1, "h"], [120414, 1, "i"], [120415, 1, "j"], [120416, 1, "k"], [120417, 1, "l"], [120418, 1, "m"], [120419, 1, "n"], [120420, 1, "o"], [120421, 1, "p"], [120422, 1, "q"], [120423, 1, "r"], [120424, 1, "s"], [120425, 1, "t"], [120426, 1, "u"], [120427, 1, "v"], [120428, 1, "w"], [120429, 1, "x"], [120430, 1, "y"], [120431, 1, "z"], [120432, 1, "a"], [120433, 1, "b"], [120434, 1, "c"], [120435, 1, "d"], [120436, 1, "e"], [120437, 1, "f"], [120438, 1, "g"], [120439, 1, "h"], [120440, 1, "i"], [120441, 1, "j"], [120442, 1, "k"], [120443, 1, "l"], [120444, 1, "m"], [120445, 1, "n"], [120446, 1, "o"], [120447, 1, "p"], [120448, 1, "q"], [120449, 1, "r"], [120450, 1, "s"], [120451, 1, "t"], [120452, 1, "u"], [120453, 1, "v"], [120454, 1, "w"], [120455, 1, "x"], [120456, 1, "y"], [120457, 1, "z"], [120458, 1, "a"], [120459, 1, "b"], [120460, 1, "c"], [120461, 1, "d"], [120462, 1, "e"], [120463, 1, "f"], [120464, 1, "g"], [120465, 1, "h"], [120466, 1, "i"], [120467, 1, "j"], [120468, 1, "k"], [120469, 1, "l"], [120470, 1, "m"], [120471, 1, "n"], [120472, 1, "o"], [120473, 1, "p"], [120474, 1, "q"], [120475, 1, "r"], [120476, 1, "s"], [120477, 1, "t"], [120478, 1, "u"], [120479, 1, "v"], [120480, 1, "w"], [120481, 1, "x"], [120482, 1, "y"], [120483, 1, "z"], [120484, 1, "\u0131"], [120485, 1, "\u0237"], [[120486, 120487], 3], [120488, 1, "\u03B1"], [120489, 1, "\u03B2"], [120490, 1, "\u03B3"], [120491, 1, "\u03B4"], [120492, 1, "\u03B5"], [120493, 1, "\u03B6"], [120494, 1, "\u03B7"], [120495, 1, "\u03B8"], [120496, 1, "\u03B9"], [120497, 1, "\u03BA"], [120498, 1, "\u03BB"], [120499, 1, "\u03BC"], [120500, 1, "\u03BD"], [120501, 1, "\u03BE"], [120502, 1, "\u03BF"], [120503, 1, "\u03C0"], [120504, 1, "\u03C1"], [120505, 1, "\u03B8"], [120506, 1, "\u03C3"], [120507, 1, "\u03C4"], [120508, 1, "\u03C5"], [120509, 1, "\u03C6"], [120510, 1, "\u03C7"], [120511, 1, "\u03C8"], [120512, 1, "\u03C9"], [120513, 1, "\u2207"], [120514, 1, "\u03B1"], [120515, 1, "\u03B2"], [120516, 1, "\u03B3"], [120517, 1, "\u03B4"], [120518, 1, "\u03B5"], [120519, 1, "\u03B6"], [120520, 1, "\u03B7"], [120521, 1, "\u03B8"], [120522, 1, "\u03B9"], [120523, 1, "\u03BA"], [120524, 1, "\u03BB"], [120525, 1, "\u03BC"], [120526, 1, "\u03BD"], [120527, 1, "\u03BE"], [120528, 1, "\u03BF"], [120529, 1, "\u03C0"], [120530, 1, "\u03C1"], [[120531, 120532], 1, "\u03C3"], [120533, 1, "\u03C4"], [120534, 1, "\u03C5"], [120535, 1, "\u03C6"], [120536, 1, "\u03C7"], [120537, 1, "\u03C8"], [120538, 1, "\u03C9"], [120539, 1, "\u2202"], [120540, 1, "\u03B5"], [120541, 1, "\u03B8"], [120542, 1, "\u03BA"], [120543, 1, "\u03C6"], [120544, 1, "\u03C1"], [120545, 1, "\u03C0"], [120546, 1, "\u03B1"], [120547, 1, "\u03B2"], [120548, 1, "\u03B3"], [120549, 1, "\u03B4"], [120550, 1, "\u03B5"], [120551, 1, "\u03B6"], [120552, 1, "\u03B7"], [120553, 1, "\u03B8"], [120554, 1, "\u03B9"], [120555, 1, "\u03BA"], [120556, 1, "\u03BB"], [120557, 1, "\u03BC"], [120558, 1, "\u03BD"], [120559, 1, "\u03BE"], [120560, 1, "\u03BF"], [120561, 1, "\u03C0"], [120562, 1, "\u03C1"], [120563, 1, "\u03B8"], [120564, 1, "\u03C3"], [120565, 1, "\u03C4"], [120566, 1, "\u03C5"], [120567, 1, "\u03C6"], [120568, 1, "\u03C7"], [120569, 1, "\u03C8"], [120570, 1, "\u03C9"], [120571, 1, "\u2207"], [120572, 1, "\u03B1"], [120573, 1, "\u03B2"], [120574, 1, "\u03B3"], [120575, 1, "\u03B4"], [120576, 1, "\u03B5"], [120577, 1, "\u03B6"], [120578, 1, "\u03B7"], [120579, 1, "\u03B8"], [120580, 1, "\u03B9"], [120581, 1, "\u03BA"], [120582, 1, "\u03BB"], [120583, 1, "\u03BC"], [120584, 1, "\u03BD"], [120585, 1, "\u03BE"], [120586, 1, "\u03BF"], [120587, 1, "\u03C0"], [120588, 1, "\u03C1"], [[120589, 120590], 1, "\u03C3"], [120591, 1, "\u03C4"], [120592, 1, "\u03C5"], [120593, 1, "\u03C6"], [120594, 1, "\u03C7"], [120595, 1, "\u03C8"], [120596, 1, "\u03C9"], [120597, 1, "\u2202"], [120598, 1, "\u03B5"], [120599, 1, "\u03B8"], [120600, 1, "\u03BA"], [120601, 1, "\u03C6"], [120602, 1, "\u03C1"], [120603, 1, "\u03C0"], [120604, 1, "\u03B1"], [120605, 1, "\u03B2"], [120606, 1, "\u03B3"], [120607, 1, "\u03B4"], [120608, 1, "\u03B5"], [120609, 1, "\u03B6"], [120610, 1, "\u03B7"], [120611, 1, "\u03B8"], [120612, 1, "\u03B9"], [120613, 1, "\u03BA"], [120614, 1, "\u03BB"], [120615, 1, "\u03BC"], [120616, 1, "\u03BD"], [120617, 1, "\u03BE"], [120618, 1, "\u03BF"], [120619, 1, "\u03C0"], [120620, 1, "\u03C1"], [120621, 1, "\u03B8"], [120622, 1, "\u03C3"], [120623, 1, "\u03C4"], [120624, 1, "\u03C5"], [120625, 1, "\u03C6"], [120626, 1, "\u03C7"], [120627, 1, "\u03C8"], [120628, 1, "\u03C9"], [120629, 1, "\u2207"], [120630, 1, "\u03B1"], [120631, 1, "\u03B2"], [120632, 1, "\u03B3"], [120633, 1, "\u03B4"], [120634, 1, "\u03B5"], [120635, 1, "\u03B6"], [120636, 1, "\u03B7"], [120637, 1, "\u03B8"], [120638, 1, "\u03B9"], [120639, 1, "\u03BA"], [120640, 1, "\u03BB"], [120641, 1, "\u03BC"], [120642, 1, "\u03BD"], [120643, 1, "\u03BE"], [120644, 1, "\u03BF"], [120645, 1, "\u03C0"], [120646, 1, "\u03C1"], [[120647, 120648], 1, "\u03C3"], [120649, 1, "\u03C4"], [120650, 1, "\u03C5"], [120651, 1, "\u03C6"], [120652, 1, "\u03C7"], [120653, 1, "\u03C8"], [120654, 1, "\u03C9"], [120655, 1, "\u2202"], [120656, 1, "\u03B5"], [120657, 1, "\u03B8"], [120658, 1, "\u03BA"], [120659, 1, "\u03C6"], [120660, 1, "\u03C1"], [120661, 1, "\u03C0"], [120662, 1, "\u03B1"], [120663, 1, "\u03B2"], [120664, 1, "\u03B3"], [120665, 1, "\u03B4"], [120666, 1, "\u03B5"], [120667, 1, "\u03B6"], [120668, 1, "\u03B7"], [120669, 1, "\u03B8"], [120670, 1, "\u03B9"], [120671, 1, "\u03BA"], [120672, 1, "\u03BB"], [120673, 1, "\u03BC"], [120674, 1, "\u03BD"], [120675, 1, "\u03BE"], [120676, 1, "\u03BF"], [120677, 1, "\u03C0"], [120678, 1, "\u03C1"], [120679, 1, "\u03B8"], [120680, 1, "\u03C3"], [120681, 1, "\u03C4"], [120682, 1, "\u03C5"], [120683, 1, "\u03C6"], [120684, 1, "\u03C7"], [120685, 1, "\u03C8"], [120686, 1, "\u03C9"], [120687, 1, "\u2207"], [120688, 1, "\u03B1"], [120689, 1, "\u03B2"], [120690, 1, "\u03B3"], [120691, 1, "\u03B4"], [120692, 1, "\u03B5"], [120693, 1, "\u03B6"], [120694, 1, "\u03B7"], [120695, 1, "\u03B8"], [120696, 1, "\u03B9"], [120697, 1, "\u03BA"], [120698, 1, "\u03BB"], [120699, 1, "\u03BC"], [120700, 1, "\u03BD"], [120701, 1, "\u03BE"], [120702, 1, "\u03BF"], [120703, 1, "\u03C0"], [120704, 1, "\u03C1"], [[120705, 120706], 1, "\u03C3"], [120707, 1, "\u03C4"], [120708, 1, "\u03C5"], [120709, 1, "\u03C6"], [120710, 1, "\u03C7"], [120711, 1, "\u03C8"], [120712, 1, "\u03C9"], [120713, 1, "\u2202"], [120714, 1, "\u03B5"], [120715, 1, "\u03B8"], [120716, 1, "\u03BA"], [120717, 1, "\u03C6"], [120718, 1, "\u03C1"], [120719, 1, "\u03C0"], [120720, 1, "\u03B1"], [120721, 1, "\u03B2"], [120722, 1, "\u03B3"], [120723, 1, "\u03B4"], [120724, 1, "\u03B5"], [120725, 1, "\u03B6"], [120726, 1, "\u03B7"], [120727, 1, "\u03B8"], [120728, 1, "\u03B9"], [120729, 1, "\u03BA"], [120730, 1, "\u03BB"], [120731, 1, "\u03BC"], [120732, 1, "\u03BD"], [120733, 1, "\u03BE"], [120734, 1, "\u03BF"], [120735, 1, "\u03C0"], [120736, 1, "\u03C1"], [120737, 1, "\u03B8"], [120738, 1, "\u03C3"], [120739, 1, "\u03C4"], [120740, 1, "\u03C5"], [120741, 1, "\u03C6"], [120742, 1, "\u03C7"], [120743, 1, "\u03C8"], [120744, 1, "\u03C9"], [120745, 1, "\u2207"], [120746, 1, "\u03B1"], [120747, 1, "\u03B2"], [120748, 1, "\u03B3"], [120749, 1, "\u03B4"], [120750, 1, "\u03B5"], [120751, 1, "\u03B6"], [120752, 1, "\u03B7"], [120753, 1, "\u03B8"], [120754, 1, "\u03B9"], [120755, 1, "\u03BA"], [120756, 1, "\u03BB"], [120757, 1, "\u03BC"], [120758, 1, "\u03BD"], [120759, 1, "\u03BE"], [120760, 1, "\u03BF"], [120761, 1, "\u03C0"], [120762, 1, "\u03C1"], [[120763, 120764], 1, "\u03C3"], [120765, 1, "\u03C4"], [120766, 1, "\u03C5"], [120767, 1, "\u03C6"], [120768, 1, "\u03C7"], [120769, 1, "\u03C8"], [120770, 1, "\u03C9"], [120771, 1, "\u2202"], [120772, 1, "\u03B5"], [120773, 1, "\u03B8"], [120774, 1, "\u03BA"], [120775, 1, "\u03C6"], [120776, 1, "\u03C1"], [120777, 1, "\u03C0"], [[120778, 120779], 1, "\u03DD"], [[120780, 120781], 3], [120782, 1, "0"], [120783, 1, "1"], [120784, 1, "2"], [120785, 1, "3"], [120786, 1, "4"], [120787, 1, "5"], [120788, 1, "6"], [120789, 1, "7"], [120790, 1, "8"], [120791, 1, "9"], [120792, 1, "0"], [120793, 1, "1"], [120794, 1, "2"], [120795, 1, "3"], [120796, 1, "4"], [120797, 1, "5"], [120798, 1, "6"], [120799, 1, "7"], [120800, 1, "8"], [120801, 1, "9"], [120802, 1, "0"], [120803, 1, "1"], [120804, 1, "2"], [120805, 1, "3"], [120806, 1, "4"], [120807, 1, "5"], [120808, 1, "6"], [120809, 1, "7"], [120810, 1, "8"], [120811, 1, "9"], [120812, 1, "0"], [120813, 1, "1"], [120814, 1, "2"], [120815, 1, "3"], [120816, 1, "4"], [120817, 1, "5"], [120818, 1, "6"], [120819, 1, "7"], [120820, 1, "8"], [120821, 1, "9"], [120822, 1, "0"], [120823, 1, "1"], [120824, 1, "2"], [120825, 1, "3"], [120826, 1, "4"], [120827, 1, "5"], [120828, 1, "6"], [120829, 1, "7"], [120830, 1, "8"], [120831, 1, "9"], [[120832, 121343], 2], [[121344, 121398], 2], [[121399, 121402], 2], [[121403, 121452], 2], [[121453, 121460], 2], [121461, 2], [[121462, 121475], 2], [121476, 2], [[121477, 121483], 2], [[121484, 121498], 3], [[121499, 121503], 2], [121504, 3], [[121505, 121519], 2], [[121520, 122623], 3], [[122624, 122654], 2], [[122655, 122660], 3], [[122661, 122666], 2], [[122667, 122879], 3], [[122880, 122886], 2], [122887, 3], [[122888, 122904], 2], [[122905, 122906], 3], [[122907, 122913], 2], [122914, 3], [[122915, 122916], 2], [122917, 3], [[122918, 122922], 2], [[122923, 122927], 3], [122928, 1, "\u0430"], [122929, 1, "\u0431"], [122930, 1, "\u0432"], [122931, 1, "\u0433"], [122932, 1, "\u0434"], [122933, 1, "\u0435"], [122934, 1, "\u0436"], [122935, 1, "\u0437"], [122936, 1, "\u0438"], [122937, 1, "\u043A"], [122938, 1, "\u043B"], [122939, 1, "\u043C"], [122940, 1, "\u043E"], [122941, 1, "\u043F"], [122942, 1, "\u0440"], [122943, 1, "\u0441"], [122944, 1, "\u0442"], [122945, 1, "\u0443"], [122946, 1, "\u0444"], [122947, 1, "\u0445"], [122948, 1, "\u0446"], [122949, 1, "\u0447"], [122950, 1, "\u0448"], [122951, 1, "\u044B"], [122952, 1, "\u044D"], [122953, 1, "\u044E"], [122954, 1, "\uA689"], [122955, 1, "\u04D9"], [122956, 1, "\u0456"], [122957, 1, "\u0458"], [122958, 1, "\u04E9"], [122959, 1, "\u04AF"], [122960, 1, "\u04CF"], [122961, 1, "\u0430"], [122962, 1, "\u0431"], [122963, 1, "\u0432"], [122964, 1, "\u0433"], [122965, 1, "\u0434"], [122966, 1, "\u0435"], [122967, 1, "\u0436"], [122968, 1, "\u0437"], [122969, 1, "\u0438"], [122970, 1, "\u043A"], [122971, 1, "\u043B"], [122972, 1, "\u043E"], [122973, 1, "\u043F"], [122974, 1, "\u0441"], [122975, 1, "\u0443"], [122976, 1, "\u0444"], [122977, 1, "\u0445"], [122978, 1, "\u0446"], [122979, 1, "\u0447"], [122980, 1, "\u0448"], [122981, 1, "\u044A"], [122982, 1, "\u044B"], [122983, 1, "\u0491"], [122984, 1, "\u0456"], [122985, 1, "\u0455"], [122986, 1, "\u045F"], [122987, 1, "\u04AB"], [122988, 1, "\uA651"], [122989, 1, "\u04B1"], [[122990, 123022], 3], [123023, 2], [[123024, 123135], 3], [[123136, 123180], 2], [[123181, 123183], 3], [[123184, 123197], 2], [[123198, 123199], 3], [[123200, 123209], 2], [[123210, 123213], 3], [123214, 2], [123215, 2], [[123216, 123535], 3], [[123536, 123566], 2], [[123567, 123583], 3], [[123584, 123641], 2], [[123642, 123646], 3], [123647, 2], [[123648, 124111], 3], [[124112, 124153], 2], [[124154, 124367], 3], [[124368, 124410], 2], [[124411, 124414], 3], [124415, 2], [[124416, 124895], 3], [[124896, 124902], 2], [124903, 3], [[124904, 124907], 2], [124908, 3], [[124909, 124910], 2], [124911, 3], [[124912, 124926], 2], [124927, 3], [[124928, 125124], 2], [[125125, 125126], 3], [[125127, 125135], 2], [[125136, 125142], 2], [[125143, 125183], 3], [125184, 1, "\u{1E922}"], [125185, 1, "\u{1E923}"], [125186, 1, "\u{1E924}"], [125187, 1, "\u{1E925}"], [125188, 1, "\u{1E926}"], [125189, 1, "\u{1E927}"], [125190, 1, "\u{1E928}"], [125191, 1, "\u{1E929}"], [125192, 1, "\u{1E92A}"], [125193, 1, "\u{1E92B}"], [125194, 1, "\u{1E92C}"], [125195, 1, "\u{1E92D}"], [125196, 1, "\u{1E92E}"], [125197, 1, "\u{1E92F}"], [125198, 1, "\u{1E930}"], [125199, 1, "\u{1E931}"], [125200, 1, "\u{1E932}"], [125201, 1, "\u{1E933}"], [125202, 1, "\u{1E934}"], [125203, 1, "\u{1E935}"], [125204, 1, "\u{1E936}"], [125205, 1, "\u{1E937}"], [125206, 1, "\u{1E938}"], [125207, 1, "\u{1E939}"], [125208, 1, "\u{1E93A}"], [125209, 1, "\u{1E93B}"], [125210, 1, "\u{1E93C}"], [125211, 1, "\u{1E93D}"], [125212, 1, "\u{1E93E}"], [125213, 1, "\u{1E93F}"], [125214, 1, "\u{1E940}"], [125215, 1, "\u{1E941}"], [125216, 1, "\u{1E942}"], [125217, 1, "\u{1E943}"], [[125218, 125258], 2], [125259, 2], [[125260, 125263], 3], [[125264, 125273], 2], [[125274, 125277], 3], [[125278, 125279], 2], [[125280, 126064], 3], [[126065, 126132], 2], [[126133, 126208], 3], [[126209, 126269], 2], [[126270, 126463], 3], [126464, 1, "\u0627"], [126465, 1, "\u0628"], [126466, 1, "\u062C"], [126467, 1, "\u062F"], [126468, 3], [126469, 1, "\u0648"], [126470, 1, "\u0632"], [126471, 1, "\u062D"], [126472, 1, "\u0637"], [126473, 1, "\u064A"], [126474, 1, "\u0643"], [126475, 1, "\u0644"], [126476, 1, "\u0645"], [126477, 1, "\u0646"], [126478, 1, "\u0633"], [126479, 1, "\u0639"], [126480, 1, "\u0641"], [126481, 1, "\u0635"], [126482, 1, "\u0642"], [126483, 1, "\u0631"], [126484, 1, "\u0634"], [126485, 1, "\u062A"], [126486, 1, "\u062B"], [126487, 1, "\u062E"], [126488, 1, "\u0630"], [126489, 1, "\u0636"], [126490, 1, "\u0638"], [126491, 1, "\u063A"], [126492, 1, "\u066E"], [126493, 1, "\u06BA"], [126494, 1, "\u06A1"], [126495, 1, "\u066F"], [126496, 3], [126497, 1, "\u0628"], [126498, 1, "\u062C"], [126499, 3], [126500, 1, "\u0647"], [[126501, 126502], 3], [126503, 1, "\u062D"], [126504, 3], [126505, 1, "\u064A"], [126506, 1, "\u0643"], [126507, 1, "\u0644"], [126508, 1, "\u0645"], [126509, 1, "\u0646"], [126510, 1, "\u0633"], [126511, 1, "\u0639"], [126512, 1, "\u0641"], [126513, 1, "\u0635"], [126514, 1, "\u0642"], [126515, 3], [126516, 1, "\u0634"], [126517, 1, "\u062A"], [126518, 1, "\u062B"], [126519, 1, "\u062E"], [126520, 3], [126521, 1, "\u0636"], [126522, 3], [126523, 1, "\u063A"], [[126524, 126529], 3], [126530, 1, "\u062C"], [[126531, 126534], 3], [126535, 1, "\u062D"], [126536, 3], [126537, 1, "\u064A"], [126538, 3], [126539, 1, "\u0644"], [126540, 3], [126541, 1, "\u0646"], [126542, 1, "\u0633"], [126543, 1, "\u0639"], [126544, 3], [126545, 1, "\u0635"], [126546, 1, "\u0642"], [126547, 3], [126548, 1, "\u0634"], [[126549, 126550], 3], [126551, 1, "\u062E"], [126552, 3], [126553, 1, "\u0636"], [126554, 3], [126555, 1, "\u063A"], [126556, 3], [126557, 1, "\u06BA"], [126558, 3], [126559, 1, "\u066F"], [126560, 3], [126561, 1, "\u0628"], [126562, 1, "\u062C"], [126563, 3], [126564, 1, "\u0647"], [[126565, 126566], 3], [126567, 1, "\u062D"], [126568, 1, "\u0637"], [126569, 1, "\u064A"], [126570, 1, "\u0643"], [126571, 3], [126572, 1, "\u0645"], [126573, 1, "\u0646"], [126574, 1, "\u0633"], [126575, 1, "\u0639"], [126576, 1, "\u0641"], [126577, 1, "\u0635"], [126578, 1, "\u0642"], [126579, 3], [126580, 1, "\u0634"], [126581, 1, "\u062A"], [126582, 1, "\u062B"], [126583, 1, "\u062E"], [126584, 3], [126585, 1, "\u0636"], [126586, 1, "\u0638"], [126587, 1, "\u063A"], [126588, 1, "\u066E"], [126589, 3], [126590, 1, "\u06A1"], [126591, 3], [126592, 1, "\u0627"], [126593, 1, "\u0628"], [126594, 1, "\u062C"], [126595, 1, "\u062F"], [126596, 1, "\u0647"], [126597, 1, "\u0648"], [126598, 1, "\u0632"], [126599, 1, "\u062D"], [126600, 1, "\u0637"], [126601, 1, "\u064A"], [126602, 3], [126603, 1, "\u0644"], [126604, 1, "\u0645"], [126605, 1, "\u0646"], [126606, 1, "\u0633"], [126607, 1, "\u0639"], [126608, 1, "\u0641"], [126609, 1, "\u0635"], [126610, 1, "\u0642"], [126611, 1, "\u0631"], [126612, 1, "\u0634"], [126613, 1, "\u062A"], [126614, 1, "\u062B"], [126615, 1, "\u062E"], [126616, 1, "\u0630"], [126617, 1, "\u0636"], [126618, 1, "\u0638"], [126619, 1, "\u063A"], [[126620, 126624], 3], [126625, 1, "\u0628"], [126626, 1, "\u062C"], [126627, 1, "\u062F"], [126628, 3], [126629, 1, "\u0648"], [126630, 1, "\u0632"], [126631, 1, "\u062D"], [126632, 1, "\u0637"], [126633, 1, "\u064A"], [126634, 3], [126635, 1, "\u0644"], [126636, 1, "\u0645"], [126637, 1, "\u0646"], [126638, 1, "\u0633"], [126639, 1, "\u0639"], [126640, 1, "\u0641"], [126641, 1, "\u0635"], [126642, 1, "\u0642"], [126643, 1, "\u0631"], [126644, 1, "\u0634"], [126645, 1, "\u062A"], [126646, 1, "\u062B"], [126647, 1, "\u062E"], [126648, 1, "\u0630"], [126649, 1, "\u0636"], [126650, 1, "\u0638"], [126651, 1, "\u063A"], [[126652, 126703], 3], [[126704, 126705], 2], [[126706, 126975], 3], [[126976, 127019], 2], [[127020, 127023], 3], [[127024, 127123], 2], [[127124, 127135], 3], [[127136, 127150], 2], [[127151, 127152], 3], [[127153, 127166], 2], [127167, 2], [127168, 3], [[127169, 127183], 2], [127184, 3], [[127185, 127199], 2], [[127200, 127221], 2], [[127222, 127231], 3], [127232, 3], [127233, 1, "0,"], [127234, 1, "1,"], [127235, 1, "2,"], [127236, 1, "3,"], [127237, 1, "4,"], [127238, 1, "5,"], [127239, 1, "6,"], [127240, 1, "7,"], [127241, 1, "8,"], [127242, 1, "9,"], [[127243, 127244], 2], [[127245, 127247], 2], [127248, 1, "(a)"], [127249, 1, "(b)"], [127250, 1, "(c)"], [127251, 1, "(d)"], [127252, 1, "(e)"], [127253, 1, "(f)"], [127254, 1, "(g)"], [127255, 1, "(h)"], [127256, 1, "(i)"], [127257, 1, "(j)"], [127258, 1, "(k)"], [127259, 1, "(l)"], [127260, 1, "(m)"], [127261, 1, "(n)"], [127262, 1, "(o)"], [127263, 1, "(p)"], [127264, 1, "(q)"], [127265, 1, "(r)"], [127266, 1, "(s)"], [127267, 1, "(t)"], [127268, 1, "(u)"], [127269, 1, "(v)"], [127270, 1, "(w)"], [127271, 1, "(x)"], [127272, 1, "(y)"], [127273, 1, "(z)"], [127274, 1, "\u3014s\u3015"], [127275, 1, "c"], [127276, 1, "r"], [127277, 1, "cd"], [127278, 1, "wz"], [127279, 2], [127280, 1, "a"], [127281, 1, "b"], [127282, 1, "c"], [127283, 1, "d"], [127284, 1, "e"], [127285, 1, "f"], [127286, 1, "g"], [127287, 1, "h"], [127288, 1, "i"], [127289, 1, "j"], [127290, 1, "k"], [127291, 1, "l"], [127292, 1, "m"], [127293, 1, "n"], [127294, 1, "o"], [127295, 1, "p"], [127296, 1, "q"], [127297, 1, "r"], [127298, 1, "s"], [127299, 1, "t"], [127300, 1, "u"], [127301, 1, "v"], [127302, 1, "w"], [127303, 1, "x"], [127304, 1, "y"], [127305, 1, "z"], [127306, 1, "hv"], [127307, 1, "mv"], [127308, 1, "sd"], [127309, 1, "ss"], [127310, 1, "ppv"], [127311, 1, "wc"], [[127312, 127318], 2], [127319, 2], [[127320, 127326], 2], [127327, 2], [[127328, 127337], 2], [127338, 1, "mc"], [127339, 1, "md"], [127340, 1, "mr"], [[127341, 127343], 2], [[127344, 127352], 2], [127353, 2], [127354, 2], [[127355, 127356], 2], [[127357, 127358], 2], [127359, 2], [[127360, 127369], 2], [[127370, 127373], 2], [[127374, 127375], 2], [127376, 1, "dj"], [[127377, 127386], 2], [[127387, 127404], 2], [127405, 2], [[127406, 127461], 3], [[127462, 127487], 2], [127488, 1, "\u307B\u304B"], [127489, 1, "\u30B3\u30B3"], [127490, 1, "\u30B5"], [[127491, 127503], 3], [127504, 1, "\u624B"], [127505, 1, "\u5B57"], [127506, 1, "\u53CC"], [127507, 1, "\u30C7"], [127508, 1, "\u4E8C"], [127509, 1, "\u591A"], [127510, 1, "\u89E3"], [127511, 1, "\u5929"], [127512, 1, "\u4EA4"], [127513, 1, "\u6620"], [127514, 1, "\u7121"], [127515, 1, "\u6599"], [127516, 1, "\u524D"], [127517, 1, "\u5F8C"], [127518, 1, "\u518D"], [127519, 1, "\u65B0"], [127520, 1, "\u521D"], [127521, 1, "\u7D42"], [127522, 1, "\u751F"], [127523, 1, "\u8CA9"], [127524, 1, "\u58F0"], [127525, 1, "\u5439"], [127526, 1, "\u6F14"], [127527, 1, "\u6295"], [127528, 1, "\u6355"], [127529, 1, "\u4E00"], [127530, 1, "\u4E09"], [127531, 1, "\u904A"], [127532, 1, "\u5DE6"], [127533, 1, "\u4E2D"], [127534, 1, "\u53F3"], [127535, 1, "\u6307"], [127536, 1, "\u8D70"], [127537, 1, "\u6253"], [127538, 1, "\u7981"], [127539, 1, "\u7A7A"], [127540, 1, "\u5408"], [127541, 1, "\u6E80"], [127542, 1, "\u6709"], [127543, 1, "\u6708"], [127544, 1, "\u7533"], [127545, 1, "\u5272"], [127546, 1, "\u55B6"], [127547, 1, "\u914D"], [[127548, 127551], 3], [127552, 1, "\u3014\u672C\u3015"], [127553, 1, "\u3014\u4E09\u3015"], [127554, 1, "\u3014\u4E8C\u3015"], [127555, 1, "\u3014\u5B89\u3015"], [127556, 1, "\u3014\u70B9\u3015"], [127557, 1, "\u3014\u6253\u3015"], [127558, 1, "\u3014\u76D7\u3015"], [127559, 1, "\u3014\u52DD\u3015"], [127560, 1, "\u3014\u6557\u3015"], [[127561, 127567], 3], [127568, 1, "\u5F97"], [127569, 1, "\u53EF"], [[127570, 127583], 3], [[127584, 127589], 2], [[127590, 127743], 3], [[127744, 127776], 2], [[127777, 127788], 2], [[127789, 127791], 2], [[127792, 127797], 2], [127798, 2], [[127799, 127868], 2], [127869, 2], [[127870, 127871], 2], [[127872, 127891], 2], [[127892, 127903], 2], [[127904, 127940], 2], [127941, 2], [[127942, 127946], 2], [[127947, 127950], 2], [[127951, 127955], 2], [[127956, 127967], 2], [[127968, 127984], 2], [[127985, 127991], 2], [[127992, 127999], 2], [[128e3, 128062], 2], [128063, 2], [128064, 2], [128065, 2], [[128066, 128247], 2], [128248, 2], [[128249, 128252], 2], [[128253, 128254], 2], [128255, 2], [[128256, 128317], 2], [[128318, 128319], 2], [[128320, 128323], 2], [[128324, 128330], 2], [[128331, 128335], 2], [[128336, 128359], 2], [[128360, 128377], 2], [128378, 2], [[128379, 128419], 2], [128420, 2], [[128421, 128506], 2], [[128507, 128511], 2], [128512, 2], [[128513, 128528], 2], [128529, 2], [[128530, 128532], 2], [128533, 2], [128534, 2], [128535, 2], [128536, 2], [128537, 2], [128538, 2], [128539, 2], [[128540, 128542], 2], [128543, 2], [[128544, 128549], 2], [[128550, 128551], 2], [[128552, 128555], 2], [128556, 2], [128557, 2], [[128558, 128559], 2], [[128560, 128563], 2], [128564, 2], [[128565, 128576], 2], [[128577, 128578], 2], [[128579, 128580], 2], [[128581, 128591], 2], [[128592, 128639], 2], [[128640, 128709], 2], [[128710, 128719], 2], [128720, 2], [[128721, 128722], 2], [[128723, 128724], 2], [128725, 2], [[128726, 128727], 2], [[128728, 128731], 3], [128732, 2], [[128733, 128735], 2], [[128736, 128748], 2], [[128749, 128751], 3], [[128752, 128755], 2], [[128756, 128758], 2], [[128759, 128760], 2], [128761, 2], [128762, 2], [[128763, 128764], 2], [[128765, 128767], 3], [[128768, 128883], 2], [[128884, 128886], 2], [[128887, 128890], 3], [[128891, 128895], 2], [[128896, 128980], 2], [[128981, 128984], 2], [128985, 2], [[128986, 128991], 3], [[128992, 129003], 2], [[129004, 129007], 3], [129008, 2], [[129009, 129023], 3], [[129024, 129035], 2], [[129036, 129039], 3], [[129040, 129095], 2], [[129096, 129103], 3], [[129104, 129113], 2], [[129114, 129119], 3], [[129120, 129159], 2], [[129160, 129167], 3], [[129168, 129197], 2], [[129198, 129199], 3], [[129200, 129201], 2], [[129202, 129211], 2], [[129212, 129215], 3], [[129216, 129217], 2], [[129218, 129279], 3], [[129280, 129291], 2], [129292, 2], [[129293, 129295], 2], [[129296, 129304], 2], [[129305, 129310], 2], [129311, 2], [[129312, 129319], 2], [[129320, 129327], 2], [129328, 2], [[129329, 129330], 2], [[129331, 129342], 2], [129343, 2], [[129344, 129355], 2], [129356, 2], [[129357, 129359], 2], [[129360, 129374], 2], [[129375, 129387], 2], [[129388, 129392], 2], [129393, 2], [129394, 2], [[129395, 129398], 2], [[129399, 129400], 2], [129401, 2], [129402, 2], [129403, 2], [[129404, 129407], 2], [[129408, 129412], 2], [[129413, 129425], 2], [[129426, 129431], 2], [[129432, 129442], 2], [[129443, 129444], 2], [[129445, 129450], 2], [[129451, 129453], 2], [[129454, 129455], 2], [[129456, 129465], 2], [[129466, 129471], 2], [129472, 2], [[129473, 129474], 2], [[129475, 129482], 2], [129483, 2], [129484, 2], [[129485, 129487], 2], [[129488, 129510], 2], [[129511, 129535], 2], [[129536, 129619], 2], [[129620, 129631], 3], [[129632, 129645], 2], [[129646, 129647], 3], [[129648, 129651], 2], [129652, 2], [[129653, 129655], 2], [[129656, 129658], 2], [[129659, 129660], 2], [[129661, 129663], 3], [[129664, 129666], 2], [[129667, 129670], 2], [[129671, 129672], 2], [129673, 2], [[129674, 129678], 3], [129679, 2], [[129680, 129685], 2], [[129686, 129704], 2], [[129705, 129708], 2], [[129709, 129711], 2], [[129712, 129718], 2], [[129719, 129722], 2], [[129723, 129725], 2], [129726, 2], [129727, 2], [[129728, 129730], 2], [[129731, 129733], 2], [129734, 2], [[129735, 129741], 3], [[129742, 129743], 2], [[129744, 129750], 2], [[129751, 129753], 2], [[129754, 129755], 2], [129756, 2], [[129757, 129758], 3], [129759, 2], [[129760, 129767], 2], [129768, 2], [129769, 2], [[129770, 129775], 3], [[129776, 129782], 2], [[129783, 129784], 2], [[129785, 129791], 3], [[129792, 129938], 2], [129939, 3], [[129940, 129994], 2], [[129995, 130031], 2], [130032, 1, "0"], [130033, 1, "1"], [130034, 1, "2"], [130035, 1, "3"], [130036, 1, "4"], [130037, 1, "5"], [130038, 1, "6"], [130039, 1, "7"], [130040, 1, "8"], [130041, 1, "9"], [[130042, 131069], 3], [[131070, 131071], 3], [[131072, 173782], 2], [[173783, 173789], 2], [[173790, 173791], 2], [[173792, 173823], 3], [[173824, 177972], 2], [[177973, 177976], 2], [177977, 2], [[177978, 177983], 3], [[177984, 178205], 2], [[178206, 178207], 3], [[178208, 183969], 2], [[183970, 183983], 3], [[183984, 191456], 2], [[191457, 191471], 3], [[191472, 192093], 2], [[192094, 194559], 3], [194560, 1, "\u4E3D"], [194561, 1, "\u4E38"], [194562, 1, "\u4E41"], [194563, 1, "\u{20122}"], [194564, 1, "\u4F60"], [194565, 1, "\u4FAE"], [194566, 1, "\u4FBB"], [194567, 1, "\u5002"], [194568, 1, "\u507A"], [194569, 1, "\u5099"], [194570, 1, "\u50E7"], [194571, 1, "\u50CF"], [194572, 1, "\u349E"], [194573, 1, "\u{2063A}"], [194574, 1, "\u514D"], [194575, 1, "\u5154"], [194576, 1, "\u5164"], [194577, 1, "\u5177"], [194578, 1, "\u{2051C}"], [194579, 1, "\u34B9"], [194580, 1, "\u5167"], [194581, 1, "\u518D"], [194582, 1, "\u{2054B}"], [194583, 1, "\u5197"], [194584, 1, "\u51A4"], [194585, 1, "\u4ECC"], [194586, 1, "\u51AC"], [194587, 1, "\u51B5"], [194588, 1, "\u{291DF}"], [194589, 1, "\u51F5"], [194590, 1, "\u5203"], [194591, 1, "\u34DF"], [194592, 1, "\u523B"], [194593, 1, "\u5246"], [194594, 1, "\u5272"], [194595, 1, "\u5277"], [194596, 1, "\u3515"], [194597, 1, "\u52C7"], [194598, 1, "\u52C9"], [194599, 1, "\u52E4"], [194600, 1, "\u52FA"], [194601, 1, "\u5305"], [194602, 1, "\u5306"], [194603, 1, "\u5317"], [194604, 1, "\u5349"], [194605, 1, "\u5351"], [194606, 1, "\u535A"], [194607, 1, "\u5373"], [194608, 1, "\u537D"], [[194609, 194611], 1, "\u537F"], [194612, 1, "\u{20A2C}"], [194613, 1, "\u7070"], [194614, 1, "\u53CA"], [194615, 1, "\u53DF"], [194616, 1, "\u{20B63}"], [194617, 1, "\u53EB"], [194618, 1, "\u53F1"], [194619, 1, "\u5406"], [194620, 1, "\u549E"], [194621, 1, "\u5438"], [194622, 1, "\u5448"], [194623, 1, "\u5468"], [194624, 1, "\u54A2"], [194625, 1, "\u54F6"], [194626, 1, "\u5510"], [194627, 1, "\u5553"], [194628, 1, "\u5563"], [[194629, 194630], 1, "\u5584"], [194631, 1, "\u5599"], [194632, 1, "\u55AB"], [194633, 1, "\u55B3"], [194634, 1, "\u55C2"], [194635, 1, "\u5716"], [194636, 1, "\u5606"], [194637, 1, "\u5717"], [194638, 1, "\u5651"], [194639, 1, "\u5674"], [194640, 1, "\u5207"], [194641, 1, "\u58EE"], [194642, 1, "\u57CE"], [194643, 1, "\u57F4"], [194644, 1, "\u580D"], [194645, 1, "\u578B"], [194646, 1, "\u5832"], [194647, 1, "\u5831"], [194648, 1, "\u58AC"], [194649, 1, "\u{214E4}"], [194650, 1, "\u58F2"], [194651, 1, "\u58F7"], [194652, 1, "\u5906"], [194653, 1, "\u591A"], [194654, 1, "\u5922"], [194655, 1, "\u5962"], [194656, 1, "\u{216A8}"], [194657, 1, "\u{216EA}"], [194658, 1, "\u59EC"], [194659, 1, "\u5A1B"], [194660, 1, "\u5A27"], [194661, 1, "\u59D8"], [194662, 1, "\u5A66"], [194663, 1, "\u36EE"], [194664, 1, "\u36FC"], [194665, 1, "\u5B08"], [[194666, 194667], 1, "\u5B3E"], [194668, 1, "\u{219C8}"], [194669, 1, "\u5BC3"], [194670, 1, "\u5BD8"], [194671, 1, "\u5BE7"], [194672, 1, "\u5BF3"], [194673, 1, "\u{21B18}"], [194674, 1, "\u5BFF"], [194675, 1, "\u5C06"], [194676, 1, "\u5F53"], [194677, 1, "\u5C22"], [194678, 1, "\u3781"], [194679, 1, "\u5C60"], [194680, 1, "\u5C6E"], [194681, 1, "\u5CC0"], [194682, 1, "\u5C8D"], [194683, 1, "\u{21DE4}"], [194684, 1, "\u5D43"], [194685, 1, "\u{21DE6}"], [194686, 1, "\u5D6E"], [194687, 1, "\u5D6B"], [194688, 1, "\u5D7C"], [194689, 1, "\u5DE1"], [194690, 1, "\u5DE2"], [194691, 1, "\u382F"], [194692, 1, "\u5DFD"], [194693, 1, "\u5E28"], [194694, 1, "\u5E3D"], [194695, 1, "\u5E69"], [194696, 1, "\u3862"], [194697, 1, "\u{22183}"], [194698, 1, "\u387C"], [194699, 1, "\u5EB0"], [194700, 1, "\u5EB3"], [194701, 1, "\u5EB6"], [194702, 1, "\u5ECA"], [194703, 1, "\u{2A392}"], [194704, 1, "\u5EFE"], [[194705, 194706], 1, "\u{22331}"], [194707, 1, "\u8201"], [[194708, 194709], 1, "\u5F22"], [194710, 1, "\u38C7"], [194711, 1, "\u{232B8}"], [194712, 1, "\u{261DA}"], [194713, 1, "\u5F62"], [194714, 1, "\u5F6B"], [194715, 1, "\u38E3"], [194716, 1, "\u5F9A"], [194717, 1, "\u5FCD"], [194718, 1, "\u5FD7"], [194719, 1, "\u5FF9"], [194720, 1, "\u6081"], [194721, 1, "\u393A"], [194722, 1, "\u391C"], [194723, 1, "\u6094"], [194724, 1, "\u{226D4}"], [194725, 1, "\u60C7"], [194726, 1, "\u6148"], [194727, 1, "\u614C"], [194728, 1, "\u614E"], [194729, 1, "\u614C"], [194730, 1, "\u617A"], [194731, 1, "\u618E"], [194732, 1, "\u61B2"], [194733, 1, "\u61A4"], [194734, 1, "\u61AF"], [194735, 1, "\u61DE"], [194736, 1, "\u61F2"], [194737, 1, "\u61F6"], [194738, 1, "\u6210"], [194739, 1, "\u621B"], [194740, 1, "\u625D"], [194741, 1, "\u62B1"], [194742, 1, "\u62D4"], [194743, 1, "\u6350"], [194744, 1, "\u{22B0C}"], [194745, 1, "\u633D"], [194746, 1, "\u62FC"], [194747, 1, "\u6368"], [194748, 1, "\u6383"], [194749, 1, "\u63E4"], [194750, 1, "\u{22BF1}"], [194751, 1, "\u6422"], [194752, 1, "\u63C5"], [194753, 1, "\u63A9"], [194754, 1, "\u3A2E"], [194755, 1, "\u6469"], [194756, 1, "\u647E"], [194757, 1, "\u649D"], [194758, 1, "\u6477"], [194759, 1, "\u3A6C"], [194760, 1, "\u654F"], [194761, 1, "\u656C"], [194762, 1, "\u{2300A}"], [194763, 1, "\u65E3"], [194764, 1, "\u66F8"], [194765, 1, "\u6649"], [194766, 1, "\u3B19"], [194767, 1, "\u6691"], [194768, 1, "\u3B08"], [194769, 1, "\u3AE4"], [194770, 1, "\u5192"], [194771, 1, "\u5195"], [194772, 1, "\u6700"], [194773, 1, "\u669C"], [194774, 1, "\u80AD"], [194775, 1, "\u43D9"], [194776, 1, "\u6717"], [194777, 1, "\u671B"], [194778, 1, "\u6721"], [194779, 1, "\u675E"], [194780, 1, "\u6753"], [194781, 1, "\u{233C3}"], [194782, 1, "\u3B49"], [194783, 1, "\u67FA"], [194784, 1, "\u6785"], [194785, 1, "\u6852"], [194786, 1, "\u6885"], [194787, 1, "\u{2346D}"], [194788, 1, "\u688E"], [194789, 1, "\u681F"], [194790, 1, "\u6914"], [194791, 1, "\u3B9D"], [194792, 1, "\u6942"], [194793, 1, "\u69A3"], [194794, 1, "\u69EA"], [194795, 1, "\u6AA8"], [194796, 1, "\u{236A3}"], [194797, 1, "\u6ADB"], [194798, 1, "\u3C18"], [194799, 1, "\u6B21"], [194800, 1, "\u{238A7}"], [194801, 1, "\u6B54"], [194802, 1, "\u3C4E"], [194803, 1, "\u6B72"], [194804, 1, "\u6B9F"], [194805, 1, "\u6BBA"], [194806, 1, "\u6BBB"], [194807, 1, "\u{23A8D}"], [194808, 1, "\u{21D0B}"], [194809, 1, "\u{23AFA}"], [194810, 1, "\u6C4E"], [194811, 1, "\u{23CBC}"], [194812, 1, "\u6CBF"], [194813, 1, "\u6CCD"], [194814, 1, "\u6C67"], [194815, 1, "\u6D16"], [194816, 1, "\u6D3E"], [194817, 1, "\u6D77"], [194818, 1, "\u6D41"], [194819, 1, "\u6D69"], [194820, 1, "\u6D78"], [194821, 1, "\u6D85"], [194822, 1, "\u{23D1E}"], [194823, 1, "\u6D34"], [194824, 1, "\u6E2F"], [194825, 1, "\u6E6E"], [194826, 1, "\u3D33"], [194827, 1, "\u6ECB"], [194828, 1, "\u6EC7"], [194829, 1, "\u{23ED1}"], [194830, 1, "\u6DF9"], [194831, 1, "\u6F6E"], [194832, 1, "\u{23F5E}"], [194833, 1, "\u{23F8E}"], [194834, 1, "\u6FC6"], [194835, 1, "\u7039"], [194836, 1, "\u701E"], [194837, 1, "\u701B"], [194838, 1, "\u3D96"], [194839, 1, "\u704A"], [194840, 1, "\u707D"], [194841, 1, "\u7077"], [194842, 1, "\u70AD"], [194843, 1, "\u{20525}"], [194844, 1, "\u7145"], [194845, 1, "\u{24263}"], [194846, 1, "\u719C"], [194847, 1, "\u{243AB}"], [194848, 1, "\u7228"], [194849, 1, "\u7235"], [194850, 1, "\u7250"], [194851, 1, "\u{24608}"], [194852, 1, "\u7280"], [194853, 1, "\u7295"], [194854, 1, "\u{24735}"], [194855, 1, "\u{24814}"], [194856, 1, "\u737A"], [194857, 1, "\u738B"], [194858, 1, "\u3EAC"], [194859, 1, "\u73A5"], [[194860, 194861], 1, "\u3EB8"], [194862, 1, "\u7447"], [194863, 1, "\u745C"], [194864, 1, "\u7471"], [194865, 1, "\u7485"], [194866, 1, "\u74CA"], [194867, 1, "\u3F1B"], [194868, 1, "\u7524"], [194869, 1, "\u{24C36}"], [194870, 1, "\u753E"], [194871, 1, "\u{24C92}"], [194872, 1, "\u7570"], [194873, 1, "\u{2219F}"], [194874, 1, "\u7610"], [194875, 1, "\u{24FA1}"], [194876, 1, "\u{24FB8}"], [194877, 1, "\u{25044}"], [194878, 1, "\u3FFC"], [194879, 1, "\u4008"], [194880, 1, "\u76F4"], [194881, 1, "\u{250F3}"], [194882, 1, "\u{250F2}"], [194883, 1, "\u{25119}"], [194884, 1, "\u{25133}"], [194885, 1, "\u771E"], [[194886, 194887], 1, "\u771F"], [194888, 1, "\u774A"], [194889, 1, "\u4039"], [194890, 1, "\u778B"], [194891, 1, "\u4046"], [194892, 1, "\u4096"], [194893, 1, "\u{2541D}"], [194894, 1, "\u784E"], [194895, 1, "\u788C"], [194896, 1, "\u78CC"], [194897, 1, "\u40E3"], [194898, 1, "\u{25626}"], [194899, 1, "\u7956"], [194900, 1, "\u{2569A}"], [194901, 1, "\u{256C5}"], [194902, 1, "\u798F"], [194903, 1, "\u79EB"], [194904, 1, "\u412F"], [194905, 1, "\u7A40"], [194906, 1, "\u7A4A"], [194907, 1, "\u7A4F"], [194908, 1, "\u{2597C}"], [[194909, 194910], 1, "\u{25AA7}"], [194911, 1, "\u7AEE"], [194912, 1, "\u4202"], [194913, 1, "\u{25BAB}"], [194914, 1, "\u7BC6"], [194915, 1, "\u7BC9"], [194916, 1, "\u4227"], [194917, 1, "\u{25C80}"], [194918, 1, "\u7CD2"], [194919, 1, "\u42A0"], [194920, 1, "\u7CE8"], [194921, 1, "\u7CE3"], [194922, 1, "\u7D00"], [194923, 1, "\u{25F86}"], [194924, 1, "\u7D63"], [194925, 1, "\u4301"], [194926, 1, "\u7DC7"], [194927, 1, "\u7E02"], [194928, 1, "\u7E45"], [194929, 1, "\u4334"], [194930, 1, "\u{26228}"], [194931, 1, "\u{26247}"], [194932, 1, "\u4359"], [194933, 1, "\u{262D9}"], [194934, 1, "\u7F7A"], [194935, 1, "\u{2633E}"], [194936, 1, "\u7F95"], [194937, 1, "\u7FFA"], [194938, 1, "\u8005"], [194939, 1, "\u{264DA}"], [194940, 1, "\u{26523}"], [194941, 1, "\u8060"], [194942, 1, "\u{265A8}"], [194943, 1, "\u8070"], [194944, 1, "\u{2335F}"], [194945, 1, "\u43D5"], [194946, 1, "\u80B2"], [194947, 1, "\u8103"], [194948, 1, "\u440B"], [194949, 1, "\u813E"], [194950, 1, "\u5AB5"], [194951, 1, "\u{267A7}"], [194952, 1, "\u{267B5}"], [194953, 1, "\u{23393}"], [194954, 1, "\u{2339C}"], [194955, 1, "\u8201"], [194956, 1, "\u8204"], [194957, 1, "\u8F9E"], [194958, 1, "\u446B"], [194959, 1, "\u8291"], [194960, 1, "\u828B"], [194961, 1, "\u829D"], [194962, 1, "\u52B3"], [194963, 1, "\u82B1"], [194964, 1, "\u82B3"], [194965, 1, "\u82BD"], [194966, 1, "\u82E6"], [194967, 1, "\u{26B3C}"], [194968, 1, "\u82E5"], [194969, 1, "\u831D"], [194970, 1, "\u8363"], [194971, 1, "\u83AD"], [194972, 1, "\u8323"], [194973, 1, "\u83BD"], [194974, 1, "\u83E7"], [194975, 1, "\u8457"], [194976, 1, "\u8353"], [194977, 1, "\u83CA"], [194978, 1, "\u83CC"], [194979, 1, "\u83DC"], [194980, 1, "\u{26C36}"], [194981, 1, "\u{26D6B}"], [194982, 1, "\u{26CD5}"], [194983, 1, "\u452B"], [194984, 1, "\u84F1"], [194985, 1, "\u84F3"], [194986, 1, "\u8516"], [194987, 1, "\u{273CA}"], [194988, 1, "\u8564"], [194989, 1, "\u{26F2C}"], [194990, 1, "\u455D"], [194991, 1, "\u4561"], [194992, 1, "\u{26FB1}"], [194993, 1, "\u{270D2}"], [194994, 1, "\u456B"], [194995, 1, "\u8650"], [194996, 1, "\u865C"], [194997, 1, "\u8667"], [194998, 1, "\u8669"], [194999, 1, "\u86A9"], [195e3, 1, "\u8688"], [195001, 1, "\u870E"], [195002, 1, "\u86E2"], [195003, 1, "\u8779"], [195004, 1, "\u8728"], [195005, 1, "\u876B"], [195006, 1, "\u8786"], [195007, 1, "\u45D7"], [195008, 1, "\u87E1"], [195009, 1, "\u8801"], [195010, 1, "\u45F9"], [195011, 1, "\u8860"], [195012, 1, "\u8863"], [195013, 1, "\u{27667}"], [195014, 1, "\u88D7"], [195015, 1, "\u88DE"], [195016, 1, "\u4635"], [195017, 1, "\u88FA"], [195018, 1, "\u34BB"], [195019, 1, "\u{278AE}"], [195020, 1, "\u{27966}"], [195021, 1, "\u46BE"], [195022, 1, "\u46C7"], [195023, 1, "\u8AA0"], [195024, 1, "\u8AED"], [195025, 1, "\u8B8A"], [195026, 1, "\u8C55"], [195027, 1, "\u{27CA8}"], [195028, 1, "\u8CAB"], [195029, 1, "\u8CC1"], [195030, 1, "\u8D1B"], [195031, 1, "\u8D77"], [195032, 1, "\u{27F2F}"], [195033, 1, "\u{20804}"], [195034, 1, "\u8DCB"], [195035, 1, "\u8DBC"], [195036, 1, "\u8DF0"], [195037, 1, "\u{208DE}"], [195038, 1, "\u8ED4"], [195039, 1, "\u8F38"], [195040, 1, "\u{285D2}"], [195041, 1, "\u{285ED}"], [195042, 1, "\u9094"], [195043, 1, "\u90F1"], [195044, 1, "\u9111"], [195045, 1, "\u{2872E}"], [195046, 1, "\u911B"], [195047, 1, "\u9238"], [195048, 1, "\u92D7"], [195049, 1, "\u92D8"], [195050, 1, "\u927C"], [195051, 1, "\u93F9"], [195052, 1, "\u9415"], [195053, 1, "\u{28BFA}"], [195054, 1, "\u958B"], [195055, 1, "\u4995"], [195056, 1, "\u95B7"], [195057, 1, "\u{28D77}"], [195058, 1, "\u49E6"], [195059, 1, "\u96C3"], [195060, 1, "\u5DB2"], [195061, 1, "\u9723"], [195062, 1, "\u{29145}"], [195063, 1, "\u{2921A}"], [195064, 1, "\u4A6E"], [195065, 1, "\u4A76"], [195066, 1, "\u97E0"], [195067, 1, "\u{2940A}"], [195068, 1, "\u4AB2"], [195069, 1, "\u{29496}"], [[195070, 195071], 1, "\u980B"], [195072, 1, "\u9829"], [195073, 1, "\u{295B6}"], [195074, 1, "\u98E2"], [195075, 1, "\u4B33"], [195076, 1, "\u9929"], [195077, 1, "\u99A7"], [195078, 1, "\u99C2"], [195079, 1, "\u99FE"], [195080, 1, "\u4BCE"], [195081, 1, "\u{29B30}"], [195082, 1, "\u9B12"], [195083, 1, "\u9C40"], [195084, 1, "\u9CFD"], [195085, 1, "\u4CCE"], [195086, 1, "\u4CED"], [195087, 1, "\u9D67"], [195088, 1, "\u{2A0CE}"], [195089, 1, "\u4CF8"], [195090, 1, "\u{2A105}"], [195091, 1, "\u{2A20E}"], [195092, 1, "\u{2A291}"], [195093, 1, "\u9EBB"], [195094, 1, "\u4D56"], [195095, 1, "\u9EF9"], [195096, 1, "\u9EFE"], [195097, 1, "\u9F05"], [195098, 1, "\u9F0F"], [195099, 1, "\u9F16"], [195100, 1, "\u9F3B"], [195101, 1, "\u{2A600}"], [[195102, 196605], 3], [[196606, 196607], 3], [[196608, 201546], 2], [[201547, 201551], 3], [[201552, 205743], 2], [[205744, 262141], 3], [[262142, 262143], 3], [[262144, 327677], 3], [[327678, 327679], 3], [[327680, 393213], 3], [[393214, 393215], 3], [[393216, 458749], 3], [[458750, 458751], 3], [[458752, 524285], 3], [[524286, 524287], 3], [[524288, 589821], 3], [[589822, 589823], 3], [[589824, 655357], 3], [[655358, 655359], 3], [[655360, 720893], 3], [[720894, 720895], 3], [[720896, 786429], 3], [[786430, 786431], 3], [[786432, 851965], 3], [[851966, 851967], 3], [[851968, 917501], 3], [[917502, 917503], 3], [917504, 3], [917505, 3], [[917506, 917535], 3], [[917536, 917631], 3], [[917632, 917759], 3], [[917760, 917999], 7], [[918e3, 983037], 3], [[983038, 983039], 3], [[983040, 1048573], 3], [[1048574, 1048575], 3], [[1048576, 1114109], 3], [[1114110, 1114111], 3]];
  }
});

// node_modules/tr46/lib/statusMapping.js
var require_statusMapping = __commonJS({
  "node_modules/tr46/lib/statusMapping.js"(exports2, module2) {
    "use strict";
    module2.exports.STATUS_MAPPING = {
      mapped: 1,
      valid: 2,
      disallowed: 3,
      deviation: 6,
      ignored: 7
    };
  }
});

// node_modules/tr46/index.js
var require_tr46 = __commonJS({
  "node_modules/tr46/index.js"(exports2, module2) {
    "use strict";
    var punycode = require_punycode();
    var regexes = require_regexes();
    var mappingTable = require_mappingTable();
    var { STATUS_MAPPING } = require_statusMapping();
    function containsNonASCII(str) {
      return /[^\x00-\x7F]/u.test(str);
    }
    function findStatus(val) {
      let start = 0;
      let end = mappingTable.length - 1;
      while (start <= end) {
        const mid = Math.floor((start + end) / 2);
        const target = mappingTable[mid];
        const min = Array.isArray(target[0]) ? target[0][0] : target[0];
        const max = Array.isArray(target[0]) ? target[0][1] : target[0];
        if (min <= val && max >= val) {
          return target.slice(1);
        } else if (min > val) {
          end = mid - 1;
        } else {
          start = mid + 1;
        }
      }
      return null;
    }
    function mapChars(domainName, { transitionalProcessing }) {
      let processed = "";
      for (const ch of domainName) {
        const [status, mapping] = findStatus(ch.codePointAt(0));
        switch (status) {
          case STATUS_MAPPING.disallowed:
            processed += ch;
            break;
          case STATUS_MAPPING.ignored:
            break;
          case STATUS_MAPPING.mapped:
            if (transitionalProcessing && ch === "\u1E9E") {
              processed += "ss";
            } else {
              processed += mapping;
            }
            break;
          case STATUS_MAPPING.deviation:
            if (transitionalProcessing) {
              processed += mapping;
            } else {
              processed += ch;
            }
            break;
          case STATUS_MAPPING.valid:
            processed += ch;
            break;
        }
      }
      return processed;
    }
    function validateLabel(label, {
      checkHyphens,
      checkBidi,
      checkJoiners,
      transitionalProcessing,
      useSTD3ASCIIRules,
      isBidi
    }) {
      if (label.length === 0) {
        return true;
      }
      if (label.normalize("NFC") !== label) {
        return false;
      }
      const codePoints = Array.from(label);
      if (checkHyphens) {
        if (codePoints[2] === "-" && codePoints[3] === "-" || (label.startsWith("-") || label.endsWith("-"))) {
          return false;
        }
      }
      if (!checkHyphens) {
        if (label.startsWith("xn--")) {
          return false;
        }
      }
      if (label.includes(".")) {
        return false;
      }
      if (regexes.combiningMarks.test(codePoints[0])) {
        return false;
      }
      for (const ch of codePoints) {
        const codePoint = ch.codePointAt(0);
        const [status] = findStatus(codePoint);
        if (transitionalProcessing) {
          if (status !== STATUS_MAPPING.valid) {
            return false;
          }
        } else if (status !== STATUS_MAPPING.valid && status !== STATUS_MAPPING.deviation) {
          return false;
        }
        if (useSTD3ASCIIRules && codePoint <= 127) {
          if (!/^(?:[a-z]|[0-9]|-)$/u.test(ch)) {
            return false;
          }
        }
      }
      if (checkJoiners) {
        let last = 0;
        for (const [i2, ch] of codePoints.entries()) {
          if (ch === "\u200C" || ch === "\u200D") {
            if (i2 > 0) {
              if (regexes.combiningClassVirama.test(codePoints[i2 - 1])) {
                continue;
              }
              if (ch === "\u200C") {
                const next = codePoints.indexOf("\u200C", i2 + 1);
                const test = next < 0 ? codePoints.slice(last) : codePoints.slice(last, next);
                if (regexes.validZWNJ.test(test.join(""))) {
                  last = i2 + 1;
                  continue;
                }
              }
            }
            return false;
          }
        }
      }
      if (checkBidi && isBidi) {
        let rtl;
        if (regexes.bidiS1LTR.test(codePoints[0])) {
          rtl = false;
        } else if (regexes.bidiS1RTL.test(codePoints[0])) {
          rtl = true;
        } else {
          return false;
        }
        if (rtl) {
          if (!regexes.bidiS2.test(label) || !regexes.bidiS3.test(label) || regexes.bidiS4EN.test(label) && regexes.bidiS4AN.test(label)) {
            return false;
          }
        } else if (!regexes.bidiS5.test(label) || !regexes.bidiS6.test(label)) {
          return false;
        }
      }
      return true;
    }
    function isBidiDomain(labels) {
      const domain2 = labels.map((label) => {
        if (label.startsWith("xn--")) {
          try {
            return punycode.decode(label.substring(4));
          } catch {
            return "";
          }
        }
        return label;
      }).join(".");
      return regexes.bidiDomain.test(domain2);
    }
    function processing(domainName, options) {
      let string4 = mapChars(domainName, options);
      string4 = string4.normalize("NFC");
      const labels = string4.split(".");
      const isBidi = isBidiDomain(labels);
      let error51 = false;
      for (const [i2, origLabel] of labels.entries()) {
        let label = origLabel;
        let transitionalProcessingForThisLabel = options.transitionalProcessing;
        if (label.startsWith("xn--")) {
          if (containsNonASCII(label)) {
            error51 = true;
            continue;
          }
          try {
            label = punycode.decode(label.substring(4));
          } catch {
            if (!options.ignoreInvalidPunycode) {
              error51 = true;
              continue;
            }
          }
          labels[i2] = label;
          if (label === "" || !containsNonASCII(label)) {
            error51 = true;
          }
          transitionalProcessingForThisLabel = false;
        }
        if (error51) {
          continue;
        }
        const validation = validateLabel(label, {
          ...options,
          transitionalProcessing: transitionalProcessingForThisLabel,
          isBidi
        });
        if (!validation) {
          error51 = true;
        }
      }
      return {
        string: labels.join("."),
        error: error51
      };
    }
    function toASCII(domainName, {
      checkHyphens = false,
      checkBidi = false,
      checkJoiners = false,
      useSTD3ASCIIRules = false,
      verifyDNSLength = false,
      transitionalProcessing = false,
      ignoreInvalidPunycode = false
    } = {}) {
      const result = processing(domainName, {
        checkHyphens,
        checkBidi,
        checkJoiners,
        useSTD3ASCIIRules,
        transitionalProcessing,
        ignoreInvalidPunycode
      });
      let labels = result.string.split(".");
      labels = labels.map((l) => {
        if (containsNonASCII(l)) {
          try {
            return `xn--${punycode.encode(l)}`;
          } catch {
            result.error = true;
          }
        }
        return l;
      });
      if (verifyDNSLength) {
        const total = labels.join(".").length;
        if (total > 253 || total === 0) {
          result.error = true;
        }
        for (let i2 = 0; i2 < labels.length; ++i2) {
          if (labels[i2].length > 63 || labels[i2].length === 0) {
            result.error = true;
            break;
          }
        }
      }
      if (result.error) {
        return null;
      }
      return labels.join(".");
    }
    function toUnicode(domainName, {
      checkHyphens = false,
      checkBidi = false,
      checkJoiners = false,
      useSTD3ASCIIRules = false,
      transitionalProcessing = false,
      ignoreInvalidPunycode = false
    } = {}) {
      const result = processing(domainName, {
        checkHyphens,
        checkBidi,
        checkJoiners,
        useSTD3ASCIIRules,
        transitionalProcessing,
        ignoreInvalidPunycode
      });
      return {
        domain: result.string,
        error: result.error
      };
    }
    module2.exports = {
      toASCII,
      toUnicode
    };
  }
});

// node_modules/whatwg-url/lib/infra.js
var require_infra = __commonJS({
  "node_modules/whatwg-url/lib/infra.js"(exports2, module2) {
    "use strict";
    function isASCIIDigit(c) {
      return c >= 48 && c <= 57;
    }
    function isASCIIAlpha(c) {
      return c >= 65 && c <= 90 || c >= 97 && c <= 122;
    }
    function isASCIIAlphanumeric(c) {
      return isASCIIAlpha(c) || isASCIIDigit(c);
    }
    function isASCIIHex(c) {
      return isASCIIDigit(c) || c >= 65 && c <= 70 || c >= 97 && c <= 102;
    }
    module2.exports = {
      isASCIIDigit,
      isASCIIAlpha,
      isASCIIAlphanumeric,
      isASCIIHex
    };
  }
});

// node_modules/whatwg-url/lib/encoding.js
var require_encoding = __commonJS({
  "node_modules/whatwg-url/lib/encoding.js"(exports2, module2) {
    "use strict";
    var utf8Encoder = new TextEncoder();
    var utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true });
    function utf8Encode(string4) {
      return utf8Encoder.encode(string4);
    }
    function utf8DecodeWithoutBOM(bytes) {
      return utf8Decoder.decode(bytes);
    }
    module2.exports = {
      utf8Encode,
      utf8DecodeWithoutBOM
    };
  }
});

// node_modules/whatwg-url/lib/percent-encoding.js
var require_percent_encoding = __commonJS({
  "node_modules/whatwg-url/lib/percent-encoding.js"(exports2, module2) {
    "use strict";
    var { isASCIIHex } = require_infra();
    var { utf8Encode } = require_encoding();
    function p(char) {
      return char.codePointAt(0);
    }
    function percentEncode(c) {
      let hex3 = c.toString(16).toUpperCase();
      if (hex3.length === 1) {
        hex3 = `0${hex3}`;
      }
      return `%${hex3}`;
    }
    function percentDecodeBytes(input) {
      const output = new Uint8Array(input.byteLength);
      let outputIndex = 0;
      for (let i2 = 0; i2 < input.byteLength; ++i2) {
        const byte = input[i2];
        if (byte !== 37) {
          output[outputIndex++] = byte;
        } else if (byte === 37 && (!isASCIIHex(input[i2 + 1]) || !isASCIIHex(input[i2 + 2]))) {
          output[outputIndex++] = byte;
        } else {
          const bytePoint = parseInt(String.fromCodePoint(input[i2 + 1], input[i2 + 2]), 16);
          output[outputIndex++] = bytePoint;
          i2 += 2;
        }
      }
      return output.slice(0, outputIndex);
    }
    function percentDecodeString(input) {
      const bytes = utf8Encode(input);
      return percentDecodeBytes(bytes);
    }
    function isC0ControlPercentEncode(c) {
      return c <= 31 || c > 126;
    }
    var extraFragmentPercentEncodeSet = /* @__PURE__ */ new Set([p(" "), p('"'), p("<"), p(">"), p("`")]);
    function isFragmentPercentEncode(c) {
      return isC0ControlPercentEncode(c) || extraFragmentPercentEncodeSet.has(c);
    }
    var extraQueryPercentEncodeSet = /* @__PURE__ */ new Set([p(" "), p('"'), p("#"), p("<"), p(">")]);
    function isQueryPercentEncode(c) {
      return isC0ControlPercentEncode(c) || extraQueryPercentEncodeSet.has(c);
    }
    function isSpecialQueryPercentEncode(c) {
      return isQueryPercentEncode(c) || c === p("'");
    }
    var extraPathPercentEncodeSet = /* @__PURE__ */ new Set([p("?"), p("`"), p("{"), p("}"), p("^")]);
    function isPathPercentEncode(c) {
      return isQueryPercentEncode(c) || extraPathPercentEncodeSet.has(c);
    }
    var extraUserinfoPercentEncodeSet = /* @__PURE__ */ new Set([p("/"), p(":"), p(";"), p("="), p("@"), p("["), p("\\"), p("]"), p("|")]);
    function isUserinfoPercentEncode(c) {
      return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c);
    }
    var extraComponentPercentEncodeSet = /* @__PURE__ */ new Set([p("$"), p("%"), p("&"), p("+"), p(",")]);
    function isComponentPercentEncode(c) {
      return isUserinfoPercentEncode(c) || extraComponentPercentEncodeSet.has(c);
    }
    var extraURLEncodedPercentEncodeSet = /* @__PURE__ */ new Set([p("!"), p("'"), p("("), p(")"), p("~")]);
    function isURLEncodedPercentEncode(c) {
      return isComponentPercentEncode(c) || extraURLEncodedPercentEncodeSet.has(c);
    }
    function utf8PercentEncodeCodePointInternal(codePoint, percentEncodePredicate) {
      const bytes = utf8Encode(codePoint);
      let output = "";
      for (const byte of bytes) {
        if (!percentEncodePredicate(byte)) {
          output += String.fromCharCode(byte);
        } else {
          output += percentEncode(byte);
        }
      }
      return output;
    }
    function utf8PercentEncodeCodePoint(codePoint, percentEncodePredicate) {
      return utf8PercentEncodeCodePointInternal(String.fromCodePoint(codePoint), percentEncodePredicate);
    }
    function utf8PercentEncodeString(input, percentEncodePredicate, spaceAsPlus = false) {
      let output = "";
      for (const codePoint of input) {
        if (spaceAsPlus && codePoint === " ") {
          output += "+";
        } else {
          output += utf8PercentEncodeCodePointInternal(codePoint, percentEncodePredicate);
        }
      }
      return output;
    }
    module2.exports = {
      isC0ControlPercentEncode,
      isFragmentPercentEncode,
      isQueryPercentEncode,
      isSpecialQueryPercentEncode,
      isPathPercentEncode,
      isUserinfoPercentEncode,
      isURLEncodedPercentEncode,
      percentDecodeString,
      percentDecodeBytes,
      utf8PercentEncodeString,
      utf8PercentEncodeCodePoint
    };
  }
});

// node_modules/whatwg-url/lib/url-state-machine.js
var require_url_state_machine = __commonJS({
  "node_modules/whatwg-url/lib/url-state-machine.js"(exports2, module2) {
    "use strict";
    var tr46 = require_tr46();
    var infra = require_infra();
    var { utf8DecodeWithoutBOM } = require_encoding();
    var {
      percentDecodeString,
      utf8PercentEncodeCodePoint,
      utf8PercentEncodeString,
      isC0ControlPercentEncode,
      isFragmentPercentEncode,
      isQueryPercentEncode,
      isSpecialQueryPercentEncode,
      isPathPercentEncode,
      isUserinfoPercentEncode
    } = require_percent_encoding();
    function p(char) {
      return char.codePointAt(0);
    }
    var specialSchemes = {
      ftp: 21,
      file: null,
      http: 80,
      https: 443,
      ws: 80,
      wss: 443
    };
    var failure = /* @__PURE__ */ Symbol("failure");
    function countSymbols(str) {
      return [...str].length;
    }
    function at(input, idx) {
      const c = input[idx];
      return isNaN(c) ? void 0 : String.fromCodePoint(c);
    }
    function isSingleDot(buffer) {
      return buffer === "." || buffer.toLowerCase() === "%2e";
    }
    function isDoubleDot(buffer) {
      buffer = buffer.toLowerCase();
      return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e";
    }
    function isWindowsDriveLetterCodePoints(cp1, cp2) {
      return infra.isASCIIAlpha(cp1) && (cp2 === p(":") || cp2 === p("|"));
    }
    function isWindowsDriveLetterString(string4) {
      return string4.length === 2 && infra.isASCIIAlpha(string4.codePointAt(0)) && (string4[1] === ":" || string4[1] === "|");
    }
    function isNormalizedWindowsDriveLetterString(string4) {
      return string4.length === 2 && infra.isASCIIAlpha(string4.codePointAt(0)) && string4[1] === ":";
    }
    function containsForbiddenHostCodePoint(string4) {
      return string4.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u) !== -1;
    }
    function containsForbiddenDomainCodePoint(string4) {
      return containsForbiddenHostCodePoint(string4) || string4.search(/[\u0000-\u001F]|%|\u007F/u) !== -1;
    }
    function isSpecialScheme(scheme) {
      return specialSchemes[scheme] !== void 0;
    }
    function isSpecial(url2) {
      return isSpecialScheme(url2.scheme);
    }
    function isNotSpecial(url2) {
      return !isSpecialScheme(url2.scheme);
    }
    function defaultPort(scheme) {
      return specialSchemes[scheme];
    }
    function parseIPv4Number(input) {
      if (input === "") {
        return failure;
      }
      let R = 10;
      if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") {
        input = input.substring(2);
        R = 16;
      } else if (input.length >= 2 && input.charAt(0) === "0") {
        input = input.substring(1);
        R = 8;
      }
      if (input === "") {
        return 0;
      }
      let regex = /[^0-7]/u;
      if (R === 10) {
        regex = /[^0-9]/u;
      }
      if (R === 16) {
        regex = /[^0-9A-Fa-f]/u;
      }
      if (regex.test(input)) {
        return failure;
      }
      return parseInt(input, R);
    }
    function parseIPv4(input) {
      const parts = input.split(".");
      if (parts[parts.length - 1] === "") {
        if (parts.length > 1) {
          parts.pop();
        }
      }
      if (parts.length > 4) {
        return failure;
      }
      const numbers = [];
      for (const part of parts) {
        const n = parseIPv4Number(part);
        if (n === failure) {
          return failure;
        }
        numbers.push(n);
      }
      for (let i2 = 0; i2 < numbers.length - 1; ++i2) {
        if (numbers[i2] > 255) {
          return failure;
        }
      }
      if (numbers[numbers.length - 1] >= 256 ** (5 - numbers.length)) {
        return failure;
      }
      let ipv43 = numbers.pop();
      let counter = 0;
      for (const n of numbers) {
        ipv43 += n * 256 ** (3 - counter);
        ++counter;
      }
      return ipv43;
    }
    function serializeIPv4(address) {
      let output = "";
      let n = address;
      for (let i2 = 1; i2 <= 4; ++i2) {
        output = String(n % 256) + output;
        if (i2 !== 4) {
          output = `.${output}`;
        }
        n = Math.floor(n / 256);
      }
      return output;
    }
    function parseIPv6(input) {
      const address = [0, 0, 0, 0, 0, 0, 0, 0];
      let pieceIndex = 0;
      let compress = null;
      let pointer = 0;
      input = Array.from(input, (c) => c.codePointAt(0));
      if (input[pointer] === p(":")) {
        if (input[pointer + 1] !== p(":")) {
          return failure;
        }
        pointer += 2;
        ++pieceIndex;
        compress = pieceIndex;
      }
      while (pointer < input.length) {
        if (pieceIndex === 8) {
          return failure;
        }
        if (input[pointer] === p(":")) {
          if (compress !== null) {
            return failure;
          }
          ++pointer;
          ++pieceIndex;
          compress = pieceIndex;
          continue;
        }
        let value = 0;
        let length = 0;
        while (length < 4 && infra.isASCIIHex(input[pointer])) {
          value = value * 16 + parseInt(at(input, pointer), 16);
          ++pointer;
          ++length;
        }
        if (input[pointer] === p(".")) {
          if (length === 0) {
            return failure;
          }
          pointer -= length;
          if (pieceIndex > 6) {
            return failure;
          }
          let numbersSeen = 0;
          while (input[pointer] !== void 0) {
            let ipv4Piece = null;
            if (numbersSeen > 0) {
              if (input[pointer] === p(".") && numbersSeen < 4) {
                ++pointer;
              } else {
                return failure;
              }
            }
            if (!infra.isASCIIDigit(input[pointer])) {
              return failure;
            }
            while (infra.isASCIIDigit(input[pointer])) {
              const number4 = parseInt(at(input, pointer));
              if (ipv4Piece === null) {
                ipv4Piece = number4;
              } else if (ipv4Piece === 0) {
                return failure;
              } else {
                ipv4Piece = ipv4Piece * 10 + number4;
              }
              if (ipv4Piece > 255) {
                return failure;
              }
              ++pointer;
            }
            address[pieceIndex] = address[pieceIndex] * 256 + ipv4Piece;
            ++numbersSeen;
            if (numbersSeen === 2 || numbersSeen === 4) {
              ++pieceIndex;
            }
          }
          if (numbersSeen !== 4) {
            return failure;
          }
          break;
        } else if (input[pointer] === p(":")) {
          ++pointer;
          if (input[pointer] === void 0) {
            return failure;
          }
        } else if (input[pointer] !== void 0) {
          return failure;
        }
        address[pieceIndex] = value;
        ++pieceIndex;
      }
      if (compress !== null) {
        let swaps = pieceIndex - compress;
        pieceIndex = 7;
        while (pieceIndex !== 0 && swaps > 0) {
          const temp = address[compress + swaps - 1];
          address[compress + swaps - 1] = address[pieceIndex];
          address[pieceIndex] = temp;
          --pieceIndex;
          --swaps;
        }
      } else if (compress === null && pieceIndex !== 8) {
        return failure;
      }
      return address;
    }
    function serializeIPv6(address) {
      let output = "";
      const compress = findTheIPv6AddressCompressedPieceIndex(address);
      let ignore0 = false;
      for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) {
        if (ignore0 && address[pieceIndex] === 0) {
          continue;
        } else if (ignore0) {
          ignore0 = false;
        }
        if (compress === pieceIndex) {
          const separator = pieceIndex === 0 ? "::" : ":";
          output += separator;
          ignore0 = true;
          continue;
        }
        output += address[pieceIndex].toString(16);
        if (pieceIndex !== 7) {
          output += ":";
        }
      }
      return output;
    }
    function parseHost(input, isOpaque = false) {
      if (input[0] === "[") {
        if (input[input.length - 1] !== "]") {
          return failure;
        }
        return parseIPv6(input.substring(1, input.length - 1));
      }
      if (isOpaque) {
        return parseOpaqueHost(input);
      }
      const domain2 = utf8DecodeWithoutBOM(percentDecodeString(input));
      const asciiDomain = domainToASCII(domain2);
      if (asciiDomain === failure) {
        return failure;
      }
      if (endsInANumber(asciiDomain)) {
        return parseIPv4(asciiDomain);
      }
      return asciiDomain;
    }
    function endsInANumber(input) {
      const parts = input.split(".");
      if (parts[parts.length - 1] === "") {
        if (parts.length === 1) {
          return false;
        }
        parts.pop();
      }
      const last = parts[parts.length - 1];
      if (parseIPv4Number(last) !== failure) {
        return true;
      }
      if (/^[0-9]+$/u.test(last)) {
        return true;
      }
      return false;
    }
    function parseOpaqueHost(input) {
      if (containsForbiddenHostCodePoint(input)) {
        return failure;
      }
      return utf8PercentEncodeString(input, isC0ControlPercentEncode);
    }
    function findTheIPv6AddressCompressedPieceIndex(address) {
      let longestIndex = null;
      let longestSize = 1;
      let foundIndex = null;
      let foundSize = 0;
      for (let pieceIndex = 0; pieceIndex < address.length; ++pieceIndex) {
        if (address[pieceIndex] !== 0) {
          if (foundSize > longestSize) {
            longestIndex = foundIndex;
            longestSize = foundSize;
          }
          foundIndex = null;
          foundSize = 0;
        } else {
          if (foundIndex === null) {
            foundIndex = pieceIndex;
          }
          ++foundSize;
        }
      }
      if (foundSize > longestSize) {
        return foundIndex;
      }
      return longestIndex;
    }
    function serializeHost(host) {
      if (typeof host === "number") {
        return serializeIPv4(host);
      }
      if (host instanceof Array) {
        return `[${serializeIPv6(host)}]`;
      }
      return host;
    }
    function domainToASCII(domain2, beStrict = false) {
      const result = tr46.toASCII(domain2, {
        checkHyphens: beStrict,
        checkBidi: true,
        checkJoiners: true,
        useSTD3ASCIIRules: beStrict,
        transitionalProcessing: false,
        verifyDNSLength: beStrict,
        ignoreInvalidPunycode: false
      });
      if (result === null) {
        return failure;
      }
      if (!beStrict) {
        if (result === "") {
          return failure;
        }
        if (containsForbiddenDomainCodePoint(result)) {
          return failure;
        }
      }
      return result;
    }
    function trimControlChars(string4) {
      let start = 0;
      let end = string4.length;
      for (; start < end; ++start) {
        if (string4.charCodeAt(start) > 32) {
          break;
        }
      }
      for (; end > start; --end) {
        if (string4.charCodeAt(end - 1) > 32) {
          break;
        }
      }
      return string4.substring(start, end);
    }
    function trimTabAndNewline(url2) {
      return url2.replace(/\u0009|\u000A|\u000D/ug, "");
    }
    function shortenPath(url2) {
      const { path } = url2;
      if (path.length === 0) {
        return;
      }
      if (url2.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) {
        return;
      }
      path.pop();
    }
    function includesCredentials(url2) {
      return url2.username !== "" || url2.password !== "";
    }
    function cannotHaveAUsernamePasswordPort(url2) {
      return url2.host === null || url2.host === "" || url2.scheme === "file";
    }
    function hasAnOpaquePath(url2) {
      return typeof url2.path === "string";
    }
    function isNormalizedWindowsDriveLetter(string4) {
      return /^[A-Za-z]:$/u.test(string4);
    }
    function URLStateMachine(input, base, encodingOverride, url2, stateOverride) {
      this.pointer = 0;
      this.input = input;
      this.base = base || null;
      this.encodingOverride = encodingOverride || "utf-8";
      this.stateOverride = stateOverride;
      this.url = url2;
      this.failure = false;
      this.parseError = false;
      if (!this.url) {
        this.url = {
          scheme: "",
          username: "",
          password: "",
          host: null,
          port: null,
          path: [],
          query: null,
          fragment: null
        };
        const res2 = trimControlChars(this.input);
        if (res2 !== this.input) {
          this.parseError = true;
        }
        this.input = res2;
      }
      const res = trimTabAndNewline(this.input);
      if (res !== this.input) {
        this.parseError = true;
      }
      this.input = res;
      this.state = stateOverride || "scheme start";
      this.buffer = "";
      this.atFlag = false;
      this.arrFlag = false;
      this.passwordTokenSeenFlag = false;
      this.input = Array.from(this.input, (c) => c.codePointAt(0));
      for (; this.pointer <= this.input.length; ++this.pointer) {
        const c = this.input[this.pointer];
        const cStr = isNaN(c) ? void 0 : String.fromCodePoint(c);
        const ret = this[`parse ${this.state}`](c, cStr);
        if (!ret) {
          break;
        } else if (ret === failure) {
          this.failure = true;
          break;
        }
      }
    }
    URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) {
      if (infra.isASCIIAlpha(c)) {
        this.buffer += cStr.toLowerCase();
        this.state = "scheme";
      } else if (!this.stateOverride) {
        this.state = "no scheme";
        --this.pointer;
      } else {
        this.parseError = true;
        return failure;
      }
      return true;
    };
    URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) {
      if (infra.isASCIIAlphanumeric(c) || c === p("+") || c === p("-") || c === p(".")) {
        this.buffer += cStr.toLowerCase();
      } else if (c === p(":")) {
        if (this.stateOverride) {
          if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) {
            return false;
          }
          if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) {
            return false;
          }
          if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") {
            return false;
          }
          if (this.url.scheme === "file" && this.url.host === "") {
            return false;
          }
        }
        this.url.scheme = this.buffer;
        if (this.stateOverride) {
          if (this.url.port === defaultPort(this.url.scheme)) {
            this.url.port = null;
          }
          return false;
        }
        this.buffer = "";
        if (this.url.scheme === "file") {
          if (this.input[this.pointer + 1] !== p("/") || this.input[this.pointer + 2] !== p("/")) {
            this.parseError = true;
          }
          this.state = "file";
        } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) {
          this.state = "special relative or authority";
        } else if (isSpecial(this.url)) {
          this.state = "special authority slashes";
        } else if (this.input[this.pointer + 1] === p("/")) {
          this.state = "path or authority";
          ++this.pointer;
        } else {
          this.url.path = "";
          this.state = "opaque path";
        }
      } else if (!this.stateOverride) {
        this.buffer = "";
        this.state = "no scheme";
        this.pointer = -1;
      } else {
        this.parseError = true;
        return failure;
      }
      return true;
    };
    URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) {
      if (this.base === null || hasAnOpaquePath(this.base) && c !== p("#")) {
        return failure;
      } else if (hasAnOpaquePath(this.base) && c === p("#")) {
        this.url.scheme = this.base.scheme;
        this.url.path = this.base.path;
        this.url.query = this.base.query;
        this.url.fragment = "";
        this.state = "fragment";
      } else if (this.base.scheme === "file") {
        this.state = "file";
        --this.pointer;
      } else {
        this.state = "relative";
        --this.pointer;
      }
      return true;
    };
    URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) {
      if (c === p("/") && this.input[this.pointer + 1] === p("/")) {
        this.state = "special authority ignore slashes";
        ++this.pointer;
      } else {
        this.parseError = true;
        this.state = "relative";
        --this.pointer;
      }
      return true;
    };
    URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) {
      if (c === p("/")) {
        this.state = "authority";
      } else {
        this.state = "path";
        --this.pointer;
      }
      return true;
    };
    URLStateMachine.prototype["parse relative"] = function parseRelative(c) {
      this.url.scheme = this.base.scheme;
      if (c === p("/")) {
        this.state = "relative slash";
      } else if (isSpecial(this.url) && c === p("\\")) {
        this.parseError = true;
        this.state = "relative slash";
      } else {
        this.url.username = this.base.username;
        this.url.password = this.base.password;
        this.url.host = this.base.host;
        this.url.port = this.base.port;
        this.url.path = this.base.path.slice();
        this.url.query = this.base.query;
        if (c === p("?")) {
          this.url.query = "";
          this.state = "query";
        } else if (c === p("#")) {
          this.url.fragment = "";
          this.state = "fragment";
        } else if (!isNaN(c)) {
          this.url.query = null;
          this.url.path.pop();
          this.state = "path";
          --this.pointer;
        }
      }
      return true;
    };
    URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) {
      if (isSpecial(this.url) && (c === p("/") || c === p("\\"))) {
        if (c === p("\\")) {
          this.parseError = true;
        }
        this.state = "special authority ignore slashes";
      } else if (c === p("/")) {
        this.state = "authority";
      } else {
        this.url.username = this.base.username;
        this.url.password = this.base.password;
        this.url.host = this.base.host;
        this.url.port = this.base.port;
        this.state = "path";
        --this.pointer;
      }
      return true;
    };
    URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) {
      if (c === p("/") && this.input[this.pointer + 1] === p("/")) {
        this.state = "special authority ignore slashes";
        ++this.pointer;
      } else {
        this.parseError = true;
        this.state = "special authority ignore slashes";
        --this.pointer;
      }
      return true;
    };
    URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) {
      if (c !== p("/") && c !== p("\\")) {
        this.state = "authority";
        --this.pointer;
      } else {
        this.parseError = true;
      }
      return true;
    };
    URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) {
      if (c === p("@")) {
        this.parseError = true;
        if (this.atFlag) {
          this.buffer = `%40${this.buffer}`;
        }
        this.atFlag = true;
        const len = countSymbols(this.buffer);
        for (let pointer = 0; pointer < len; ++pointer) {
          const codePoint = this.buffer.codePointAt(pointer);
          if (codePoint === p(":") && !this.passwordTokenSeenFlag) {
            this.passwordTokenSeenFlag = true;
            continue;
          }
          const encodedCodePoints = utf8PercentEncodeCodePoint(codePoint, isUserinfoPercentEncode);
          if (this.passwordTokenSeenFlag) {
            this.url.password += encodedCodePoints;
          } else {
            this.url.username += encodedCodePoints;
          }
        }
        this.buffer = "";
      } else if (isNaN(c) || c === p("/") || c === p("?") || c === p("#") || isSpecial(this.url) && c === p("\\")) {
        if (this.atFlag && this.buffer === "") {
          this.parseError = true;
          return failure;
        }
        this.pointer -= countSymbols(this.buffer) + 1;
        this.buffer = "";
        this.state = "host";
      } else {
        this.buffer += cStr;
      }
      return true;
    };
    URLStateMachine.prototype["parse hostname"] = URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) {
      if (this.stateOverride && this.url.scheme === "file") {
        --this.pointer;
        this.state = "file host";
      } else if (c === p(":") && !this.arrFlag) {
        if (this.buffer === "") {
          this.parseError = true;
          return failure;
        }
        if (this.stateOverride === "hostname") {
          return false;
        }
        const host = parseHost(this.buffer, isNotSpecial(this.url));
        if (host === failure) {
          return failure;
        }
        this.url.host = host;
        this.buffer = "";
        this.state = "port";
      } else if (isNaN(c) || c === p("/") || c === p("?") || c === p("#") || isSpecial(this.url) && c === p("\\")) {
        --this.pointer;
        if (isSpecial(this.url) && this.buffer === "") {
          this.parseError = true;
          return failure;
        } else if (this.stateOverride && this.buffer === "" && (includesCredentials(this.url) || this.url.port !== null)) {
          this.parseError = true;
          return false;
        }
        const host = parseHost(this.buffer, isNotSpecial(this.url));
        if (host === failure) {
          return failure;
        }
        this.url.host = host;
        this.buffer = "";
        this.state = "path start";
        if (this.stateOverride) {
          return false;
        }
      } else {
        if (c === p("[")) {
          this.arrFlag = true;
        } else if (c === p("]")) {
          this.arrFlag = false;
        }
        this.buffer += cStr;
      }
      return true;
    };
    URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) {
      if (infra.isASCIIDigit(c)) {
        this.buffer += cStr;
      } else if (isNaN(c) || c === p("/") || c === p("?") || c === p("#") || isSpecial(this.url) && c === p("\\") || this.stateOverride) {
        if (this.buffer !== "") {
          const port = parseInt(this.buffer);
          if (port > 2 ** 16 - 1) {
            this.parseError = true;
            return failure;
          }
          this.url.port = port === defaultPort(this.url.scheme) ? null : port;
          this.buffer = "";
        }
        if (this.stateOverride) {
          return false;
        }
        this.state = "path start";
        --this.pointer;
      } else {
        this.parseError = true;
        return failure;
      }
      return true;
    };
    var fileOtherwiseCodePoints = /* @__PURE__ */ new Set([p("/"), p("\\"), p("?"), p("#")]);
    function startsWithWindowsDriveLetter(input, pointer) {
      const length = input.length - pointer;
      return length >= 2 && isWindowsDriveLetterCodePoints(input[pointer], input[pointer + 1]) && (length === 2 || fileOtherwiseCodePoints.has(input[pointer + 2]));
    }
    URLStateMachine.prototype["parse file"] = function parseFile(c) {
      this.url.scheme = "file";
      this.url.host = "";
      if (c === p("/") || c === p("\\")) {
        if (c === p("\\")) {
          this.parseError = true;
        }
        this.state = "file slash";
      } else if (this.base !== null && this.base.scheme === "file") {
        this.url.host = this.base.host;
        this.url.path = this.base.path.slice();
        this.url.query = this.base.query;
        if (c === p("?")) {
          this.url.query = "";
          this.state = "query";
        } else if (c === p("#")) {
          this.url.fragment = "";
          this.state = "fragment";
        } else if (!isNaN(c)) {
          this.url.query = null;
          if (!startsWithWindowsDriveLetter(this.input, this.pointer)) {
            shortenPath(this.url);
          } else {
            this.parseError = true;
            this.url.path = [];
          }
          this.state = "path";
          --this.pointer;
        }
      } else {
        this.state = "path";
        --this.pointer;
      }
      return true;
    };
    URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) {
      if (c === p("/") || c === p("\\")) {
        if (c === p("\\")) {
          this.parseError = true;
        }
        this.state = "file host";
      } else {
        if (this.base !== null && this.base.scheme === "file") {
          if (!startsWithWindowsDriveLetter(this.input, this.pointer) && isNormalizedWindowsDriveLetterString(this.base.path[0])) {
            this.url.path.push(this.base.path[0]);
          }
          this.url.host = this.base.host;
        }
        this.state = "path";
        --this.pointer;
      }
      return true;
    };
    URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) {
      if (isNaN(c) || c === p("/") || c === p("\\") || c === p("?") || c === p("#")) {
        --this.pointer;
        if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) {
          this.parseError = true;
          this.state = "path";
        } else if (this.buffer === "") {
          this.url.host = "";
          if (this.stateOverride) {
            return false;
          }
          this.state = "path start";
        } else {
          let host = parseHost(this.buffer, isNotSpecial(this.url));
          if (host === failure) {
            return failure;
          }
          if (host === "localhost") {
            host = "";
          }
          this.url.host = host;
          if (this.stateOverride) {
            return false;
          }
          this.buffer = "";
          this.state = "path start";
        }
      } else {
        this.buffer += cStr;
      }
      return true;
    };
    URLStateMachine.prototype["parse path start"] = function parsePathStart(c) {
      if (isSpecial(this.url)) {
        if (c === p("\\")) {
          this.parseError = true;
        }
        this.state = "path";
        if (c !== p("/") && c !== p("\\")) {
          --this.pointer;
        }
      } else if (!this.stateOverride && c === p("?")) {
        this.url.query = "";
        this.state = "query";
      } else if (!this.stateOverride && c === p("#")) {
        this.url.fragment = "";
        this.state = "fragment";
      } else if (c !== void 0) {
        this.state = "path";
        if (c !== p("/")) {
          --this.pointer;
        }
      } else if (this.stateOverride && this.url.host === null) {
        this.url.path.push("");
      }
      return true;
    };
    URLStateMachine.prototype["parse path"] = function parsePath(c) {
      if (isNaN(c) || c === p("/") || isSpecial(this.url) && c === p("\\") || !this.stateOverride && (c === p("?") || c === p("#"))) {
        if (isSpecial(this.url) && c === p("\\")) {
          this.parseError = true;
        }
        if (isDoubleDot(this.buffer)) {
          shortenPath(this.url);
          if (c !== p("/") && !(isSpecial(this.url) && c === p("\\"))) {
            this.url.path.push("");
          }
        } else if (isSingleDot(this.buffer) && c !== p("/") && !(isSpecial(this.url) && c === p("\\"))) {
          this.url.path.push("");
        } else if (!isSingleDot(this.buffer)) {
          if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) {
            this.buffer = `${this.buffer[0]}:`;
          }
          this.url.path.push(this.buffer);
        }
        this.buffer = "";
        if (c === p("?")) {
          this.url.query = "";
          this.state = "query";
        }
        if (c === p("#")) {
          this.url.fragment = "";
          this.state = "fragment";
        }
      } else {
        if (c === p("%") && (!infra.isASCIIHex(this.input[this.pointer + 1]) || !infra.isASCIIHex(this.input[this.pointer + 2]))) {
          this.parseError = true;
        }
        this.buffer += utf8PercentEncodeCodePoint(c, isPathPercentEncode);
      }
      return true;
    };
    URLStateMachine.prototype["parse opaque path"] = function parseOpaquePath(c) {
      if (c === p("?")) {
        this.url.query = "";
        this.state = "query";
      } else if (c === p("#")) {
        this.url.fragment = "";
        this.state = "fragment";
      } else if (c === p(" ")) {
        const remaining = this.input[this.pointer + 1];
        if (remaining === p("?") || remaining === p("#")) {
          this.url.path += "%20";
        } else {
          this.url.path += " ";
        }
      } else {
        if (!isNaN(c) && c !== p("%")) {
          this.parseError = true;
        }
        if (c === p("%") && (!infra.isASCIIHex(this.input[this.pointer + 1]) || !infra.isASCIIHex(this.input[this.pointer + 2]))) {
          this.parseError = true;
        }
        if (!isNaN(c)) {
          this.url.path += utf8PercentEncodeCodePoint(c, isC0ControlPercentEncode);
        }
      }
      return true;
    };
    URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) {
      if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") {
        this.encodingOverride = "utf-8";
      }
      if (!this.stateOverride && c === p("#") || isNaN(c)) {
        const queryPercentEncodePredicate = isSpecial(this.url) ? isSpecialQueryPercentEncode : isQueryPercentEncode;
        this.url.query += utf8PercentEncodeString(this.buffer, queryPercentEncodePredicate);
        this.buffer = "";
        if (c === p("#")) {
          this.url.fragment = "";
          this.state = "fragment";
        }
      } else if (!isNaN(c)) {
        if (c === p("%") && (!infra.isASCIIHex(this.input[this.pointer + 1]) || !infra.isASCIIHex(this.input[this.pointer + 2]))) {
          this.parseError = true;
        }
        this.buffer += cStr;
      }
      return true;
    };
    URLStateMachine.prototype["parse fragment"] = function parseFragment(c) {
      if (!isNaN(c)) {
        if (c === p("%") && (!infra.isASCIIHex(this.input[this.pointer + 1]) || !infra.isASCIIHex(this.input[this.pointer + 2]))) {
          this.parseError = true;
        }
        this.url.fragment += utf8PercentEncodeCodePoint(c, isFragmentPercentEncode);
      }
      return true;
    };
    function serializeURL(url2, excludeFragment) {
      let output = `${url2.scheme}:`;
      if (url2.host !== null) {
        output += "//";
        if (url2.username !== "" || url2.password !== "") {
          output += url2.username;
          if (url2.password !== "") {
            output += `:${url2.password}`;
          }
          output += "@";
        }
        output += serializeHost(url2.host);
        if (url2.port !== null) {
          output += `:${url2.port}`;
        }
      }
      if (url2.host === null && !hasAnOpaquePath(url2) && url2.path.length > 1 && url2.path[0] === "") {
        output += "/.";
      }
      output += serializePath(url2);
      if (url2.query !== null) {
        output += `?${url2.query}`;
      }
      if (!excludeFragment && url2.fragment !== null) {
        output += `#${url2.fragment}`;
      }
      return output;
    }
    function serializeOrigin(tuple2) {
      let result = `${tuple2.scheme}://`;
      result += serializeHost(tuple2.host);
      if (tuple2.port !== null) {
        result += `:${tuple2.port}`;
      }
      return result;
    }
    function serializePath(url2) {
      if (hasAnOpaquePath(url2)) {
        return url2.path;
      }
      let output = "";
      for (const segment of url2.path) {
        output += `/${segment}`;
      }
      return output;
    }
    module2.exports.serializeURL = serializeURL;
    module2.exports.serializePath = serializePath;
    module2.exports.serializeURLOrigin = function(url2) {
      switch (url2.scheme) {
        case "blob": {
          const pathURL = module2.exports.parseURL(serializePath(url2));
          if (pathURL === null) {
            return "null";
          }
          if (pathURL.scheme !== "http" && pathURL.scheme !== "https") {
            return "null";
          }
          return module2.exports.serializeURLOrigin(pathURL);
        }
        case "ftp":
        case "http":
        case "https":
        case "ws":
        case "wss":
          return serializeOrigin({
            scheme: url2.scheme,
            host: url2.host,
            port: url2.port
          });
        case "file":
          return "null";
        default:
          return "null";
      }
    };
    module2.exports.basicURLParse = function(input, options) {
      if (options === void 0) {
        options = {};
      }
      const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride);
      if (usm.failure) {
        return null;
      }
      return usm.url;
    };
    module2.exports.setTheUsername = function(url2, username) {
      url2.username = utf8PercentEncodeString(username, isUserinfoPercentEncode);
    };
    module2.exports.setThePassword = function(url2, password) {
      url2.password = utf8PercentEncodeString(password, isUserinfoPercentEncode);
    };
    module2.exports.serializeHost = serializeHost;
    module2.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort;
    module2.exports.hasAnOpaquePath = hasAnOpaquePath;
    module2.exports.serializeInteger = function(integer2) {
      return String(integer2);
    };
    module2.exports.parseURL = function(input, options) {
      if (options === void 0) {
        options = {};
      }
      return module2.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride });
    };
  }
});

// node_modules/whatwg-url/lib/urlencoded.js
var require_urlencoded = __commonJS({
  "node_modules/whatwg-url/lib/urlencoded.js"(exports2, module2) {
    "use strict";
    var { utf8Encode, utf8DecodeWithoutBOM } = require_encoding();
    var { percentDecodeBytes, utf8PercentEncodeString, isURLEncodedPercentEncode } = require_percent_encoding();
    function p(char) {
      return char.codePointAt(0);
    }
    function parseUrlencoded(input) {
      const sequences = strictlySplitByteSequence(input, p("&"));
      const output = [];
      for (const bytes of sequences) {
        if (bytes.length === 0) {
          continue;
        }
        let name, value;
        const indexOfEqual = bytes.indexOf(p("="));
        if (indexOfEqual >= 0) {
          name = bytes.slice(0, indexOfEqual);
          value = bytes.slice(indexOfEqual + 1);
        } else {
          name = bytes;
          value = new Uint8Array(0);
        }
        name = replaceByteInByteSequence(name, 43, 32);
        value = replaceByteInByteSequence(value, 43, 32);
        const nameString = utf8DecodeWithoutBOM(percentDecodeBytes(name));
        const valueString = utf8DecodeWithoutBOM(percentDecodeBytes(value));
        output.push([nameString, valueString]);
      }
      return output;
    }
    function parseUrlencodedString(input) {
      return parseUrlencoded(utf8Encode(input));
    }
    function serializeUrlencoded(tuples) {
      let output = "";
      for (const [i2, tuple2] of tuples.entries()) {
        const name = utf8PercentEncodeString(tuple2[0], isURLEncodedPercentEncode, true);
        const value = utf8PercentEncodeString(tuple2[1], isURLEncodedPercentEncode, true);
        if (i2 !== 0) {
          output += "&";
        }
        output += `${name}=${value}`;
      }
      return output;
    }
    function strictlySplitByteSequence(buf, cp) {
      const list = [];
      let last = 0;
      let i2 = buf.indexOf(cp);
      while (i2 >= 0) {
        list.push(buf.slice(last, i2));
        last = i2 + 1;
        i2 = buf.indexOf(cp, last);
      }
      if (last !== buf.length) {
        list.push(buf.slice(last));
      }
      return list;
    }
    function replaceByteInByteSequence(buf, from, to) {
      let i2 = buf.indexOf(from);
      while (i2 >= 0) {
        buf[i2] = to;
        i2 = buf.indexOf(from, i2 + 1);
      }
      return buf;
    }
    module2.exports = {
      parseUrlencodedString,
      serializeUrlencoded
    };
  }
});

// node_modules/whatwg-url/lib/Function.js
var require_Function = __commonJS({
  "node_modules/whatwg-url/lib/Function.js"(exports2) {
    "use strict";
    var conversions = require_lib();
    var utils = require_utils2();
    exports2.convert = (globalObject, value, { context = "The provided value" } = {}) => {
      if (typeof value !== "function") {
        throw new globalObject.TypeError(context + " is not a function");
      }
      function invokeTheCallbackFunction(...args) {
        const thisArg = utils.tryWrapperForImpl(this);
        let callResult;
        for (let i2 = 0; i2 < args.length; i2++) {
          args[i2] = utils.tryWrapperForImpl(args[i2]);
        }
        callResult = Reflect.apply(value, thisArg, args);
        callResult = conversions["any"](callResult, { context, globals: globalObject });
        return callResult;
      }
      invokeTheCallbackFunction.construct = (...args) => {
        for (let i2 = 0; i2 < args.length; i2++) {
          args[i2] = utils.tryWrapperForImpl(args[i2]);
        }
        let callResult = Reflect.construct(value, args);
        callResult = conversions["any"](callResult, { context, globals: globalObject });
        return callResult;
      };
      invokeTheCallbackFunction[utils.wrapperSymbol] = value;
      invokeTheCallbackFunction.objectReference = value;
      return invokeTheCallbackFunction;
    };
  }
});

// node_modules/whatwg-url/lib/URLSearchParams-impl.js
var require_URLSearchParams_impl = __commonJS({
  "node_modules/whatwg-url/lib/URLSearchParams-impl.js"(exports2) {
    "use strict";
    var urlencoded = require_urlencoded();
    exports2.implementation = class URLSearchParamsImpl {
      constructor(globalObject, constructorArgs, { doNotStripQMark = false }) {
        let init = constructorArgs[0];
        this._list = [];
        this._url = null;
        if (!doNotStripQMark && typeof init === "string" && init[0] === "?") {
          init = init.slice(1);
        }
        if (Array.isArray(init)) {
          for (const pair of init) {
            if (pair.length !== 2) {
              throw new TypeError("Failed to construct 'URLSearchParams': parameter 1 sequence's element does not contain exactly two elements.");
            }
            this._list.push([pair[0], pair[1]]);
          }
        } else if (typeof init === "object" && Object.getPrototypeOf(init) === null) {
          for (const name of Object.keys(init)) {
            const value = init[name];
            this._list.push([name, value]);
          }
        } else {
          this._list = urlencoded.parseUrlencodedString(init);
        }
      }
      _updateSteps() {
        if (this._url !== null) {
          let serializedQuery = urlencoded.serializeUrlencoded(this._list);
          if (serializedQuery === "") {
            serializedQuery = null;
          }
          this._url._url.query = serializedQuery;
        }
      }
      get size() {
        return this._list.length;
      }
      append(name, value) {
        this._list.push([name, value]);
        this._updateSteps();
      }
      delete(name, value) {
        let i2 = 0;
        while (i2 < this._list.length) {
          if (this._list[i2][0] === name && (value === void 0 || this._list[i2][1] === value)) {
            this._list.splice(i2, 1);
          } else {
            i2++;
          }
        }
        this._updateSteps();
      }
      get(name) {
        for (const tuple2 of this._list) {
          if (tuple2[0] === name) {
            return tuple2[1];
          }
        }
        return null;
      }
      getAll(name) {
        const output = [];
        for (const tuple2 of this._list) {
          if (tuple2[0] === name) {
            output.push(tuple2[1]);
          }
        }
        return output;
      }
      has(name, value) {
        for (const tuple2 of this._list) {
          if (tuple2[0] === name && (value === void 0 || tuple2[1] === value)) {
            return true;
          }
        }
        return false;
      }
      set(name, value) {
        let found = false;
        let i2 = 0;
        while (i2 < this._list.length) {
          if (this._list[i2][0] === name) {
            if (found) {
              this._list.splice(i2, 1);
            } else {
              found = true;
              this._list[i2][1] = value;
              i2++;
            }
          } else {
            i2++;
          }
        }
        if (!found) {
          this._list.push([name, value]);
        }
        this._updateSteps();
      }
      sort() {
        this._list.sort((a, b) => {
          if (a[0] < b[0]) {
            return -1;
          }
          if (a[0] > b[0]) {
            return 1;
          }
          return 0;
        });
        this._updateSteps();
      }
      [Symbol.iterator]() {
        return this._list[Symbol.iterator]();
      }
      toString() {
        return urlencoded.serializeUrlencoded(this._list);
      }
    };
  }
});

// node_modules/whatwg-url/lib/URLSearchParams.js
var require_URLSearchParams = __commonJS({
  "node_modules/whatwg-url/lib/URLSearchParams.js"(exports2) {
    "use strict";
    var conversions = require_lib();
    var utils = require_utils2();
    var Function2 = require_Function();
    var newObjectInRealm = utils.newObjectInRealm;
    var implSymbol = utils.implSymbol;
    var ctorRegistrySymbol = utils.ctorRegistrySymbol;
    var interfaceName = "URLSearchParams";
    exports2.is = (value) => {
      return utils.isObject(value) && utils.hasOwn(value, implSymbol) && value[implSymbol] instanceof Impl.implementation;
    };
    exports2.isImpl = (value) => {
      return utils.isObject(value) && value instanceof Impl.implementation;
    };
    exports2.convert = (globalObject, value, { context = "The provided value" } = {}) => {
      if (exports2.is(value)) {
        return utils.implForWrapper(value);
      }
      throw new globalObject.TypeError(`${context} is not of type 'URLSearchParams'.`);
    };
    exports2.createDefaultIterator = (globalObject, target, kind) => {
      const ctorRegistry = globalObject[ctorRegistrySymbol];
      const iteratorPrototype = ctorRegistry["URLSearchParams Iterator"];
      const iterator = Object.create(iteratorPrototype);
      Object.defineProperty(iterator, utils.iterInternalSymbol, {
        value: { target, kind, index: 0 },
        configurable: true
      });
      return iterator;
    };
    function makeWrapper(globalObject, newTarget) {
      let proto;
      if (newTarget !== void 0) {
        proto = newTarget.prototype;
      }
      if (!utils.isObject(proto)) {
        proto = globalObject[ctorRegistrySymbol]["URLSearchParams"].prototype;
      }
      return Object.create(proto);
    }
    exports2.create = (globalObject, constructorArgs, privateData) => {
      const wrapper = makeWrapper(globalObject);
      return exports2.setup(wrapper, globalObject, constructorArgs, privateData);
    };
    exports2.createImpl = (globalObject, constructorArgs, privateData) => {
      const wrapper = exports2.create(globalObject, constructorArgs, privateData);
      return utils.implForWrapper(wrapper);
    };
    exports2._internalSetup = (wrapper, globalObject) => {
    };
    exports2.setup = (wrapper, globalObject, constructorArgs = [], privateData = {}) => {
      privateData.wrapper = wrapper;
      exports2._internalSetup(wrapper, globalObject);
      Object.defineProperty(wrapper, implSymbol, {
        value: new Impl.implementation(globalObject, constructorArgs, privateData),
        configurable: true
      });
      wrapper[implSymbol][utils.wrapperSymbol] = wrapper;
      if (Impl.init) {
        Impl.init(wrapper[implSymbol]);
      }
      return wrapper;
    };
    exports2.new = (globalObject, newTarget) => {
      const wrapper = makeWrapper(globalObject, newTarget);
      exports2._internalSetup(wrapper, globalObject);
      Object.defineProperty(wrapper, implSymbol, {
        value: Object.create(Impl.implementation.prototype),
        configurable: true
      });
      wrapper[implSymbol][utils.wrapperSymbol] = wrapper;
      if (Impl.init) {
        Impl.init(wrapper[implSymbol]);
      }
      return wrapper[implSymbol];
    };
    var exposed = /* @__PURE__ */ new Set(["Window", "Worker"]);
    exports2.install = (globalObject, globalNames) => {
      if (!globalNames.some((globalName) => exposed.has(globalName))) {
        return;
      }
      const ctorRegistry = utils.initCtorRegistry(globalObject);
      class URLSearchParams2 {
        constructor() {
          const args = [];
          {
            let curArg = arguments[0];
            if (curArg !== void 0) {
              if (utils.isObject(curArg)) {
                if (curArg[Symbol.iterator] !== void 0) {
                  if (!utils.isObject(curArg)) {
                    throw new globalObject.TypeError(
                      "Failed to construct 'URLSearchParams': parameter 1 sequence is not an iterable object."
                    );
                  } else {
                    const V = [];
                    const tmp = curArg;
                    for (let nextItem of tmp) {
                      if (!utils.isObject(nextItem)) {
                        throw new globalObject.TypeError(
                          "Failed to construct 'URLSearchParams': parameter 1 sequence's element is not an iterable object."
                        );
                      } else {
                        const V2 = [];
                        const tmp2 = nextItem;
                        for (let nextItem2 of tmp2) {
                          nextItem2 = conversions["USVString"](nextItem2, {
                            context: "Failed to construct 'URLSearchParams': parameter 1 sequence's element's element",
                            globals: globalObject
                          });
                          V2.push(nextItem2);
                        }
                        nextItem = V2;
                      }
                      V.push(nextItem);
                    }
                    curArg = V;
                  }
                } else {
                  if (!utils.isObject(curArg)) {
                    throw new globalObject.TypeError(
                      "Failed to construct 'URLSearchParams': parameter 1 record is not an object."
                    );
                  } else {
                    const result = /* @__PURE__ */ Object.create(null);
                    for (const key of Reflect.ownKeys(curArg)) {
                      const desc = Object.getOwnPropertyDescriptor(curArg, key);
                      if (desc && desc.enumerable) {
                        let typedKey = key;
                        typedKey = conversions["USVString"](typedKey, {
                          context: "Failed to construct 'URLSearchParams': parameter 1 record's key",
                          globals: globalObject
                        });
                        let typedValue = curArg[key];
                        typedValue = conversions["USVString"](typedValue, {
                          context: "Failed to construct 'URLSearchParams': parameter 1 record's value",
                          globals: globalObject
                        });
                        result[typedKey] = typedValue;
                      }
                    }
                    curArg = result;
                  }
                }
              } else {
                curArg = conversions["USVString"](curArg, {
                  context: "Failed to construct 'URLSearchParams': parameter 1",
                  globals: globalObject
                });
              }
            } else {
              curArg = "";
            }
            args.push(curArg);
          }
          return exports2.setup(Object.create(new.target.prototype), globalObject, args);
        }
        append(name, value) {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError(
              "'append' called on an object that is not a valid instance of URLSearchParams."
            );
          }
          if (arguments.length < 2) {
            throw new globalObject.TypeError(
              `Failed to execute 'append' on 'URLSearchParams': 2 arguments required, but only ${arguments.length} present.`
            );
          }
          const args = [];
          {
            let curArg = arguments[0];
            curArg = conversions["USVString"](curArg, {
              context: "Failed to execute 'append' on 'URLSearchParams': parameter 1",
              globals: globalObject
            });
            args.push(curArg);
          }
          {
            let curArg = arguments[1];
            curArg = conversions["USVString"](curArg, {
              context: "Failed to execute 'append' on 'URLSearchParams': parameter 2",
              globals: globalObject
            });
            args.push(curArg);
          }
          return utils.tryWrapperForImpl(esValue[implSymbol].append(...args));
        }
        delete(name) {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError(
              "'delete' called on an object that is not a valid instance of URLSearchParams."
            );
          }
          if (arguments.length < 1) {
            throw new globalObject.TypeError(
              `Failed to execute 'delete' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.`
            );
          }
          const args = [];
          {
            let curArg = arguments[0];
            curArg = conversions["USVString"](curArg, {
              context: "Failed to execute 'delete' on 'URLSearchParams': parameter 1",
              globals: globalObject
            });
            args.push(curArg);
          }
          {
            let curArg = arguments[1];
            if (curArg !== void 0) {
              curArg = conversions["USVString"](curArg, {
                context: "Failed to execute 'delete' on 'URLSearchParams': parameter 2",
                globals: globalObject
              });
            }
            args.push(curArg);
          }
          return utils.tryWrapperForImpl(esValue[implSymbol].delete(...args));
        }
        get(name) {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'get' called on an object that is not a valid instance of URLSearchParams.");
          }
          if (arguments.length < 1) {
            throw new globalObject.TypeError(
              `Failed to execute 'get' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.`
            );
          }
          const args = [];
          {
            let curArg = arguments[0];
            curArg = conversions["USVString"](curArg, {
              context: "Failed to execute 'get' on 'URLSearchParams': parameter 1",
              globals: globalObject
            });
            args.push(curArg);
          }
          return esValue[implSymbol].get(...args);
        }
        getAll(name) {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError(
              "'getAll' called on an object that is not a valid instance of URLSearchParams."
            );
          }
          if (arguments.length < 1) {
            throw new globalObject.TypeError(
              `Failed to execute 'getAll' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.`
            );
          }
          const args = [];
          {
            let curArg = arguments[0];
            curArg = conversions["USVString"](curArg, {
              context: "Failed to execute 'getAll' on 'URLSearchParams': parameter 1",
              globals: globalObject
            });
            args.push(curArg);
          }
          return utils.tryWrapperForImpl(esValue[implSymbol].getAll(...args));
        }
        has(name) {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'has' called on an object that is not a valid instance of URLSearchParams.");
          }
          if (arguments.length < 1) {
            throw new globalObject.TypeError(
              `Failed to execute 'has' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.`
            );
          }
          const args = [];
          {
            let curArg = arguments[0];
            curArg = conversions["USVString"](curArg, {
              context: "Failed to execute 'has' on 'URLSearchParams': parameter 1",
              globals: globalObject
            });
            args.push(curArg);
          }
          {
            let curArg = arguments[1];
            if (curArg !== void 0) {
              curArg = conversions["USVString"](curArg, {
                context: "Failed to execute 'has' on 'URLSearchParams': parameter 2",
                globals: globalObject
              });
            }
            args.push(curArg);
          }
          return esValue[implSymbol].has(...args);
        }
        set(name, value) {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'set' called on an object that is not a valid instance of URLSearchParams.");
          }
          if (arguments.length < 2) {
            throw new globalObject.TypeError(
              `Failed to execute 'set' on 'URLSearchParams': 2 arguments required, but only ${arguments.length} present.`
            );
          }
          const args = [];
          {
            let curArg = arguments[0];
            curArg = conversions["USVString"](curArg, {
              context: "Failed to execute 'set' on 'URLSearchParams': parameter 1",
              globals: globalObject
            });
            args.push(curArg);
          }
          {
            let curArg = arguments[1];
            curArg = conversions["USVString"](curArg, {
              context: "Failed to execute 'set' on 'URLSearchParams': parameter 2",
              globals: globalObject
            });
            args.push(curArg);
          }
          return utils.tryWrapperForImpl(esValue[implSymbol].set(...args));
        }
        sort() {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'sort' called on an object that is not a valid instance of URLSearchParams.");
          }
          return utils.tryWrapperForImpl(esValue[implSymbol].sort());
        }
        toString() {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError(
              "'toString' called on an object that is not a valid instance of URLSearchParams."
            );
          }
          return esValue[implSymbol].toString();
        }
        keys() {
          if (!exports2.is(this)) {
            throw new globalObject.TypeError("'keys' called on an object that is not a valid instance of URLSearchParams.");
          }
          return exports2.createDefaultIterator(globalObject, this, "key");
        }
        values() {
          if (!exports2.is(this)) {
            throw new globalObject.TypeError(
              "'values' called on an object that is not a valid instance of URLSearchParams."
            );
          }
          return exports2.createDefaultIterator(globalObject, this, "value");
        }
        entries() {
          if (!exports2.is(this)) {
            throw new globalObject.TypeError(
              "'entries' called on an object that is not a valid instance of URLSearchParams."
            );
          }
          return exports2.createDefaultIterator(globalObject, this, "key+value");
        }
        forEach(callback) {
          if (!exports2.is(this)) {
            throw new globalObject.TypeError(
              "'forEach' called on an object that is not a valid instance of URLSearchParams."
            );
          }
          if (arguments.length < 1) {
            throw new globalObject.TypeError(
              "Failed to execute 'forEach' on 'iterable': 1 argument required, but only 0 present."
            );
          }
          callback = Function2.convert(globalObject, callback, {
            context: "Failed to execute 'forEach' on 'iterable': The callback provided as parameter 1"
          });
          const thisArg = arguments[1];
          let pairs = Array.from(this[implSymbol]);
          let i2 = 0;
          while (i2 < pairs.length) {
            const [key, value] = pairs[i2].map(utils.tryWrapperForImpl);
            callback.call(thisArg, value, key, this);
            pairs = Array.from(this[implSymbol]);
            i2++;
          }
        }
        get size() {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError(
              "'get size' called on an object that is not a valid instance of URLSearchParams."
            );
          }
          return esValue[implSymbol]["size"];
        }
      }
      Object.defineProperties(URLSearchParams2.prototype, {
        append: { enumerable: true },
        delete: { enumerable: true },
        get: { enumerable: true },
        getAll: { enumerable: true },
        has: { enumerable: true },
        set: { enumerable: true },
        sort: { enumerable: true },
        toString: { enumerable: true },
        keys: { enumerable: true },
        values: { enumerable: true },
        entries: { enumerable: true },
        forEach: { enumerable: true },
        size: { enumerable: true },
        [Symbol.toStringTag]: { value: "URLSearchParams", configurable: true },
        [Symbol.iterator]: { value: URLSearchParams2.prototype.entries, configurable: true, writable: true }
      });
      ctorRegistry[interfaceName] = URLSearchParams2;
      ctorRegistry["URLSearchParams Iterator"] = Object.create(ctorRegistry["%IteratorPrototype%"], {
        [Symbol.toStringTag]: {
          configurable: true,
          value: "URLSearchParams Iterator"
        }
      });
      utils.define(ctorRegistry["URLSearchParams Iterator"], {
        next() {
          const internal = this && this[utils.iterInternalSymbol];
          if (!internal) {
            throw new globalObject.TypeError("next() called on a value that is not a URLSearchParams iterator object");
          }
          const { target, kind, index } = internal;
          const values = Array.from(target[implSymbol]);
          const len = values.length;
          if (index >= len) {
            return newObjectInRealm(globalObject, { value: void 0, done: true });
          }
          const pair = values[index];
          internal.index = index + 1;
          return newObjectInRealm(globalObject, utils.iteratorResult(pair.map(utils.tryWrapperForImpl), kind));
        }
      });
      Object.defineProperty(globalObject, interfaceName, {
        configurable: true,
        writable: true,
        value: URLSearchParams2
      });
    };
    var Impl = require_URLSearchParams_impl();
  }
});

// node_modules/whatwg-url/lib/URL-impl.js
var require_URL_impl = __commonJS({
  "node_modules/whatwg-url/lib/URL-impl.js"(exports2) {
    "use strict";
    var usm = require_url_state_machine();
    var urlencoded = require_urlencoded();
    var URLSearchParams2 = require_URLSearchParams();
    exports2.implementation = class URLImpl {
      // Unlike the spec, we duplicate some code between the constructor and canParse, because we want to give useful error
      // messages in the constructor that distinguish between the different causes of failure.
      constructor(globalObject, [url2, base]) {
        let parsedBase = null;
        if (base !== void 0) {
          parsedBase = usm.basicURLParse(base);
          if (parsedBase === null) {
            throw new TypeError(`Invalid base URL: ${base}`);
          }
        }
        const parsedURL = usm.basicURLParse(url2, { baseURL: parsedBase });
        if (parsedURL === null) {
          throw new TypeError(`Invalid URL: ${url2}`);
        }
        const query = parsedURL.query !== null ? parsedURL.query : "";
        this._url = parsedURL;
        this._query = URLSearchParams2.createImpl(globalObject, [query], { doNotStripQMark: true });
        this._query._url = this;
      }
      static parse(globalObject, input, base) {
        try {
          return new URLImpl(globalObject, [input, base]);
        } catch {
          return null;
        }
      }
      static canParse(url2, base) {
        let parsedBase = null;
        if (base !== void 0) {
          parsedBase = usm.basicURLParse(base);
          if (parsedBase === null) {
            return false;
          }
        }
        const parsedURL = usm.basicURLParse(url2, { baseURL: parsedBase });
        if (parsedURL === null) {
          return false;
        }
        return true;
      }
      get href() {
        return usm.serializeURL(this._url);
      }
      set href(v) {
        const parsedURL = usm.basicURLParse(v);
        if (parsedURL === null) {
          throw new TypeError(`Invalid URL: ${v}`);
        }
        this._url = parsedURL;
        this._query._list.splice(0);
        const { query } = parsedURL;
        if (query !== null) {
          this._query._list = urlencoded.parseUrlencodedString(query);
        }
      }
      get origin() {
        return usm.serializeURLOrigin(this._url);
      }
      get protocol() {
        return `${this._url.scheme}:`;
      }
      set protocol(v) {
        usm.basicURLParse(`${v}:`, { url: this._url, stateOverride: "scheme start" });
      }
      get username() {
        return this._url.username;
      }
      set username(v) {
        if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
          return;
        }
        usm.setTheUsername(this._url, v);
      }
      get password() {
        return this._url.password;
      }
      set password(v) {
        if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
          return;
        }
        usm.setThePassword(this._url, v);
      }
      get host() {
        const url2 = this._url;
        if (url2.host === null) {
          return "";
        }
        if (url2.port === null) {
          return usm.serializeHost(url2.host);
        }
        return `${usm.serializeHost(url2.host)}:${usm.serializeInteger(url2.port)}`;
      }
      set host(v) {
        if (usm.hasAnOpaquePath(this._url)) {
          return;
        }
        usm.basicURLParse(v, { url: this._url, stateOverride: "host" });
      }
      get hostname() {
        if (this._url.host === null) {
          return "";
        }
        return usm.serializeHost(this._url.host);
      }
      set hostname(v) {
        if (usm.hasAnOpaquePath(this._url)) {
          return;
        }
        usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" });
      }
      get port() {
        if (this._url.port === null) {
          return "";
        }
        return usm.serializeInteger(this._url.port);
      }
      set port(v) {
        if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
          return;
        }
        if (v === "") {
          this._url.port = null;
        } else {
          usm.basicURLParse(v, { url: this._url, stateOverride: "port" });
        }
      }
      get pathname() {
        return usm.serializePath(this._url);
      }
      set pathname(v) {
        if (usm.hasAnOpaquePath(this._url)) {
          return;
        }
        this._url.path = [];
        usm.basicURLParse(v, { url: this._url, stateOverride: "path start" });
      }
      get search() {
        if (this._url.query === null || this._url.query === "") {
          return "";
        }
        return `?${this._url.query}`;
      }
      set search(v) {
        const url2 = this._url;
        if (v === "") {
          url2.query = null;
          this._query._list = [];
          return;
        }
        const input = v[0] === "?" ? v.substring(1) : v;
        url2.query = "";
        usm.basicURLParse(input, { url: url2, stateOverride: "query" });
        this._query._list = urlencoded.parseUrlencodedString(input);
      }
      get searchParams() {
        return this._query;
      }
      get hash() {
        if (this._url.fragment === null || this._url.fragment === "") {
          return "";
        }
        return `#${this._url.fragment}`;
      }
      set hash(v) {
        if (v === "") {
          this._url.fragment = null;
          return;
        }
        const input = v[0] === "#" ? v.substring(1) : v;
        this._url.fragment = "";
        usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" });
      }
      toJSON() {
        return this.href;
      }
    };
  }
});

// node_modules/whatwg-url/lib/URL.js
var require_URL = __commonJS({
  "node_modules/whatwg-url/lib/URL.js"(exports2) {
    "use strict";
    var conversions = require_lib();
    var utils = require_utils2();
    var implSymbol = utils.implSymbol;
    var ctorRegistrySymbol = utils.ctorRegistrySymbol;
    var interfaceName = "URL";
    exports2.is = (value) => {
      return utils.isObject(value) && utils.hasOwn(value, implSymbol) && value[implSymbol] instanceof Impl.implementation;
    };
    exports2.isImpl = (value) => {
      return utils.isObject(value) && value instanceof Impl.implementation;
    };
    exports2.convert = (globalObject, value, { context = "The provided value" } = {}) => {
      if (exports2.is(value)) {
        return utils.implForWrapper(value);
      }
      throw new globalObject.TypeError(`${context} is not of type 'URL'.`);
    };
    function makeWrapper(globalObject, newTarget) {
      let proto;
      if (newTarget !== void 0) {
        proto = newTarget.prototype;
      }
      if (!utils.isObject(proto)) {
        proto = globalObject[ctorRegistrySymbol]["URL"].prototype;
      }
      return Object.create(proto);
    }
    exports2.create = (globalObject, constructorArgs, privateData) => {
      const wrapper = makeWrapper(globalObject);
      return exports2.setup(wrapper, globalObject, constructorArgs, privateData);
    };
    exports2.createImpl = (globalObject, constructorArgs, privateData) => {
      const wrapper = exports2.create(globalObject, constructorArgs, privateData);
      return utils.implForWrapper(wrapper);
    };
    exports2._internalSetup = (wrapper, globalObject) => {
    };
    exports2.setup = (wrapper, globalObject, constructorArgs = [], privateData = {}) => {
      privateData.wrapper = wrapper;
      exports2._internalSetup(wrapper, globalObject);
      Object.defineProperty(wrapper, implSymbol, {
        value: new Impl.implementation(globalObject, constructorArgs, privateData),
        configurable: true
      });
      wrapper[implSymbol][utils.wrapperSymbol] = wrapper;
      if (Impl.init) {
        Impl.init(wrapper[implSymbol]);
      }
      return wrapper;
    };
    exports2.new = (globalObject, newTarget) => {
      const wrapper = makeWrapper(globalObject, newTarget);
      exports2._internalSetup(wrapper, globalObject);
      Object.defineProperty(wrapper, implSymbol, {
        value: Object.create(Impl.implementation.prototype),
        configurable: true
      });
      wrapper[implSymbol][utils.wrapperSymbol] = wrapper;
      if (Impl.init) {
        Impl.init(wrapper[implSymbol]);
      }
      return wrapper[implSymbol];
    };
    var exposed = /* @__PURE__ */ new Set(["Window", "Worker"]);
    exports2.install = (globalObject, globalNames) => {
      if (!globalNames.some((globalName) => exposed.has(globalName))) {
        return;
      }
      const ctorRegistry = utils.initCtorRegistry(globalObject);
      class URL2 {
        constructor(url2) {
          if (arguments.length < 1) {
            throw new globalObject.TypeError(
              `Failed to construct 'URL': 1 argument required, but only ${arguments.length} present.`
            );
          }
          const args = [];
          {
            let curArg = arguments[0];
            curArg = conversions["USVString"](curArg, {
              context: "Failed to construct 'URL': parameter 1",
              globals: globalObject
            });
            args.push(curArg);
          }
          {
            let curArg = arguments[1];
            if (curArg !== void 0) {
              curArg = conversions["USVString"](curArg, {
                context: "Failed to construct 'URL': parameter 2",
                globals: globalObject
              });
            }
            args.push(curArg);
          }
          return exports2.setup(Object.create(new.target.prototype), globalObject, args);
        }
        toJSON() {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'toJSON' called on an object that is not a valid instance of URL.");
          }
          return esValue[implSymbol].toJSON();
        }
        get href() {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'get href' called on an object that is not a valid instance of URL.");
          }
          return esValue[implSymbol]["href"];
        }
        set href(V) {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'set href' called on an object that is not a valid instance of URL.");
          }
          V = conversions["USVString"](V, {
            context: "Failed to set the 'href' property on 'URL': The provided value",
            globals: globalObject
          });
          esValue[implSymbol]["href"] = V;
        }
        toString() {
          const esValue = this;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'toString' called on an object that is not a valid instance of URL.");
          }
          return esValue[implSymbol]["href"];
        }
        get origin() {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'get origin' called on an object that is not a valid instance of URL.");
          }
          return esValue[implSymbol]["origin"];
        }
        get protocol() {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'get protocol' called on an object that is not a valid instance of URL.");
          }
          return esValue[implSymbol]["protocol"];
        }
        set protocol(V) {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'set protocol' called on an object that is not a valid instance of URL.");
          }
          V = conversions["USVString"](V, {
            context: "Failed to set the 'protocol' property on 'URL': The provided value",
            globals: globalObject
          });
          esValue[implSymbol]["protocol"] = V;
        }
        get username() {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'get username' called on an object that is not a valid instance of URL.");
          }
          return esValue[implSymbol]["username"];
        }
        set username(V) {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'set username' called on an object that is not a valid instance of URL.");
          }
          V = conversions["USVString"](V, {
            context: "Failed to set the 'username' property on 'URL': The provided value",
            globals: globalObject
          });
          esValue[implSymbol]["username"] = V;
        }
        get password() {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'get password' called on an object that is not a valid instance of URL.");
          }
          return esValue[implSymbol]["password"];
        }
        set password(V) {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'set password' called on an object that is not a valid instance of URL.");
          }
          V = conversions["USVString"](V, {
            context: "Failed to set the 'password' property on 'URL': The provided value",
            globals: globalObject
          });
          esValue[implSymbol]["password"] = V;
        }
        get host() {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'get host' called on an object that is not a valid instance of URL.");
          }
          return esValue[implSymbol]["host"];
        }
        set host(V) {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'set host' called on an object that is not a valid instance of URL.");
          }
          V = conversions["USVString"](V, {
            context: "Failed to set the 'host' property on 'URL': The provided value",
            globals: globalObject
          });
          esValue[implSymbol]["host"] = V;
        }
        get hostname() {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'get hostname' called on an object that is not a valid instance of URL.");
          }
          return esValue[implSymbol]["hostname"];
        }
        set hostname(V) {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'set hostname' called on an object that is not a valid instance of URL.");
          }
          V = conversions["USVString"](V, {
            context: "Failed to set the 'hostname' property on 'URL': The provided value",
            globals: globalObject
          });
          esValue[implSymbol]["hostname"] = V;
        }
        get port() {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'get port' called on an object that is not a valid instance of URL.");
          }
          return esValue[implSymbol]["port"];
        }
        set port(V) {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'set port' called on an object that is not a valid instance of URL.");
          }
          V = conversions["USVString"](V, {
            context: "Failed to set the 'port' property on 'URL': The provided value",
            globals: globalObject
          });
          esValue[implSymbol]["port"] = V;
        }
        get pathname() {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'get pathname' called on an object that is not a valid instance of URL.");
          }
          return esValue[implSymbol]["pathname"];
        }
        set pathname(V) {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'set pathname' called on an object that is not a valid instance of URL.");
          }
          V = conversions["USVString"](V, {
            context: "Failed to set the 'pathname' property on 'URL': The provided value",
            globals: globalObject
          });
          esValue[implSymbol]["pathname"] = V;
        }
        get search() {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'get search' called on an object that is not a valid instance of URL.");
          }
          return esValue[implSymbol]["search"];
        }
        set search(V) {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'set search' called on an object that is not a valid instance of URL.");
          }
          V = conversions["USVString"](V, {
            context: "Failed to set the 'search' property on 'URL': The provided value",
            globals: globalObject
          });
          esValue[implSymbol]["search"] = V;
        }
        get searchParams() {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'get searchParams' called on an object that is not a valid instance of URL.");
          }
          return utils.getSameObject(this, "searchParams", () => {
            return utils.tryWrapperForImpl(esValue[implSymbol]["searchParams"]);
          });
        }
        get hash() {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'get hash' called on an object that is not a valid instance of URL.");
          }
          return esValue[implSymbol]["hash"];
        }
        set hash(V) {
          const esValue = this !== null && this !== void 0 ? this : globalObject;
          if (!exports2.is(esValue)) {
            throw new globalObject.TypeError("'set hash' called on an object that is not a valid instance of URL.");
          }
          V = conversions["USVString"](V, {
            context: "Failed to set the 'hash' property on 'URL': The provided value",
            globals: globalObject
          });
          esValue[implSymbol]["hash"] = V;
        }
        static parse(url2) {
          if (arguments.length < 1) {
            throw new globalObject.TypeError(
              `Failed to execute 'parse' on 'URL': 1 argument required, but only ${arguments.length} present.`
            );
          }
          const args = [];
          {
            let curArg = arguments[0];
            curArg = conversions["USVString"](curArg, {
              context: "Failed to execute 'parse' on 'URL': parameter 1",
              globals: globalObject
            });
            args.push(curArg);
          }
          {
            let curArg = arguments[1];
            if (curArg !== void 0) {
              curArg = conversions["USVString"](curArg, {
                context: "Failed to execute 'parse' on 'URL': parameter 2",
                globals: globalObject
              });
            }
            args.push(curArg);
          }
          return utils.tryWrapperForImpl(Impl.implementation.parse(globalObject, ...args));
        }
        static canParse(url2) {
          if (arguments.length < 1) {
            throw new globalObject.TypeError(
              `Failed to execute 'canParse' on 'URL': 1 argument required, but only ${arguments.length} present.`
            );
          }
          const args = [];
          {
            let curArg = arguments[0];
            curArg = conversions["USVString"](curArg, {
              context: "Failed to execute 'canParse' on 'URL': parameter 1",
              globals: globalObject
            });
            args.push(curArg);
          }
          {
            let curArg = arguments[1];
            if (curArg !== void 0) {
              curArg = conversions["USVString"](curArg, {
                context: "Failed to execute 'canParse' on 'URL': parameter 2",
                globals: globalObject
              });
            }
            args.push(curArg);
          }
          return Impl.implementation.canParse(...args);
        }
      }
      Object.defineProperties(URL2.prototype, {
        toJSON: { enumerable: true },
        href: { enumerable: true },
        toString: { enumerable: true },
        origin: { enumerable: true },
        protocol: { enumerable: true },
        username: { enumerable: true },
        password: { enumerable: true },
        host: { enumerable: true },
        hostname: { enumerable: true },
        port: { enumerable: true },
        pathname: { enumerable: true },
        search: { enumerable: true },
        searchParams: { enumerable: true },
        hash: { enumerable: true },
        [Symbol.toStringTag]: { value: "URL", configurable: true }
      });
      Object.defineProperties(URL2, { parse: { enumerable: true }, canParse: { enumerable: true } });
      ctorRegistry[interfaceName] = URL2;
      Object.defineProperty(globalObject, interfaceName, {
        configurable: true,
        writable: true,
        value: URL2
      });
      if (globalNames.includes("Window")) {
        Object.defineProperty(globalObject, "webkitURL", {
          configurable: true,
          writable: true,
          value: URL2
        });
      }
    };
    var Impl = require_URL_impl();
  }
});

// node_modules/whatwg-url/webidl2js-wrapper.js
var require_webidl2js_wrapper = __commonJS({
  "node_modules/whatwg-url/webidl2js-wrapper.js"(exports2) {
    "use strict";
    var URL2 = require_URL();
    var URLSearchParams2 = require_URLSearchParams();
    exports2.URL = URL2;
    exports2.URLSearchParams = URLSearchParams2;
  }
});

// node_modules/whatwg-url/index.js
var require_whatwg_url = __commonJS({
  "node_modules/whatwg-url/index.js"(exports2) {
    "use strict";
    var { URL: URL2, URLSearchParams: URLSearchParams2 } = require_webidl2js_wrapper();
    var urlStateMachine = require_url_state_machine();
    var percentEncoding = require_percent_encoding();
    var sharedGlobalObject = { Array, Object, Promise, String, TypeError };
    URL2.install(sharedGlobalObject, ["Window"]);
    URLSearchParams2.install(sharedGlobalObject, ["Window"]);
    exports2.URL = sharedGlobalObject.URL;
    exports2.URLSearchParams = sharedGlobalObject.URLSearchParams;
    exports2.parseURL = urlStateMachine.parseURL;
    exports2.basicURLParse = urlStateMachine.basicURLParse;
    exports2.serializeURL = urlStateMachine.serializeURL;
    exports2.serializePath = urlStateMachine.serializePath;
    exports2.serializeHost = urlStateMachine.serializeHost;
    exports2.serializeInteger = urlStateMachine.serializeInteger;
    exports2.serializeURLOrigin = urlStateMachine.serializeURLOrigin;
    exports2.setTheUsername = urlStateMachine.setTheUsername;
    exports2.setThePassword = urlStateMachine.setThePassword;
    exports2.cannotHaveAUsernamePasswordPort = urlStateMachine.cannotHaveAUsernamePasswordPort;
    exports2.hasAnOpaquePath = urlStateMachine.hasAnOpaquePath;
    exports2.percentDecodeString = percentEncoding.percentDecodeString;
    exports2.percentDecodeBytes = percentEncoding.percentDecodeBytes;
  }
});

// node_modules/mongodb-connection-string-url/lib/redact.js
var require_redact = __commonJS({
  "node_modules/mongodb-connection-string-url/lib/redact.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i2 = 0; i2 < k.length; i2++) if (k[i2] !== "default") __createBinding(result, mod, k[i2]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.redactValidConnectionString = redactValidConnectionString;
    exports2.redactConnectionString = redactConnectionString;
    var index_1 = __importStar(require_lib2());
    function redactValidConnectionString(inputUrl, options) {
      const url2 = inputUrl.clone();
      const replacementString = options?.replacementString ?? "_credentials_";
      const redactUsernames = options?.redactUsernames ?? true;
      if ((url2.username || url2.password) && redactUsernames) {
        url2.username = replacementString;
        url2.password = "";
      } else if (url2.password) {
        url2.password = replacementString;
      }
      if (url2.searchParams.has("authMechanismProperties")) {
        const props = new index_1.CommaAndColonSeparatedRecord(url2.searchParams.get("authMechanismProperties"));
        if (props.get("AWS_SESSION_TOKEN")) {
          props.set("AWS_SESSION_TOKEN", replacementString);
          url2.searchParams.set("authMechanismProperties", props.toString());
        }
      }
      if (url2.searchParams.has("tlsCertificateKeyFilePassword")) {
        url2.searchParams.set("tlsCertificateKeyFilePassword", replacementString);
      }
      if (url2.searchParams.has("proxyUsername") && redactUsernames) {
        url2.searchParams.set("proxyUsername", replacementString);
      }
      if (url2.searchParams.has("proxyPassword")) {
        url2.searchParams.set("proxyPassword", replacementString);
      }
      return url2;
    }
    function redactConnectionString(uri, options) {
      const replacementString = options?.replacementString ?? "<credentials>";
      const redactUsernames = options?.redactUsernames ?? true;
      let parsed;
      try {
        parsed = new index_1.default(uri);
      } catch {
      }
      if (parsed) {
        options = { ...options, replacementString: "___credentials___" };
        return parsed.redact(options).toString().replace(/___credentials___/g, replacementString);
      }
      const R = replacementString;
      const replacements = [
        (uri2) => uri2.replace(redactUsernames ? /(\/\/)(.*)(@)/g : /(\/\/[^@]*:)(.*)(@)/g, `$1${R}$3`),
        (uri2) => uri2.replace(/(AWS_SESSION_TOKEN(:|%3A))([^,&]+)/gi, `$1${R}`),
        (uri2) => uri2.replace(/(tlsCertificateKeyFilePassword=)([^&]+)/gi, `$1${R}`),
        (uri2) => redactUsernames ? uri2.replace(/(proxyUsername=)([^&]+)/gi, `$1${R}`) : uri2,
        (uri2) => uri2.replace(/(proxyPassword=)([^&]+)/gi, `$1${R}`)
      ];
      for (const replacer of replacements) {
        uri = replacer(uri);
      }
      return uri;
    }
  }
});

// node_modules/mongodb-connection-string-url/lib/index.js
var require_lib2 = __commonJS({
  "node_modules/mongodb-connection-string-url/lib/index.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CommaAndColonSeparatedRecord = exports2.ConnectionString = exports2.redactConnectionString = void 0;
    var whatwg_url_1 = require_whatwg_url();
    var redact_1 = require_redact();
    Object.defineProperty(exports2, "redactConnectionString", { enumerable: true, get: function() {
      return redact_1.redactConnectionString;
    } });
    var DUMMY_HOSTNAME = "__this_is_a_placeholder__";
    function connectionStringHasValidScheme(connectionString) {
      return connectionString.startsWith("mongodb://") || connectionString.startsWith("mongodb+srv://");
    }
    var HOSTS_REGEX = /^(?<protocol>[^/]+):\/\/(?:(?<username>[^:@]*)(?::(?<password>[^@]*))?@)?(?<hosts>(?!:)[^/?@]*)(?<rest>.*)/;
    var CaseInsensitiveMap = class extends Map {
      delete(name) {
        return super.delete(this._normalizeKey(name));
      }
      get(name) {
        return super.get(this._normalizeKey(name));
      }
      has(name) {
        return super.has(this._normalizeKey(name));
      }
      set(name, value) {
        return super.set(this._normalizeKey(name), value);
      }
      _normalizeKey(name) {
        name = `${name}`;
        for (const key of this.keys()) {
          if (key.toLowerCase() === name.toLowerCase()) {
            name = key;
            break;
          }
        }
        return name;
      }
    };
    function caseInsenstiveURLSearchParams(Ctor) {
      return class CaseInsenstiveURLSearchParams extends Ctor {
        append(name, value) {
          return super.append(this._normalizeKey(name), value);
        }
        delete(name) {
          return super.delete(this._normalizeKey(name));
        }
        get(name) {
          return super.get(this._normalizeKey(name));
        }
        getAll(name) {
          return super.getAll(this._normalizeKey(name));
        }
        has(name) {
          return super.has(this._normalizeKey(name));
        }
        set(name, value) {
          return super.set(this._normalizeKey(name), value);
        }
        keys() {
          return super.keys();
        }
        values() {
          return super.values();
        }
        entries() {
          return super.entries();
        }
        [Symbol.iterator]() {
          return super[Symbol.iterator]();
        }
        _normalizeKey(name) {
          return CaseInsensitiveMap.prototype._normalizeKey.call(this, name);
        }
      };
    }
    var URLWithoutHost = class extends whatwg_url_1.URL {
    };
    var MongoParseError = class extends Error {
      get name() {
        return "MongoParseError";
      }
    };
    var ConnectionString = class _ConnectionString extends URLWithoutHost {
      _hosts;
      constructor(uri, options = {}) {
        const { looseValidation } = options;
        if (!looseValidation && !connectionStringHasValidScheme(uri)) {
          throw new MongoParseError('Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"');
        }
        const match = uri.match(HOSTS_REGEX);
        if (!match) {
          throw new MongoParseError("Invalid connection string");
        }
        const { protocol, username, password, hosts, rest } = match.groups ?? {};
        if (!looseValidation) {
          if (!protocol || !hosts) {
            throw new MongoParseError("Protocol and host list are required in the uri");
          }
          try {
            decodeURIComponent(username ?? "");
            decodeURIComponent(password ?? "");
          } catch (err) {
            throw new MongoParseError(err.message);
          }
          const illegalCharacters = /[:/?#[\]@]/gi;
          if (username?.match(illegalCharacters)) {
            throw new MongoParseError(`Username contains unescaped characters ${username}`);
          }
          if (!username || !password) {
            const uriWithoutProtocol = uri.replace(`${protocol}://`, "");
            if (uriWithoutProtocol.startsWith("@") || uriWithoutProtocol.startsWith(":")) {
              throw new MongoParseError("URI contained empty userinfo section");
            }
          }
          if (password?.match(illegalCharacters)) {
            throw new MongoParseError("Password contains unescaped characters");
          }
          if (rest?.match(/^[^/?]*@/)) {
            throw new MongoParseError("Invalid connection string");
          }
        }
        let authString = "";
        if (typeof username === "string")
          authString += username;
        if (typeof password === "string")
          authString += `:${password}`;
        if (authString)
          authString += "@";
        try {
          super(`${protocol.toLowerCase()}://${authString}${DUMMY_HOSTNAME}${rest}`);
        } catch (err) {
          if (looseValidation) {
            new _ConnectionString(uri, {
              ...options,
              looseValidation: false
            });
          }
          if (typeof err.message === "string") {
            err.message = err.message.replace(DUMMY_HOSTNAME, hosts);
          }
          throw err;
        }
        this._hosts = hosts.split(",");
        if (!looseValidation) {
          if (this.isSRV && this.hosts.length !== 1) {
            throw new MongoParseError("mongodb+srv URI cannot have multiple service names");
          }
          if (this.isSRV && this.hosts.some((host) => host.includes(":"))) {
            throw new MongoParseError("mongodb+srv URI cannot have port number");
          }
        }
        if (!this.pathname) {
          this.pathname = "/";
        }
        Object.setPrototypeOf(this.searchParams, caseInsenstiveURLSearchParams(this.searchParams.constructor).prototype);
      }
      get host() {
        return DUMMY_HOSTNAME;
      }
      set host(_ignored) {
        throw new Error("No single host for connection string");
      }
      get hostname() {
        return DUMMY_HOSTNAME;
      }
      set hostname(_ignored) {
        throw new Error("No single host for connection string");
      }
      get port() {
        return "";
      }
      set port(_ignored) {
        throw new Error("No single host for connection string");
      }
      get href() {
        return this.toString();
      }
      set href(_ignored) {
        throw new Error("Cannot set href for connection strings");
      }
      get isSRV() {
        return this.protocol.includes("srv");
      }
      get hosts() {
        return this._hosts;
      }
      set hosts(list) {
        this._hosts = list;
      }
      toString() {
        return super.toString().replace(DUMMY_HOSTNAME, this.hosts.join(","));
      }
      clone() {
        return new _ConnectionString(this.toString(), {
          looseValidation: true
        });
      }
      redact(options) {
        return (0, redact_1.redactValidConnectionString)(this, options);
      }
      typedSearchParams() {
        return this.searchParams;
      }
      [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
        const { href, origin, protocol, username, password, hosts, pathname, search, searchParams, hash: hash2 } = this;
        return {
          href,
          origin,
          protocol,
          username,
          password,
          hosts,
          pathname,
          search,
          searchParams,
          hash: hash2
        };
      }
    };
    exports2.ConnectionString = ConnectionString;
    var CommaAndColonSeparatedRecord = class extends CaseInsensitiveMap {
      constructor(from) {
        super();
        for (const entry of (from ?? "").split(",")) {
          if (!entry)
            continue;
          const colonIndex = entry.indexOf(":");
          if (colonIndex === -1) {
            this.set(entry, "");
          } else {
            this.set(entry.slice(0, colonIndex), entry.slice(colonIndex + 1));
          }
        }
      }
      toString() {
        return [...this].map((entry) => entry.join(":")).join(",");
      }
    };
    exports2.CommaAndColonSeparatedRecord = CommaAndColonSeparatedRecord;
    exports2.default = ConnectionString;
  }
});

// node_modules/mongodb/lib/cmap/commands.js
var require_commands = __commonJS({
  "node_modules/mongodb/lib/cmap/commands.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OpCompressedRequest = exports2.OpMsgResponse = exports2.OpMsgRequest = exports2.DocumentSequence = exports2.OpReply = exports2.OpQueryRequest = void 0;
    var bson_1 = require_bson2();
    var error_1 = require_error();
    var compression_1 = require_compression();
    var constants_1 = require_constants();
    var _requestId = 0;
    var OPTS_TAILABLE_CURSOR = 2;
    var OPTS_SECONDARY = 4;
    var OPTS_OPLOG_REPLAY = 8;
    var OPTS_NO_CURSOR_TIMEOUT = 16;
    var OPTS_AWAIT_DATA = 32;
    var OPTS_EXHAUST = 64;
    var OPTS_PARTIAL = 128;
    var CURSOR_NOT_FOUND = 1;
    var QUERY_FAILURE = 2;
    var SHARD_CONFIG_STALE = 4;
    var AWAIT_CAPABLE = 8;
    var encodeUTF8Into = bson_1.ByteUtils.encodeUTF8Into;
    var OpQueryRequest = class _OpQueryRequest {
      constructor(databaseName, query, options) {
        this.moreToCome = false;
        const ns = `${databaseName}.$cmd`;
        if (typeof databaseName !== "string") {
          throw new error_1.MongoRuntimeError("Database name must be a string for a query");
        }
        if (query == null)
          throw new error_1.MongoRuntimeError("A query document must be specified for query");
        if (ns.indexOf("\0") !== -1) {
          throw new error_1.MongoRuntimeError("Namespace cannot contain a null character");
        }
        this.databaseName = databaseName;
        this.query = query;
        this.ns = ns;
        this.numberToSkip = options.numberToSkip || 0;
        this.numberToReturn = options.numberToReturn || 0;
        this.returnFieldSelector = options.returnFieldSelector || void 0;
        this.requestId = options.requestId ?? _OpQueryRequest.getRequestId();
        this.pre32Limit = options.pre32Limit;
        this.serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false;
        this.ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : false;
        this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16;
        this.checkKeys = typeof options.checkKeys === "boolean" ? options.checkKeys : false;
        this.batchSize = this.numberToReturn;
        this.tailable = false;
        this.secondaryOk = typeof options.secondaryOk === "boolean" ? options.secondaryOk : false;
        this.oplogReplay = false;
        this.noCursorTimeout = false;
        this.awaitData = false;
        this.exhaust = false;
        this.partial = false;
      }
      /** Assign next request Id. */
      incRequestId() {
        this.requestId = _requestId++;
      }
      /** Peek next request Id. */
      nextRequestId() {
        return _requestId + 1;
      }
      /** Increment then return next request Id. */
      static getRequestId() {
        return ++_requestId;
      }
      // Uses a single allocated buffer for the process, avoiding multiple memory allocations
      toBin() {
        const buffers = [];
        let projection = null;
        let flags = 0;
        if (this.tailable) {
          flags |= OPTS_TAILABLE_CURSOR;
        }
        if (this.secondaryOk) {
          flags |= OPTS_SECONDARY;
        }
        if (this.oplogReplay) {
          flags |= OPTS_OPLOG_REPLAY;
        }
        if (this.noCursorTimeout) {
          flags |= OPTS_NO_CURSOR_TIMEOUT;
        }
        if (this.awaitData) {
          flags |= OPTS_AWAIT_DATA;
        }
        if (this.exhaust) {
          flags |= OPTS_EXHAUST;
        }
        if (this.partial) {
          flags |= OPTS_PARTIAL;
        }
        if (this.batchSize !== this.numberToReturn)
          this.numberToReturn = this.batchSize;
        const header = bson_1.ByteUtils.allocate(
          4 * 4 + // Header
          4 + // Flags
          bson_1.ByteUtils.utf8ByteLength(this.ns) + 1 + // namespace
          4 + // numberToSkip
          4
          // numberToReturn
        );
        buffers.push(header);
        const query = bson_1.BSON.serialize(this.query, {
          checkKeys: this.checkKeys,
          serializeFunctions: this.serializeFunctions,
          ignoreUndefined: this.ignoreUndefined
        });
        buffers.push(query);
        if (this.returnFieldSelector && Object.keys(this.returnFieldSelector).length > 0) {
          projection = bson_1.BSON.serialize(this.returnFieldSelector, {
            checkKeys: this.checkKeys,
            serializeFunctions: this.serializeFunctions,
            ignoreUndefined: this.ignoreUndefined
          });
          buffers.push(projection);
        }
        const totalLength = header.length + query.length + (projection ? projection.length : 0);
        let index = 4;
        header[3] = totalLength >> 24 & 255;
        header[2] = totalLength >> 16 & 255;
        header[1] = totalLength >> 8 & 255;
        header[0] = totalLength & 255;
        header[index + 3] = this.requestId >> 24 & 255;
        header[index + 2] = this.requestId >> 16 & 255;
        header[index + 1] = this.requestId >> 8 & 255;
        header[index] = this.requestId & 255;
        index = index + 4;
        header[index + 3] = 0 >> 24 & 255;
        header[index + 2] = 0 >> 16 & 255;
        header[index + 1] = 0 >> 8 & 255;
        header[index] = 0 & 255;
        index = index + 4;
        header[index + 3] = constants_1.OP_QUERY >> 24 & 255;
        header[index + 2] = constants_1.OP_QUERY >> 16 & 255;
        header[index + 1] = constants_1.OP_QUERY >> 8 & 255;
        header[index] = constants_1.OP_QUERY & 255;
        index = index + 4;
        header[index + 3] = flags >> 24 & 255;
        header[index + 2] = flags >> 16 & 255;
        header[index + 1] = flags >> 8 & 255;
        header[index] = flags & 255;
        index = index + 4;
        index = index + encodeUTF8Into(header, this.ns, index) + 1;
        header[index - 1] = 0;
        header[index + 3] = this.numberToSkip >> 24 & 255;
        header[index + 2] = this.numberToSkip >> 16 & 255;
        header[index + 1] = this.numberToSkip >> 8 & 255;
        header[index] = this.numberToSkip & 255;
        index = index + 4;
        header[index + 3] = this.numberToReturn >> 24 & 255;
        header[index + 2] = this.numberToReturn >> 16 & 255;
        header[index + 1] = this.numberToReturn >> 8 & 255;
        header[index] = this.numberToReturn & 255;
        index = index + 4;
        return buffers;
      }
    };
    exports2.OpQueryRequest = OpQueryRequest;
    var OpReply = class {
      constructor(message, msgHeader, msgBody, opts) {
        this.index = 0;
        this.sections = [];
        this.moreToCome = false;
        this.parsed = false;
        this.raw = message;
        this.data = msgBody;
        this.opts = opts ?? {
          useBigInt64: false,
          promoteLongs: true,
          promoteValues: true,
          promoteBuffers: false,
          bsonRegExp: false
        };
        this.length = msgHeader.length;
        this.requestId = msgHeader.requestId;
        this.responseTo = msgHeader.responseTo;
        this.opCode = msgHeader.opCode;
        this.fromCompressed = msgHeader.fromCompressed;
        this.useBigInt64 = typeof this.opts.useBigInt64 === "boolean" ? this.opts.useBigInt64 : false;
        this.promoteLongs = typeof this.opts.promoteLongs === "boolean" ? this.opts.promoteLongs : true;
        this.promoteValues = typeof this.opts.promoteValues === "boolean" ? this.opts.promoteValues : true;
        this.promoteBuffers = typeof this.opts.promoteBuffers === "boolean" ? this.opts.promoteBuffers : false;
        this.bsonRegExp = typeof this.opts.bsonRegExp === "boolean" ? this.opts.bsonRegExp : false;
      }
      isParsed() {
        return this.parsed;
      }
      parse() {
        if (this.parsed)
          return this.sections[0];
        this.index = 20;
        this.responseFlags = (0, bson_1.readInt32LE)(this.data, 0);
        this.cursorId = new bson_1.BSON.Long((0, bson_1.readInt32LE)(this.data, 4), (0, bson_1.readInt32LE)(this.data, 8));
        this.startingFrom = (0, bson_1.readInt32LE)(this.data, 12);
        this.numberReturned = (0, bson_1.readInt32LE)(this.data, 16);
        if (this.numberReturned < 0 || this.numberReturned > 2 ** 32 - 1) {
          throw new RangeError(`OP_REPLY numberReturned is an invalid array length ${this.numberReturned}`);
        }
        this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0;
        this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0;
        this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0;
        this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0;
        for (let i2 = 0; i2 < this.numberReturned; i2++) {
          const bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24;
          const section = this.data.subarray(this.index, this.index + bsonSize);
          this.sections.push(section);
          this.index = this.index + bsonSize;
        }
        this.parsed = true;
        return this.sections[0];
      }
    };
    exports2.OpReply = OpReply;
    var OPTS_CHECKSUM_PRESENT = 1;
    var OPTS_MORE_TO_COME = 2;
    var OPTS_EXHAUST_ALLOWED = 1 << 16;
    var DocumentSequence = class {
      /**
       * Create a new document sequence for the provided field.
       * @param field - The field it will replace.
       */
      constructor(field, documents) {
        this.field = field;
        this.documents = [];
        this.chunks = [];
        this.serializedDocumentsLength = 0;
        const buffer = bson_1.ByteUtils.allocateUnsafe(1 + 4 + this.field.length + 1);
        buffer[0] = 1;
        encodeUTF8Into(buffer, `${this.field}\0`, 5);
        this.chunks.push(buffer);
        this.header = buffer;
        if (documents) {
          for (const doc of documents) {
            this.push(doc, bson_1.BSON.serialize(doc));
          }
        }
      }
      /**
       * Push a document to the document sequence. Will serialize the document
       * as well and return the current serialized length of all documents.
       * @param document - The document to add.
       * @param buffer - The serialized document in raw BSON.
       * @returns The new total document sequence length.
       */
      push(document2, buffer) {
        this.serializedDocumentsLength += buffer.length;
        this.documents.push(document2);
        this.chunks.push(buffer);
        if (this.header) {
          bson_1.NumberUtils.setInt32LE(this.header, 1, 4 + this.field.length + 1 + this.serializedDocumentsLength);
        }
        return this.serializedDocumentsLength + this.header.length;
      }
      /**
       * Get the fully serialized bytes for the document sequence section.
       * @returns The section bytes.
       */
      toBin() {
        return bson_1.ByteUtils.concat(this.chunks);
      }
    };
    exports2.DocumentSequence = DocumentSequence;
    var OpMsgRequest = class _OpMsgRequest {
      constructor(databaseName, command, options) {
        if (command == null)
          throw new error_1.MongoInvalidArgumentError("Query document must be specified for query");
        this.databaseName = databaseName;
        this.command = command;
        this.command.$db = databaseName;
        this.options = options ?? {};
        this.requestId = options.requestId ? options.requestId : _OpMsgRequest.getRequestId();
        this.serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false;
        this.ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : false;
        this.checkKeys = typeof options.checkKeys === "boolean" ? options.checkKeys : false;
        this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16;
        this.checksumPresent = false;
        this.moreToCome = options.moreToCome ?? command.writeConcern?.w === 0;
        this.exhaustAllowed = typeof options.exhaustAllowed === "boolean" ? options.exhaustAllowed : false;
      }
      toBin() {
        const buffers = [];
        let flags = 0;
        if (this.checksumPresent) {
          flags |= OPTS_CHECKSUM_PRESENT;
        }
        if (this.moreToCome) {
          flags |= OPTS_MORE_TO_COME;
        }
        if (this.exhaustAllowed) {
          flags |= OPTS_EXHAUST_ALLOWED;
        }
        const header = bson_1.ByteUtils.allocate(
          4 * 4 + // Header
          4
          // Flags
        );
        buffers.push(header);
        let totalLength = header.length;
        const command = this.command;
        totalLength += this.makeSections(buffers, command);
        bson_1.NumberUtils.setInt32LE(header, 0, totalLength);
        bson_1.NumberUtils.setInt32LE(header, 4, this.requestId);
        bson_1.NumberUtils.setInt32LE(header, 8, 0);
        bson_1.NumberUtils.setInt32LE(header, 12, constants_1.OP_MSG);
        (0, bson_1.setUint32LE)(header, 16, flags);
        return buffers;
      }
      /**
       * Add the sections to the OP_MSG request's buffers and returns the length.
       */
      makeSections(buffers, document2) {
        const sequencesBuffer = this.extractDocumentSequences(document2);
        const payloadTypeBuffer = bson_1.ByteUtils.allocateUnsafe(1);
        payloadTypeBuffer[0] = 0;
        const documentBuffer = this.serializeBson(document2);
        buffers.push(payloadTypeBuffer);
        buffers.push(documentBuffer);
        buffers.push(sequencesBuffer);
        return payloadTypeBuffer.length + documentBuffer.length + sequencesBuffer.length;
      }
      /**
       * Extracts the document sequences from the command document and returns
       * a buffer to be added as multiple sections after the initial type 0
       * section in the message.
       */
      extractDocumentSequences(document2) {
        const chunks = [];
        for (const [key, value] of Object.entries(document2)) {
          if (value instanceof DocumentSequence) {
            chunks.push(value.toBin());
            delete document2[key];
          }
        }
        if (chunks.length > 0) {
          return bson_1.ByteUtils.concat(chunks);
        }
        return bson_1.ByteUtils.allocate(0);
      }
      serializeBson(document2) {
        return bson_1.BSON.serialize(document2, {
          checkKeys: this.checkKeys,
          serializeFunctions: this.serializeFunctions,
          ignoreUndefined: this.ignoreUndefined
        });
      }
      static getRequestId() {
        _requestId = _requestId + 1 & 2147483647;
        return _requestId;
      }
    };
    exports2.OpMsgRequest = OpMsgRequest;
    var OpMsgResponse = class {
      constructor(message, msgHeader, msgBody, opts) {
        this.index = 0;
        this.sections = [];
        this.parsed = false;
        this.raw = message;
        this.data = msgBody;
        this.opts = opts ?? {
          useBigInt64: false,
          promoteLongs: true,
          promoteValues: true,
          promoteBuffers: false,
          bsonRegExp: false
        };
        this.length = msgHeader.length;
        this.requestId = msgHeader.requestId;
        this.responseTo = msgHeader.responseTo;
        this.opCode = msgHeader.opCode;
        this.fromCompressed = msgHeader.fromCompressed;
        this.responseFlags = (0, bson_1.readInt32LE)(msgBody, 0);
        this.checksumPresent = (this.responseFlags & OPTS_CHECKSUM_PRESENT) !== 0;
        this.moreToCome = (this.responseFlags & OPTS_MORE_TO_COME) !== 0;
        this.exhaustAllowed = (this.responseFlags & OPTS_EXHAUST_ALLOWED) !== 0;
        this.useBigInt64 = typeof this.opts.useBigInt64 === "boolean" ? this.opts.useBigInt64 : false;
        this.promoteLongs = typeof this.opts.promoteLongs === "boolean" ? this.opts.promoteLongs : true;
        this.promoteValues = typeof this.opts.promoteValues === "boolean" ? this.opts.promoteValues : true;
        this.promoteBuffers = typeof this.opts.promoteBuffers === "boolean" ? this.opts.promoteBuffers : false;
        this.bsonRegExp = typeof this.opts.bsonRegExp === "boolean" ? this.opts.bsonRegExp : false;
      }
      isParsed() {
        return this.parsed;
      }
      parse() {
        if (this.parsed)
          return this.sections[0];
        this.index = 4;
        while (this.index < this.data.length) {
          const payloadType = this.data[this.index++];
          if (payloadType === 0) {
            const bsonSize = (0, bson_1.readInt32LE)(this.data, this.index);
            const bin = this.data.subarray(this.index, this.index + bsonSize);
            this.sections.push(bin);
            this.index += bsonSize;
          } else if (payloadType === 1) {
            throw new error_1.MongoRuntimeError("OP_MSG Payload Type 1 detected unsupported protocol");
          }
        }
        this.parsed = true;
        return this.sections[0];
      }
    };
    exports2.OpMsgResponse = OpMsgResponse;
    var MESSAGE_HEADER_SIZE = 16;
    var COMPRESSION_DETAILS_SIZE = 9;
    var OpCompressedRequest = class {
      constructor(command, options) {
        this.command = command;
        this.options = {
          zlibCompressionLevel: options.zlibCompressionLevel,
          agreedCompressor: options.agreedCompressor
        };
      }
      // Return whether a command contains an uncompressible command term
      // Will return true if command contains no uncompressible command terms
      static canCompress(command) {
        const commandDoc = command instanceof OpMsgRequest ? command.command : command.query;
        const commandName = Object.keys(commandDoc)[0];
        return !compression_1.uncompressibleCommands.has(commandName);
      }
      async toBin() {
        const concatenatedOriginalCommandBuffer = bson_1.ByteUtils.concat(this.command.toBin());
        const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE);
        const originalCommandOpCode = (0, bson_1.readInt32LE)(concatenatedOriginalCommandBuffer, 12);
        const compressedMessage = await (0, compression_1.compress)(this.options, messageToBeCompressed);
        const msgHeader = bson_1.ByteUtils.allocate(MESSAGE_HEADER_SIZE);
        bson_1.NumberUtils.setInt32LE(msgHeader, 0, MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length);
        bson_1.NumberUtils.setInt32LE(msgHeader, 4, this.command.requestId);
        bson_1.NumberUtils.setInt32LE(msgHeader, 8, 0);
        bson_1.NumberUtils.setInt32LE(msgHeader, 12, constants_1.OP_COMPRESSED);
        const compressionDetails = bson_1.ByteUtils.allocate(COMPRESSION_DETAILS_SIZE);
        bson_1.NumberUtils.setInt32LE(compressionDetails, 0, originalCommandOpCode);
        bson_1.NumberUtils.setInt32LE(compressionDetails, 4, messageToBeCompressed.length);
        compressionDetails[8] = compression_1.Compressor[this.options.agreedCompressor];
        return [msgHeader, compressionDetails, compressedMessage];
      }
    };
    exports2.OpCompressedRequest = OpCompressedRequest;
  }
});

// node_modules/mongodb/lib/cmap/wire_protocol/compression.js
var require_compression = __commonJS({
  "node_modules/mongodb/lib/cmap/wire_protocol/compression.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.uncompressibleCommands = exports2.Compressor = void 0;
    exports2.compress = compress;
    exports2.decompress = decompress;
    exports2.compressCommand = compressCommand;
    exports2.decompressResponse = decompressResponse;
    var zlib2 = require("zlib");
    var bson_1 = require_bson2();
    var constants_1 = require_constants2();
    var deps_1 = require_deps();
    var error_1 = require_error();
    var commands_1 = require_commands();
    var constants_2 = require_constants();
    exports2.Compressor = Object.freeze({
      none: 0,
      snappy: 1,
      zlib: 2,
      zstd: 3
    });
    exports2.uncompressibleCommands = /* @__PURE__ */ new Set([
      constants_1.LEGACY_HELLO_COMMAND,
      "saslStart",
      "saslContinue",
      "getnonce",
      "authenticate",
      "createUser",
      "updateUser",
      "copydbSaslStart",
      "copydbgetnonce",
      "copydb"
    ]);
    var ZSTD_COMPRESSION_LEVEL = 3;
    var zlibInflate = (buf) => {
      return new Promise((resolve2, reject) => {
        zlib2.inflate(buf, (error51, result) => {
          if (error51)
            return reject(error51);
          resolve2(result);
        });
      });
    };
    var zlibDeflate = (buf, options) => {
      return new Promise((resolve2, reject) => {
        zlib2.deflate(buf, options, (error51, result) => {
          if (error51)
            return reject(error51);
          resolve2(result);
        });
      });
    };
    var zstd;
    var Snappy = null;
    function loadSnappy() {
      if (Snappy == null) {
        const snappyImport = (0, deps_1.getSnappy)();
        if ("kModuleError" in snappyImport) {
          throw snappyImport.kModuleError;
        }
        Snappy = snappyImport;
      }
      return Snappy;
    }
    async function compress(options, dataToBeCompressed) {
      const zlibOptions = {};
      switch (options.agreedCompressor) {
        case "snappy": {
          Snappy ??= loadSnappy();
          return await Snappy.compress(dataToBeCompressed);
        }
        case "zstd": {
          loadZstd();
          if ("kModuleError" in zstd) {
            throw zstd["kModuleError"];
          }
          return await zstd.compress(dataToBeCompressed, ZSTD_COMPRESSION_LEVEL);
        }
        case "zlib": {
          if (options.zlibCompressionLevel) {
            zlibOptions.level = options.zlibCompressionLevel;
          }
          return await zlibDeflate(dataToBeCompressed, zlibOptions);
        }
        default: {
          throw new error_1.MongoInvalidArgumentError(`Unknown compressor ${options.agreedCompressor} failed to compress`);
        }
      }
    }
    async function decompress(compressorID, compressedData) {
      if (compressorID !== exports2.Compressor.snappy && compressorID !== exports2.Compressor.zstd && compressorID !== exports2.Compressor.zlib && compressorID !== exports2.Compressor.none) {
        throw new error_1.MongoDecompressionError(`Server sent message compressed using an unsupported compressor. (Received compressor ID ${compressorID})`);
      }
      switch (compressorID) {
        case exports2.Compressor.snappy: {
          Snappy ??= loadSnappy();
          return await Snappy.uncompress(compressedData, { asBuffer: true });
        }
        case exports2.Compressor.zstd: {
          loadZstd();
          if ("kModuleError" in zstd) {
            throw zstd["kModuleError"];
          }
          return await zstd.decompress(compressedData);
        }
        case exports2.Compressor.zlib: {
          return await zlibInflate(compressedData);
        }
        default: {
          return compressedData;
        }
      }
    }
    function loadZstd() {
      if (!zstd) {
        zstd = (0, deps_1.getZstdLibrary)();
      }
    }
    var MESSAGE_HEADER_SIZE = 16;
    async function compressCommand(command, description) {
      const finalCommand = description.agreedCompressor === "none" || !commands_1.OpCompressedRequest.canCompress(command) ? command : new commands_1.OpCompressedRequest(command, {
        agreedCompressor: description.agreedCompressor ?? "none",
        zlibCompressionLevel: description.zlibCompressionLevel ?? 0
      });
      const data = await finalCommand.toBin();
      return bson_1.ByteUtils.concat(data);
    }
    async function decompressResponse(message) {
      const messageHeader = {
        length: (0, bson_1.readInt32LE)(message, 0),
        requestId: (0, bson_1.readInt32LE)(message, 4),
        responseTo: (0, bson_1.readInt32LE)(message, 8),
        opCode: (0, bson_1.readInt32LE)(message, 12)
      };
      if (messageHeader.opCode !== constants_2.OP_COMPRESSED) {
        const ResponseType2 = messageHeader.opCode === constants_2.OP_MSG ? commands_1.OpMsgResponse : commands_1.OpReply;
        const messageBody2 = message.subarray(MESSAGE_HEADER_SIZE);
        return new ResponseType2(message, messageHeader, messageBody2);
      }
      const header = {
        ...messageHeader,
        fromCompressed: true,
        opCode: (0, bson_1.readInt32LE)(message, MESSAGE_HEADER_SIZE),
        length: (0, bson_1.readInt32LE)(message, MESSAGE_HEADER_SIZE + 4)
      };
      const compressorID = message[MESSAGE_HEADER_SIZE + 8];
      const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9);
      const ResponseType = header.opCode === constants_2.OP_MSG ? commands_1.OpMsgResponse : commands_1.OpReply;
      const messageBody = await decompress(compressorID, compressedBuffer);
      if (messageBody.length !== header.length) {
        throw new error_1.MongoDecompressionError("Message body and message header must be the same length");
      }
      return new ResponseType(message, header, messageBody);
    }
  }
});

// node_modules/mongodb/lib/client-side-encryption/errors.js
var require_errors = __commonJS({
  "node_modules/mongodb/lib/client-side-encryption/errors.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MongoCryptKMSRequestNetworkTimeoutError = exports2.MongoCryptAzureKMSRequestError = exports2.MongoCryptCreateEncryptedCollectionError = exports2.MongoCryptCreateDataKeyError = exports2.MongoCryptInvalidArgumentError = exports2.defaultErrorWrapper = exports2.MongoCryptError = void 0;
    var error_1 = require_error();
    var MongoCryptError = class extends error_1.MongoError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message, options = {}) {
        super(message, options);
      }
      get name() {
        return "MongoCryptError";
      }
    };
    exports2.MongoCryptError = MongoCryptError;
    var defaultErrorWrapper = (error51) => new MongoCryptError(error51.message, { cause: error51 });
    exports2.defaultErrorWrapper = defaultErrorWrapper;
    var MongoCryptInvalidArgumentError = class extends MongoCryptError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message) {
        super(message);
      }
      get name() {
        return "MongoCryptInvalidArgumentError";
      }
    };
    exports2.MongoCryptInvalidArgumentError = MongoCryptInvalidArgumentError;
    var MongoCryptCreateDataKeyError = class extends MongoCryptError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(encryptedFields, { cause }) {
        super(`Unable to complete creating data keys: ${cause.message}`, { cause });
        this.encryptedFields = encryptedFields;
      }
      get name() {
        return "MongoCryptCreateDataKeyError";
      }
    };
    exports2.MongoCryptCreateDataKeyError = MongoCryptCreateDataKeyError;
    var MongoCryptCreateEncryptedCollectionError = class extends MongoCryptError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(encryptedFields, { cause }) {
        super(`Unable to create collection: ${cause.message}`, { cause });
        this.encryptedFields = encryptedFields;
      }
      get name() {
        return "MongoCryptCreateEncryptedCollectionError";
      }
    };
    exports2.MongoCryptCreateEncryptedCollectionError = MongoCryptCreateEncryptedCollectionError;
    var MongoCryptAzureKMSRequestError = class extends MongoCryptError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message, body) {
        super(message);
        this.body = body;
      }
      get name() {
        return "MongoCryptAzureKMSRequestError";
      }
    };
    exports2.MongoCryptAzureKMSRequestError = MongoCryptAzureKMSRequestError;
    var MongoCryptKMSRequestNetworkTimeoutError = class extends MongoCryptError {
      get name() {
        return "MongoCryptKMSRequestNetworkTimeoutError";
      }
    };
    exports2.MongoCryptKMSRequestNetworkTimeoutError = MongoCryptKMSRequestNetworkTimeoutError;
  }
});

// node_modules/mongodb/lib/cmap/auth/aws_temporary_credentials.js
var require_aws_temporary_credentials = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/aws_temporary_credentials.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AWSSDKCredentialProvider = void 0;
    var process4 = require("process");
    var deps_1 = require_deps();
    var error_1 = require_error();
    var AWSSDKCredentialProvider = class _AWSSDKCredentialProvider {
      /**
       * Create the SDK credentials provider.
       * @param credentialsProvider - The credentials provider.
       */
      constructor(credentialsProvider) {
        if (credentialsProvider) {
          this._provider = credentialsProvider;
        }
      }
      static get awsSDK() {
        _AWSSDKCredentialProvider._awsSDK ??= (0, deps_1.getAwsCredentialProvider)();
        return _AWSSDKCredentialProvider._awsSDK;
      }
      /**
       * The AWS SDK caches credentials automatically and handles refresh when the credentials have expired.
       * To ensure this occurs, we need to cache the `provider` returned by the AWS sdk and re-use it when fetching credentials.
       */
      get provider() {
        if ("kModuleError" in _AWSSDKCredentialProvider.awsSDK) {
          throw _AWSSDKCredentialProvider.awsSDK.kModuleError;
        }
        if (this._provider) {
          return this._provider;
        }
        let { AWS_STS_REGIONAL_ENDPOINTS = "", AWS_REGION = "" } = process4.env;
        AWS_STS_REGIONAL_ENDPOINTS = AWS_STS_REGIONAL_ENDPOINTS.toLowerCase();
        AWS_REGION = AWS_REGION.toLowerCase();
        const awsRegionSettingsExist = AWS_REGION.length !== 0 && AWS_STS_REGIONAL_ENDPOINTS.length !== 0;
        const LEGACY_REGIONS = /* @__PURE__ */ new Set([
          "ap-northeast-1",
          "ap-south-1",
          "ap-southeast-1",
          "ap-southeast-2",
          "aws-global",
          "ca-central-1",
          "eu-central-1",
          "eu-north-1",
          "eu-west-1",
          "eu-west-2",
          "eu-west-3",
          "sa-east-1",
          "us-east-1",
          "us-east-2",
          "us-west-1",
          "us-west-2"
        ]);
        const useRegionalSts = AWS_STS_REGIONAL_ENDPOINTS === "regional" || AWS_STS_REGIONAL_ENDPOINTS === "legacy" && !LEGACY_REGIONS.has(AWS_REGION);
        this._provider = awsRegionSettingsExist && useRegionalSts ? _AWSSDKCredentialProvider.awsSDK.fromNodeProviderChain({
          clientConfig: { region: AWS_REGION }
        }) : _AWSSDKCredentialProvider.awsSDK.fromNodeProviderChain();
        return this._provider;
      }
      async getCredentials() {
        try {
          const creds = await this.provider();
          return {
            AccessKeyId: creds.accessKeyId,
            SecretAccessKey: creds.secretAccessKey,
            Token: creds.sessionToken,
            Expiration: creds.expiration
          };
        } catch (error51) {
          throw new error_1.MongoAWSError(error51.message, { cause: error51 });
        }
      }
    };
    exports2.AWSSDKCredentialProvider = AWSSDKCredentialProvider;
  }
});

// node_modules/mongodb/lib/client-side-encryption/providers/aws.js
var require_aws = __commonJS({
  "node_modules/mongodb/lib/client-side-encryption/providers/aws.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.loadAWSCredentials = loadAWSCredentials;
    var aws_temporary_credentials_1 = require_aws_temporary_credentials();
    async function loadAWSCredentials(kmsProviders, provider) {
      const credentialProvider = new aws_temporary_credentials_1.AWSSDKCredentialProvider(provider);
      const { SecretAccessKey = "", AccessKeyId = "", Token } = await credentialProvider.getCredentials();
      const aws = {
        secretAccessKey: SecretAccessKey,
        accessKeyId: AccessKeyId
      };
      Token != null && (aws.sessionToken = Token);
      return { ...kmsProviders, aws };
    }
  }
});

// node_modules/mongodb/lib/client-side-encryption/providers/azure.js
var require_azure = __commonJS({
  "node_modules/mongodb/lib/client-side-encryption/providers/azure.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.tokenCache = exports2.AzureCredentialCache = exports2.AZURE_BASE_URL = void 0;
    exports2.addAzureParams = addAzureParams;
    exports2.prepareRequest = prepareRequest;
    exports2.fetchAzureKMSToken = fetchAzureKMSToken;
    exports2.loadAzureCredentials = loadAzureCredentials;
    var error_1 = require_error();
    var utils_1 = require_utils();
    var errors_1 = require_errors();
    var MINIMUM_TOKEN_REFRESH_IN_MILLISECONDS = 6e3;
    exports2.AZURE_BASE_URL = "http://169.254.169.254/metadata/identity/oauth2/token?";
    var AzureCredentialCache = class {
      constructor() {
        this.cachedToken = null;
      }
      async getToken() {
        if (this.cachedToken == null || this.needsRefresh(this.cachedToken)) {
          this.cachedToken = await this._getToken();
        }
        return { accessToken: this.cachedToken.accessToken };
      }
      needsRefresh(token) {
        const timeUntilExpirationMS = token.expiresOnTimestamp - Date.now();
        return timeUntilExpirationMS <= MINIMUM_TOKEN_REFRESH_IN_MILLISECONDS;
      }
      /**
       * exposed for testing
       */
      resetCache() {
        this.cachedToken = null;
      }
      /**
       * exposed for testing
       */
      _getToken() {
        return fetchAzureKMSToken();
      }
    };
    exports2.AzureCredentialCache = AzureCredentialCache;
    exports2.tokenCache = new AzureCredentialCache();
    async function parseResponse(response) {
      const { status, body: rawBody } = response;
      const body = (() => {
        try {
          return JSON.parse(rawBody);
        } catch {
          throw new errors_1.MongoCryptAzureKMSRequestError("Malformed JSON body in GET request.");
        }
      })();
      if (status !== 200) {
        throw new errors_1.MongoCryptAzureKMSRequestError("Unable to complete request.", body);
      }
      if (!body.access_token) {
        throw new errors_1.MongoCryptAzureKMSRequestError("Malformed response body - missing field `access_token`.");
      }
      if (!body.expires_in) {
        throw new errors_1.MongoCryptAzureKMSRequestError("Malformed response body - missing field `expires_in`.");
      }
      const expiresInMS = Number(body.expires_in) * 1e3;
      if (Number.isNaN(expiresInMS)) {
        throw new errors_1.MongoCryptAzureKMSRequestError("Malformed response body - unable to parse int from `expires_in` field.");
      }
      return {
        accessToken: body.access_token,
        expiresOnTimestamp: Date.now() + expiresInMS
      };
    }
    function addAzureParams(url2, resource, username) {
      url2.searchParams.append("api-version", "2018-02-01");
      url2.searchParams.append("resource", resource);
      if (username) {
        url2.searchParams.append("client_id", username);
      }
      return url2;
    }
    function prepareRequest(options) {
      const url2 = new URL(options.url?.toString() ?? exports2.AZURE_BASE_URL);
      addAzureParams(url2, "https://vault.azure.net");
      const headers = { ...options.headers, "Content-Type": "application/json", Metadata: true };
      return { headers, url: url2 };
    }
    async function fetchAzureKMSToken(options = {}) {
      const { headers, url: url2 } = prepareRequest(options);
      try {
        const response = await (0, utils_1.get)(url2, { headers });
        return await parseResponse(response);
      } catch (error51) {
        if (error51 instanceof error_1.MongoNetworkTimeoutError) {
          throw new errors_1.MongoCryptAzureKMSRequestError(`[Azure KMS] ${error51.message}`);
        }
        throw error51;
      }
    }
    async function loadAzureCredentials(kmsProviders) {
      const azure = await exports2.tokenCache.getToken();
      return { ...kmsProviders, azure };
    }
  }
});

// node_modules/mongodb/lib/client-side-encryption/providers/gcp.js
var require_gcp = __commonJS({
  "node_modules/mongodb/lib/client-side-encryption/providers/gcp.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.loadGCPCredentials = loadGCPCredentials;
    var deps_1 = require_deps();
    async function loadGCPCredentials(kmsProviders) {
      const gcpMetadata = (0, deps_1.getGcpMetadata)();
      if ("kModuleError" in gcpMetadata) {
        return kmsProviders;
      }
      const { access_token: accessToken } = await gcpMetadata.instance({
        property: "service-accounts/default/token"
      });
      return { ...kmsProviders, gcp: { accessToken } };
    }
  }
});

// node_modules/mongodb/lib/client-side-encryption/providers/index.js
var require_providers2 = __commonJS({
  "node_modules/mongodb/lib/client-side-encryption/providers/index.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isEmptyCredentials = isEmptyCredentials;
    exports2.refreshKMSCredentials = refreshKMSCredentials;
    var aws_1 = require_aws();
    var azure_1 = require_azure();
    var gcp_1 = require_gcp();
    function isEmptyCredentials(providerName, kmsProviders) {
      const provider = kmsProviders[providerName];
      if (provider == null) {
        return false;
      }
      return typeof provider === "object" && Object.keys(provider).length === 0;
    }
    async function refreshKMSCredentials(kmsProviders, credentialProviders) {
      let finalKMSProviders = kmsProviders;
      if (isEmptyCredentials("aws", kmsProviders)) {
        finalKMSProviders = await (0, aws_1.loadAWSCredentials)(finalKMSProviders, credentialProviders?.aws);
      }
      if (isEmptyCredentials("gcp", kmsProviders)) {
        finalKMSProviders = await (0, gcp_1.loadGCPCredentials)(finalKMSProviders);
      }
      if (isEmptyCredentials("azure", kmsProviders)) {
        finalKMSProviders = await (0, azure_1.loadAzureCredentials)(finalKMSProviders);
      }
      return finalKMSProviders;
    }
  }
});

// node_modules/mongodb/lib/client-side-encryption/state_machine.js
var require_state_machine = __commonJS({
  "node_modules/mongodb/lib/client-side-encryption/state_machine.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.StateMachine = void 0;
    var fs2 = require("fs/promises");
    var net = require("net");
    var process4 = require("process");
    var tls = require("tls");
    var bson_1 = require_bson2();
    var abstract_cursor_1 = require_abstract_cursor();
    var deps_1 = require_deps();
    var error_1 = require_error();
    var timeout_1 = require_timeout();
    var utils_1 = require_utils();
    var client_encryption_1 = require_client_encryption();
    var errors_1 = require_errors();
    var socks = null;
    function loadSocks() {
      if (socks == null) {
        const socksImport = (0, deps_1.getSocks)();
        if ("kModuleError" in socksImport) {
          throw socksImport.kModuleError;
        }
        socks = socksImport;
      }
      return socks;
    }
    var MONGOCRYPT_CTX_ERROR = 0;
    var MONGOCRYPT_CTX_NEED_MONGO_COLLINFO = 1;
    var MONGOCRYPT_CTX_NEED_MONGO_MARKINGS = 2;
    var MONGOCRYPT_CTX_NEED_MONGO_KEYS = 3;
    var MONGOCRYPT_CTX_NEED_KMS_CREDENTIALS = 7;
    var MONGOCRYPT_CTX_NEED_KMS = 4;
    var MONGOCRYPT_CTX_READY = 5;
    var MONGOCRYPT_CTX_DONE = 6;
    var HTTPS_PORT = 443;
    var stateToString = /* @__PURE__ */ new Map([
      [MONGOCRYPT_CTX_ERROR, "MONGOCRYPT_CTX_ERROR"],
      [MONGOCRYPT_CTX_NEED_MONGO_COLLINFO, "MONGOCRYPT_CTX_NEED_MONGO_COLLINFO"],
      [MONGOCRYPT_CTX_NEED_MONGO_MARKINGS, "MONGOCRYPT_CTX_NEED_MONGO_MARKINGS"],
      [MONGOCRYPT_CTX_NEED_MONGO_KEYS, "MONGOCRYPT_CTX_NEED_MONGO_KEYS"],
      [MONGOCRYPT_CTX_NEED_KMS_CREDENTIALS, "MONGOCRYPT_CTX_NEED_KMS_CREDENTIALS"],
      [MONGOCRYPT_CTX_NEED_KMS, "MONGOCRYPT_CTX_NEED_KMS"],
      [MONGOCRYPT_CTX_READY, "MONGOCRYPT_CTX_READY"],
      [MONGOCRYPT_CTX_DONE, "MONGOCRYPT_CTX_DONE"]
    ]);
    var INSECURE_TLS_OPTIONS = [
      "tlsInsecure",
      "tlsAllowInvalidCertificates",
      "tlsAllowInvalidHostnames"
    ];
    function debug(msg) {
      if (process4.env.MONGODB_CRYPT_DEBUG) {
        console.error(msg);
      }
    }
    var EMPTY_V;
    var StateMachine = class {
      constructor(options, bsonOptions = (0, bson_1.pluckBSONSerializeOptions)(options)) {
        this.options = options;
        this.bsonOptions = bsonOptions;
      }
      /**
       * Executes the state machine according to the specification
       */
      async execute(executor, context, options) {
        const keyVaultNamespace = executor._keyVaultNamespace;
        const keyVaultClient = executor._keyVaultClient;
        const metaDataClient = executor._metaDataClient;
        const mongocryptdClient = executor._mongocryptdClient;
        const mongocryptdManager = executor._mongocryptdManager;
        let result = null;
        const getStatus = () => context.status;
        const getState = () => context.state;
        while (getState() !== MONGOCRYPT_CTX_DONE && getState() !== MONGOCRYPT_CTX_ERROR) {
          options.signal?.throwIfAborted();
          debug(`[context#${context.id}] ${stateToString.get(getState()) || getState()}`);
          switch (getState()) {
            case MONGOCRYPT_CTX_NEED_MONGO_COLLINFO: {
              const filter = (0, bson_1.deserialize)(context.nextMongoOperation());
              if (!metaDataClient) {
                throw new errors_1.MongoCryptError("unreachable state machine state: entered MONGOCRYPT_CTX_NEED_MONGO_COLLINFO but metadata client is undefined");
              }
              const collInfoCursor = this.fetchCollectionInfo(metaDataClient, context.ns, filter, options);
              for await (const collInfo of collInfoCursor) {
                context.addMongoOperationResponse((0, bson_1.serialize)(collInfo));
                if (getState() === MONGOCRYPT_CTX_ERROR)
                  break;
              }
              if (getState() === MONGOCRYPT_CTX_ERROR)
                break;
              context.finishMongoOperation();
              break;
            }
            case MONGOCRYPT_CTX_NEED_MONGO_MARKINGS: {
              const command = context.nextMongoOperation();
              if (getState() === MONGOCRYPT_CTX_ERROR)
                break;
              if (!mongocryptdClient) {
                throw new errors_1.MongoCryptError("unreachable state machine state: entered MONGOCRYPT_CTX_NEED_MONGO_MARKINGS but mongocryptdClient is undefined");
              }
              const markedCommand = mongocryptdManager ? await mongocryptdManager.withRespawn(this.markCommand.bind(this, mongocryptdClient, context.ns, command, options)) : await this.markCommand(mongocryptdClient, context.ns, command, options);
              context.addMongoOperationResponse(markedCommand);
              context.finishMongoOperation();
              break;
            }
            case MONGOCRYPT_CTX_NEED_MONGO_KEYS: {
              const filter = context.nextMongoOperation();
              const keys = await this.fetchKeys(keyVaultClient, keyVaultNamespace, filter, options);
              if (keys.length === 0) {
                result = EMPTY_V ??= (0, bson_1.serialize)({ v: [] });
              }
              for (const key of keys) {
                context.addMongoOperationResponse((0, bson_1.serialize)(key));
              }
              context.finishMongoOperation();
              break;
            }
            case MONGOCRYPT_CTX_NEED_KMS_CREDENTIALS: {
              const kmsProviders = await executor.askForKMSCredentials();
              context.provideKMSProviders((0, bson_1.serialize)(kmsProviders));
              break;
            }
            case MONGOCRYPT_CTX_NEED_KMS: {
              await Promise.all(this.requests(context, options));
              context.finishKMSRequests();
              break;
            }
            case MONGOCRYPT_CTX_READY: {
              const finalizedContext = context.finalize();
              if (getState() === MONGOCRYPT_CTX_ERROR) {
                const message = getStatus().message || "Finalization error";
                throw new errors_1.MongoCryptError(message);
              }
              result = finalizedContext;
              break;
            }
            default:
              throw new errors_1.MongoCryptError(`Unknown state: ${getState()}`);
          }
        }
        if (getState() === MONGOCRYPT_CTX_ERROR || result == null) {
          const message = getStatus().message;
          if (!message) {
            debug(`unidentifiable error in MongoCrypt - received an error status from \`libmongocrypt\` but received no error message.`);
          }
          throw new errors_1.MongoCryptError(message ?? "unidentifiable error in MongoCrypt - received an error status from `libmongocrypt` but received no error message.");
        }
        return result;
      }
      /**
       * Handles the request to the KMS service. Exposed for testing purposes. Do not directly invoke.
       * @param kmsContext - A C++ KMS context returned from the bindings
       * @returns A promise that resolves when the KMS reply has be fully parsed
       */
      async kmsRequest(request, options) {
        const parsedUrl = request.endpoint.split(":");
        const port = parsedUrl[1] != null ? Number.parseInt(parsedUrl[1], 10) : HTTPS_PORT;
        const socketOptions = {
          host: parsedUrl[0],
          servername: parsedUrl[0],
          port,
          ...(0, client_encryption_1.autoSelectSocketOptions)(this.options.socketOptions || {})
        };
        const message = request.message;
        const buffer = new utils_1.BufferPool();
        let netSocket;
        let socket;
        function destroySockets() {
          for (const sock of [socket, netSocket]) {
            if (sock) {
              sock.destroy();
            }
          }
        }
        function onerror(cause) {
          return new errors_1.MongoCryptError("KMS request failed", { cause });
        }
        function onclose() {
          return new errors_1.MongoCryptError("KMS request closed");
        }
        const tlsOptions = this.options.tlsOptions;
        if (tlsOptions) {
          const kmsProvider = request.kmsProvider;
          const providerTlsOptions = tlsOptions[kmsProvider];
          if (providerTlsOptions) {
            const error51 = this.validateTlsOptions(kmsProvider, providerTlsOptions);
            if (error51) {
              throw error51;
            }
            try {
              await this.setTlsOptions(providerTlsOptions, socketOptions);
            } catch (err) {
              throw onerror(err);
            }
          }
        }
        let abortListener;
        try {
          if (this.options.proxyOptions && this.options.proxyOptions.proxyHost) {
            netSocket = new net.Socket();
            const { promise: willConnect, reject: rejectOnNetSocketError, resolve: resolveOnNetSocketConnect } = (0, utils_1.promiseWithResolvers)();
            netSocket.once("error", (err) => rejectOnNetSocketError(onerror(err))).once("close", () => rejectOnNetSocketError(onclose())).once("connect", () => resolveOnNetSocketConnect());
            const netSocketOptions = {
              ...socketOptions,
              host: this.options.proxyOptions.proxyHost,
              port: this.options.proxyOptions.proxyPort || 1080
            };
            netSocket.connect(netSocketOptions);
            await willConnect;
            try {
              socks ??= loadSocks();
              socketOptions.socket = (await socks.SocksClient.createConnection({
                existing_socket: netSocket,
                command: "connect",
                destination: { host: socketOptions.host, port: socketOptions.port },
                proxy: {
                  // host and port are ignored because we pass existing_socket
                  host: "iLoveJavaScript",
                  port: 0,
                  type: 5,
                  userId: this.options.proxyOptions.proxyUsername,
                  password: this.options.proxyOptions.proxyPassword
                }
              })).socket;
            } catch (err) {
              throw onerror(err);
            }
          }
          socket = tls.connect(socketOptions, () => {
            socket.write(message);
          });
          const { promise: willResolveKmsRequest, reject: rejectOnTlsSocketError, resolve: resolve2 } = (0, utils_1.promiseWithResolvers)();
          abortListener = (0, utils_1.addAbortListener)(options?.signal, function() {
            destroySockets();
            rejectOnTlsSocketError(this.reason);
          });
          socket.once("error", (err) => rejectOnTlsSocketError(onerror(err))).once("close", () => rejectOnTlsSocketError(onclose())).on("data", (data) => {
            buffer.append(data);
            while (request.bytesNeeded > 0 && buffer.length) {
              const bytesNeeded = Math.min(request.bytesNeeded, buffer.length);
              request.addResponse(buffer.read(bytesNeeded));
            }
            if (request.bytesNeeded <= 0) {
              resolve2();
            }
          });
          await (options?.timeoutContext?.csotEnabled() ? Promise.all([
            willResolveKmsRequest,
            timeout_1.Timeout.expires(options.timeoutContext?.remainingTimeMS)
          ]) : willResolveKmsRequest);
        } catch (error51) {
          if (error51 instanceof timeout_1.TimeoutError)
            throw new error_1.MongoOperationTimeoutError("KMS request timed out");
          throw error51;
        } finally {
          destroySockets();
          abortListener?.[utils_1.kDispose]();
        }
      }
      *requests(context, options) {
        for (let request = context.nextKMSRequest(); request != null; request = context.nextKMSRequest()) {
          yield this.kmsRequest(request, options);
        }
      }
      /**
       * Validates the provided TLS options are secure.
       *
       * @param kmsProvider - The KMS provider name.
       * @param tlsOptions - The client TLS options for the provider.
       *
       * @returns An error if any option is invalid.
       */
      validateTlsOptions(kmsProvider, tlsOptions) {
        const tlsOptionNames = Object.keys(tlsOptions);
        for (const option of INSECURE_TLS_OPTIONS) {
          if (tlsOptionNames.includes(option)) {
            return new errors_1.MongoCryptError(`Insecure TLS options prohibited for ${kmsProvider}: ${option}`);
          }
        }
      }
      /**
       * Sets only the valid secure TLS options.
       *
       * @param tlsOptions - The client TLS options for the provider.
       * @param options - The existing connection options.
       */
      async setTlsOptions(tlsOptions, options) {
        if (tlsOptions.secureContext) {
          options.secureContext = tlsOptions.secureContext;
        }
        if (tlsOptions.tlsCertificateKeyFile) {
          const cert = await fs2.readFile(tlsOptions.tlsCertificateKeyFile);
          options.cert = options.key = cert;
        }
        if (tlsOptions.tlsCAFile) {
          options.ca = await fs2.readFile(tlsOptions.tlsCAFile);
        }
        if (tlsOptions.tlsCertificateKeyFilePassword) {
          options.passphrase = tlsOptions.tlsCertificateKeyFilePassword;
        }
      }
      /**
       * Fetches collection info for a provided namespace, when libmongocrypt
       * enters the `MONGOCRYPT_CTX_NEED_MONGO_COLLINFO` state. The result is
       * used to inform libmongocrypt of the schema associated with this
       * namespace. Exposed for testing purposes. Do not directly invoke.
       *
       * @param client - A MongoClient connected to the topology
       * @param ns - The namespace to list collections from
       * @param filter - A filter for the listCollections command
       * @param callback - Invoked with the info of the requested collection, or with an error
       */
      fetchCollectionInfo(client, ns, filter, options) {
        const { db } = utils_1.MongoDBCollectionNamespace.fromString(ns);
        const cursor = client.db(db).listCollections(filter, {
          promoteLongs: false,
          promoteValues: false,
          timeoutContext: options?.timeoutContext && new abstract_cursor_1.CursorTimeoutContext(options?.timeoutContext, /* @__PURE__ */ Symbol()),
          signal: options?.signal,
          nameOnly: false
        });
        return cursor;
      }
      /**
       * Calls to the mongocryptd to provide markings for a command.
       * Exposed for testing purposes. Do not directly invoke.
       * @param client - A MongoClient connected to a mongocryptd
       * @param ns - The namespace (database.collection) the command is being executed on
       * @param command - The command to execute.
       * @param callback - Invoked with the serialized and marked bson command, or with an error
       */
      async markCommand(client, ns, command, options) {
        const { db } = utils_1.MongoDBCollectionNamespace.fromString(ns);
        const bsonOptions = { promoteLongs: false, promoteValues: false };
        const rawCommand = (0, bson_1.deserialize)(command, bsonOptions);
        const commandOptions = {
          timeoutMS: void 0,
          signal: void 0
        };
        if (options?.timeoutContext?.csotEnabled()) {
          commandOptions.timeoutMS = options.timeoutContext.remainingTimeMS;
        }
        if (options?.signal) {
          commandOptions.signal = options.signal;
        }
        const response = await client.db(db).command(rawCommand, {
          ...bsonOptions,
          ...commandOptions
        });
        return (0, bson_1.serialize)(response, this.bsonOptions);
      }
      /**
       * Requests keys from the keyVault collection on the topology.
       * Exposed for testing purposes. Do not directly invoke.
       * @param client - A MongoClient connected to the topology
       * @param keyVaultNamespace - The namespace (database.collection) of the keyVault Collection
       * @param filter - The filter for the find query against the keyVault Collection
       * @param callback - Invoked with the found keys, or with an error
       */
      fetchKeys(client, keyVaultNamespace, filter, options) {
        const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(keyVaultNamespace);
        const commandOptions = {
          timeoutContext: void 0,
          signal: void 0
        };
        if (options?.timeoutContext != null) {
          commandOptions.timeoutContext = new abstract_cursor_1.CursorTimeoutContext(options.timeoutContext, /* @__PURE__ */ Symbol());
        }
        if (options?.signal != null) {
          commandOptions.signal = options.signal;
        }
        return client.db(dbName).collection(collectionName, { readConcern: { level: "majority" } }).find((0, bson_1.deserialize)(filter), commandOptions).toArray();
      }
    };
    exports2.StateMachine = StateMachine;
  }
});

// node_modules/mongodb/lib/client-side-encryption/client_encryption.js
var require_client_encryption = __commonJS({
  "node_modules/mongodb/lib/client-side-encryption/client_encryption.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ClientEncryption = void 0;
    exports2.autoSelectSocketOptions = autoSelectSocketOptions;
    var bson_1 = require_bson2();
    var deps_1 = require_deps();
    var timeout_1 = require_timeout();
    var utils_1 = require_utils();
    var errors_1 = require_errors();
    var index_1 = require_providers2();
    var state_machine_1 = require_state_machine();
    var ClientEncryption = class _ClientEncryption {
      /** @internal */
      static getMongoCrypt() {
        const encryption = (0, deps_1.getMongoDBClientEncryption)();
        if ("kModuleError" in encryption) {
          throw encryption.kModuleError;
        }
        return encryption.MongoCrypt;
      }
      /**
       * Create a new encryption instance
       *
       * @example
       * ```ts
       * new ClientEncryption(mongoClient, {
       *   keyVaultNamespace: 'client.encryption',
       *   kmsProviders: {
       *     local: {
       *       key: masterKey // The master key used for encryption/decryption. A 96-byte long Buffer
       *     }
       *   }
       * });
       * ```
       *
       * @example
       * ```ts
       * new ClientEncryption(mongoClient, {
       *   keyVaultNamespace: 'client.encryption',
       *   kmsProviders: {
       *     aws: {
       *       accessKeyId: AWS_ACCESS_KEY,
       *       secretAccessKey: AWS_SECRET_KEY
       *     }
       *   }
       * });
       * ```
       */
      constructor(client, options) {
        this._client = client;
        this._proxyOptions = options.proxyOptions ?? {};
        this._tlsOptions = options.tlsOptions ?? {};
        this._kmsProviders = options.kmsProviders || {};
        const { timeoutMS } = (0, utils_1.resolveTimeoutOptions)(client, options);
        this._timeoutMS = timeoutMS;
        this._credentialProviders = options.credentialProviders;
        if (options.credentialProviders?.aws && !(0, index_1.isEmptyCredentials)("aws", this._kmsProviders)) {
          throw new errors_1.MongoCryptInvalidArgumentError("Can only provide a custom AWS credential provider when the state machine is configured for automatic AWS credential fetching");
        }
        if (options.keyVaultNamespace == null) {
          throw new errors_1.MongoCryptInvalidArgumentError("Missing required option `keyVaultNamespace`");
        }
        const mongoCryptOptions = {
          ...options,
          kmsProviders: (0, bson_1.serialize)(this._kmsProviders),
          errorWrapper: errors_1.defaultErrorWrapper
        };
        this._keyVaultNamespace = options.keyVaultNamespace;
        this._keyVaultClient = options.keyVaultClient || client;
        const MongoCrypt = _ClientEncryption.getMongoCrypt();
        this._mongoCrypt = new MongoCrypt(mongoCryptOptions);
      }
      /**
       * Creates a data key used for explicit encryption and inserts it into the key vault namespace
       *
       * @example
       * ```ts
       * // Using async/await to create a local key
       * const dataKeyId = await clientEncryption.createDataKey('local');
       * ```
       *
       * @example
       * ```ts
       * // Using async/await to create an aws key
       * const dataKeyId = await clientEncryption.createDataKey('aws', {
       *   masterKey: {
       *     region: 'us-east-1',
       *     key: 'xxxxxxxxxxxxxx' // CMK ARN here
       *   }
       * });
       * ```
       *
       * @example
       * ```ts
       * // Using async/await to create an aws key with a keyAltName
       * const dataKeyId = await clientEncryption.createDataKey('aws', {
       *   masterKey: {
       *     region: 'us-east-1',
       *     key: 'xxxxxxxxxxxxxx' // CMK ARN here
       *   },
       *   keyAltNames: [ 'mySpecialKey' ]
       * });
       * ```
       */
      async createDataKey(provider, options = {}) {
        if (options.keyAltNames && !Array.isArray(options.keyAltNames)) {
          throw new errors_1.MongoCryptInvalidArgumentError(`Option "keyAltNames" must be an array of strings, but was of type ${typeof options.keyAltNames}.`);
        }
        let keyAltNames = void 0;
        if (options.keyAltNames && options.keyAltNames.length > 0) {
          keyAltNames = options.keyAltNames.map((keyAltName, i2) => {
            if (typeof keyAltName !== "string") {
              throw new errors_1.MongoCryptInvalidArgumentError(`Option "keyAltNames" must be an array of strings, but item at index ${i2} was of type ${typeof keyAltName}`);
            }
            return (0, bson_1.serialize)({ keyAltName });
          });
        }
        let keyMaterial = void 0;
        if (options.keyMaterial) {
          keyMaterial = (0, bson_1.serialize)({ keyMaterial: options.keyMaterial });
        }
        const dataKeyBson = (0, bson_1.serialize)({
          provider,
          ...options.masterKey
        });
        const context = this._mongoCrypt.makeDataKeyContext(dataKeyBson, {
          keyAltNames,
          keyMaterial
        });
        const stateMachine = new state_machine_1.StateMachine({
          proxyOptions: this._proxyOptions,
          tlsOptions: this._tlsOptions,
          socketOptions: autoSelectSocketOptions(this._client.s.options)
        });
        const timeoutContext = options?.timeoutContext ?? timeout_1.TimeoutContext.create((0, utils_1.resolveTimeoutOptions)(this._client, { timeoutMS: this._timeoutMS }));
        const dataKey = (0, bson_1.deserialize)(await stateMachine.execute(this, context, { timeoutContext }));
        const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);
        const { insertedId } = await this._keyVaultClient.db(dbName).collection(collectionName).insertOne(dataKey, {
          writeConcern: { w: "majority" },
          timeoutMS: timeoutContext?.csotEnabled() ? timeoutContext?.getRemainingTimeMSOrThrow() : void 0
        });
        return insertedId;
      }
      /**
       * Searches the keyvault for any data keys matching the provided filter.  If there are matches, rewrapManyDataKey then attempts to re-wrap the data keys using the provided options.
       *
       * If no matches are found, then no bulk write is performed.
       *
       * @example
       * ```ts
       * // rewrapping all data data keys (using a filter that matches all documents)
       * const filter = {};
       *
       * const result = await clientEncryption.rewrapManyDataKey(filter);
       * if (result.bulkWriteResult != null) {
       *  // keys were re-wrapped, results will be available in the bulkWrite object.
       * }
       * ```
       *
       * @example
       * ```ts
       * // attempting to rewrap all data keys with no matches
       * const filter = { _id: new Binary() } // assume _id matches no documents in the database
       * const result = await clientEncryption.rewrapManyDataKey(filter);
       *
       * if (result.bulkWriteResult == null) {
       *  // no keys matched, `bulkWriteResult` does not exist on the result object
       * }
       * ```
       */
      async rewrapManyDataKey(filter, options) {
        let keyEncryptionKeyBson = void 0;
        if (options) {
          const keyEncryptionKey = Object.assign({ provider: options.provider }, options.masterKey);
          keyEncryptionKeyBson = (0, bson_1.serialize)(keyEncryptionKey);
        }
        const filterBson = (0, bson_1.serialize)(filter);
        const context = this._mongoCrypt.makeRewrapManyDataKeyContext(filterBson, keyEncryptionKeyBson);
        const stateMachine = new state_machine_1.StateMachine({
          proxyOptions: this._proxyOptions,
          tlsOptions: this._tlsOptions,
          socketOptions: autoSelectSocketOptions(this._client.s.options)
        });
        const timeoutContext = timeout_1.TimeoutContext.create((0, utils_1.resolveTimeoutOptions)(this._client, { timeoutMS: this._timeoutMS }));
        const { v: dataKeys } = (0, bson_1.deserialize)(await stateMachine.execute(this, context, { timeoutContext }));
        if (dataKeys.length === 0) {
          return {};
        }
        const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);
        const replacements = dataKeys.map((key) => ({
          updateOne: {
            filter: { _id: key._id },
            update: {
              $set: {
                masterKey: key.masterKey,
                keyMaterial: key.keyMaterial
              },
              $currentDate: {
                updateDate: true
              }
            }
          }
        }));
        const result = await this._keyVaultClient.db(dbName).collection(collectionName).bulkWrite(replacements, {
          writeConcern: { w: "majority" },
          timeoutMS: timeoutContext.csotEnabled() ? timeoutContext?.remainingTimeMS : void 0
        });
        return { bulkWriteResult: result };
      }
      /**
       * Deletes the key with the provided id from the keyvault, if it exists.
       *
       * @example
       * ```ts
       * // delete a key by _id
       * const id = new Binary(); // id is a bson binary subtype 4 object
       * const { deletedCount } = await clientEncryption.deleteKey(id);
       *
       * if (deletedCount != null && deletedCount > 0) {
       *   // successful deletion
       * }
       * ```
       *
       */
      async deleteKey(_id) {
        const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);
        return await this._keyVaultClient.db(dbName).collection(collectionName).deleteOne({ _id }, { writeConcern: { w: "majority" }, timeoutMS: this._timeoutMS });
      }
      /**
       * Finds all the keys currently stored in the keyvault.
       *
       * This method will not throw.
       *
       * @returns a FindCursor over all keys in the keyvault.
       * @example
       * ```ts
       * // fetching all keys
       * const keys = await clientEncryption.getKeys().toArray();
       * ```
       */
      getKeys() {
        const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);
        return this._keyVaultClient.db(dbName).collection(collectionName).find({}, { readConcern: { level: "majority" }, timeoutMS: this._timeoutMS });
      }
      /**
       * Finds a key in the keyvault with the specified _id.
       *
       * Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
       * match the id.  The promise rejects with an error if an error is thrown.
       * @example
       * ```ts
       * // getting a key by id
       * const id = new Binary(); // id is a bson binary subtype 4 object
       * const key = await clientEncryption.getKey(id);
       * if (!key) {
       *  // key is null if there was no matching key
       * }
       * ```
       */
      async getKey(_id) {
        const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);
        return await this._keyVaultClient.db(dbName).collection(collectionName).findOne({ _id }, { readConcern: { level: "majority" }, timeoutMS: this._timeoutMS });
      }
      /**
       * Finds a key in the keyvault which has the specified keyAltName.
       *
       * @param keyAltName - a keyAltName to search for a key
       * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
       * match the keyAltName.  The promise rejects with an error if an error is thrown.
       * @example
       * ```ts
       * // get a key by alt name
       * const keyAltName = 'keyAltName';
       * const key = await clientEncryption.getKeyByAltName(keyAltName);
       * if (!key) {
       *  // key is null if there is no matching key
       * }
       * ```
       */
      async getKeyByAltName(keyAltName) {
        const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);
        return await this._keyVaultClient.db(dbName).collection(collectionName).findOne({ keyAltNames: keyAltName }, { readConcern: { level: "majority" }, timeoutMS: this._timeoutMS });
      }
      /**
       * Adds a keyAltName to a key identified by the provided _id.
       *
       * This method resolves to/returns the *old* key value (prior to adding the new altKeyName).
       *
       * @param _id - The id of the document to update.
       * @param keyAltName - a keyAltName to search for a key
       * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
       * match the id.  The promise rejects with an error if an error is thrown.
       * @example
       * ```ts
       * // adding an keyAltName to a data key
       * const id = new Binary();  // id is a bson binary subtype 4 object
       * const keyAltName = 'keyAltName';
       * const oldKey = await clientEncryption.addKeyAltName(id, keyAltName);
       * if (!oldKey) {
       *  // null is returned if there is no matching document with an id matching the supplied id
       * }
       * ```
       */
      async addKeyAltName(_id, keyAltName) {
        const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);
        const value = await this._keyVaultClient.db(dbName).collection(collectionName).findOneAndUpdate({ _id }, { $addToSet: { keyAltNames: keyAltName } }, { writeConcern: { w: "majority" }, returnDocument: "before", timeoutMS: this._timeoutMS });
        return value;
      }
      /**
       * Adds a keyAltName to a key identified by the provided _id.
       *
       * This method resolves to/returns the *old* key value (prior to removing the new altKeyName).
       *
       * If the removed keyAltName is the last keyAltName for that key, the `altKeyNames` property is unset from the document.
       *
       * @param _id - The id of the document to update.
       * @param keyAltName - a keyAltName to search for a key
       * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
       * match the id.  The promise rejects with an error if an error is thrown.
       * @example
       * ```ts
       * // removing a key alt name from a data key
       * const id = new Binary();  // id is a bson binary subtype 4 object
       * const keyAltName = 'keyAltName';
       * const oldKey = await clientEncryption.removeKeyAltName(id, keyAltName);
       *
       * if (!oldKey) {
       *  // null is returned if there is no matching document with an id matching the supplied id
       * }
       * ```
       */
      async removeKeyAltName(_id, keyAltName) {
        const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);
        const pipeline2 = [
          {
            $set: {
              keyAltNames: {
                $cond: [
                  {
                    $eq: ["$keyAltNames", [keyAltName]]
                  },
                  "$$REMOVE",
                  {
                    $filter: {
                      input: "$keyAltNames",
                      cond: {
                        $ne: ["$$this", keyAltName]
                      }
                    }
                  }
                ]
              }
            }
          }
        ];
        const value = await this._keyVaultClient.db(dbName).collection(collectionName).findOneAndUpdate({ _id }, pipeline2, {
          writeConcern: { w: "majority" },
          returnDocument: "before",
          timeoutMS: this._timeoutMS
        });
        return value;
      }
      /**
       * A convenience method for creating an encrypted collection.
       * This method will create data keys for any encryptedFields that do not have a `keyId` defined
       * and then create a new collection with the full set of encryptedFields.
       *
       * @param db - A Node.js driver Db object with which to create the collection
       * @param name - The name of the collection to be created
       * @param options - Options for createDataKey and for createCollection
       * @returns created collection and generated encryptedFields
       * @throws MongoCryptCreateDataKeyError - If part way through the process a createDataKey invocation fails, an error will be rejected that has the partial `encryptedFields` that were created.
       * @throws MongoCryptCreateEncryptedCollectionError - If creating the collection fails, an error will be rejected that has the entire `encryptedFields` that were created.
       */
      async createEncryptedCollection(db, name, options) {
        const { provider, masterKey, createCollectionOptions: { encryptedFields: { ...encryptedFields }, ...createCollectionOptions } } = options;
        const timeoutContext = this._timeoutMS != null ? timeout_1.TimeoutContext.create((0, utils_1.resolveTimeoutOptions)(this._client, { timeoutMS: this._timeoutMS })) : void 0;
        if (Array.isArray(encryptedFields.fields)) {
          const createDataKeyPromises = encryptedFields.fields.map(async (field) => field == null || typeof field !== "object" || field.keyId != null ? field : {
            ...field,
            keyId: await this.createDataKey(provider, {
              masterKey,
              // clone the timeoutContext
              // in order to avoid sharing the same timeout for server selection and connection checkout across different concurrent operations
              timeoutContext: timeoutContext?.csotEnabled() ? timeoutContext?.clone() : void 0
            })
          });
          const createDataKeyResolutions = await Promise.allSettled(createDataKeyPromises);
          encryptedFields.fields = createDataKeyResolutions.map((resolution, index) => resolution.status === "fulfilled" ? resolution.value : encryptedFields.fields[index]);
          const rejection = createDataKeyResolutions.find((result) => result.status === "rejected");
          if (rejection != null) {
            throw new errors_1.MongoCryptCreateDataKeyError(encryptedFields, { cause: rejection.reason });
          }
        }
        try {
          const collection = await db.createCollection(name, {
            ...createCollectionOptions,
            encryptedFields,
            timeoutMS: timeoutContext?.csotEnabled() ? timeoutContext?.getRemainingTimeMSOrThrow() : void 0
          });
          return { collection, encryptedFields };
        } catch (cause) {
          throw new errors_1.MongoCryptCreateEncryptedCollectionError(encryptedFields, { cause });
        }
      }
      /**
       * Explicitly encrypt a provided value. Note that either `options.keyId` or `options.keyAltName` must
       * be specified. Specifying both `options.keyId` and `options.keyAltName` is considered an error.
       *
       * @param value - The value that you wish to serialize. Must be of a type that can be serialized into BSON
       * @param options -
       * @returns a Promise that either resolves with the encrypted value, or rejects with an error.
       *
       * @example
       * ```ts
       * // Encryption with async/await api
       * async function encryptMyData(value) {
       *   const keyId = await clientEncryption.createDataKey('local');
       *   return clientEncryption.encrypt(value, { keyId, algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' });
       * }
       * ```
       *
       * @example
       * ```ts
       * // Encryption using a keyAltName
       * async function encryptMyData(value) {
       *   await clientEncryption.createDataKey('local', { keyAltNames: 'mySpecialKey' });
       *   return clientEncryption.encrypt(value, { keyAltName: 'mySpecialKey', algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' });
       * }
       * ```
       */
      async encrypt(value, options) {
        return await this._encrypt(value, false, options);
      }
      /**
       * Encrypts a Match Expression or Aggregate Expression to query a range index.
       *
       * Only supported when queryType is "range" and algorithm is "Range".
       *
       * @param expression - a BSON document of one of the following forms:
       *  1. A Match Expression of this form:
       *      `{$and: [{<field>: {$gt: <value1>}}, {<field>: {$lt: <value2> }}]}`
       *  2. An Aggregate Expression of this form:
       *      `{$and: [{$gt: [<fieldpath>, <value1>]}, {$lt: [<fieldpath>, <value2>]}]}`
       *
       *    `$gt` may also be `$gte`. `$lt` may also be `$lte`.
       *
       * @param options -
       * @returns Returns a Promise that either resolves with the encrypted value or rejects with an error.
       */
      async encryptExpression(expression, options) {
        return await this._encrypt(expression, true, options);
      }
      /**
       * Explicitly decrypt a provided encrypted value
       *
       * @param value - An encrypted value
       * @returns a Promise that either resolves with the decrypted value, or rejects with an error
       *
       * @example
       * ```ts
       * // Decrypting value with async/await API
       * async function decryptMyValue(value) {
       *   return clientEncryption.decrypt(value);
       * }
       * ```
       */
      async decrypt(value) {
        const valueBuffer = (0, bson_1.serialize)({ v: value });
        const context = this._mongoCrypt.makeExplicitDecryptionContext(valueBuffer);
        const stateMachine = new state_machine_1.StateMachine({
          proxyOptions: this._proxyOptions,
          tlsOptions: this._tlsOptions,
          socketOptions: autoSelectSocketOptions(this._client.s.options)
        });
        const timeoutContext = this._timeoutMS != null ? timeout_1.TimeoutContext.create((0, utils_1.resolveTimeoutOptions)(this._client, { timeoutMS: this._timeoutMS })) : void 0;
        const { v } = (0, bson_1.deserialize)(await stateMachine.execute(this, context, { timeoutContext }));
        return v;
      }
      /**
       * @internal
       * Ask the user for KMS credentials.
       *
       * This returns anything that looks like the kmsProviders original input
       * option. It can be empty, and any provider specified here will override
       * the original ones.
       */
      async askForKMSCredentials() {
        return await (0, index_1.refreshKMSCredentials)(this._kmsProviders, this._credentialProviders);
      }
      static get libmongocryptVersion() {
        return _ClientEncryption.getMongoCrypt().libmongocryptVersion;
      }
      /**
       * @internal
       * A helper that perform explicit encryption of values and expressions.
       * Explicitly encrypt a provided value. Note that either `options.keyId` or `options.keyAltName` must
       * be specified. Specifying both `options.keyId` and `options.keyAltName` is considered an error.
       *
       * @param value - The value that you wish to encrypt. Must be of a type that can be serialized into BSON
       * @param expressionMode - a boolean that indicates whether or not to encrypt the value as an expression
       * @param options - options to pass to encrypt
       * @returns the raw result of the call to stateMachine.execute().  When expressionMode is set to true, the return
       *          value will be a bson document.  When false, the value will be a BSON Binary.
       *
       */
      async _encrypt(value, expressionMode, options) {
        const { algorithm, keyId, keyAltName, contentionFactor, queryType, rangeOptions, stringOptions, textOptions } = options;
        const contextOptions = {
          expressionMode,
          algorithm
        };
        if (keyId) {
          contextOptions.keyId = keyId.buffer;
        }
        if (keyAltName) {
          if (keyId) {
            throw new errors_1.MongoCryptInvalidArgumentError(`"options" cannot contain both "keyId" and "keyAltName"`);
          }
          if (typeof keyAltName !== "string") {
            throw new errors_1.MongoCryptInvalidArgumentError(`"options.keyAltName" must be of type string, but was of type ${typeof keyAltName}`);
          }
          contextOptions.keyAltName = (0, bson_1.serialize)({ keyAltName });
        }
        if (typeof contentionFactor === "number" || typeof contentionFactor === "bigint") {
          contextOptions.contentionFactor = contentionFactor;
        }
        if (typeof queryType === "string") {
          contextOptions.queryType = queryType;
        }
        if (typeof rangeOptions === "object") {
          contextOptions.rangeOptions = (0, bson_1.serialize)(rangeOptions);
        }
        const resolvedStringOptions = stringOptions ?? textOptions;
        if (typeof resolvedStringOptions === "object") {
          contextOptions.textOptions = (0, bson_1.serialize)(resolvedStringOptions);
        }
        const valueBuffer = (0, bson_1.serialize)({ v: value });
        const stateMachine = new state_machine_1.StateMachine({
          proxyOptions: this._proxyOptions,
          tlsOptions: this._tlsOptions,
          socketOptions: autoSelectSocketOptions(this._client.s.options)
        });
        const context = this._mongoCrypt.makeExplicitEncryptionContext(valueBuffer, contextOptions);
        const timeoutContext = this._timeoutMS != null ? timeout_1.TimeoutContext.create((0, utils_1.resolveTimeoutOptions)(this._client, { timeoutMS: this._timeoutMS })) : void 0;
        const { v } = (0, bson_1.deserialize)(await stateMachine.execute(this, context, { timeoutContext }));
        return v;
      }
    };
    exports2.ClientEncryption = ClientEncryption;
    function autoSelectSocketOptions(baseOptions) {
      const options = { autoSelectFamily: true };
      if ("autoSelectFamily" in baseOptions) {
        options.autoSelectFamily = baseOptions.autoSelectFamily;
      }
      if ("autoSelectFamilyAttemptTimeout" in baseOptions) {
        options.autoSelectFamilyAttemptTimeout = baseOptions.autoSelectFamilyAttemptTimeout;
      }
      return options;
    }
  }
});

// node_modules/mongodb/lib/client-side-encryption/mongocryptd_manager.js
var require_mongocryptd_manager = __commonJS({
  "node_modules/mongodb/lib/client-side-encryption/mongocryptd_manager.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MongocryptdManager = void 0;
    var error_1 = require_error();
    var MongocryptdManager = class _MongocryptdManager {
      static {
        this.DEFAULT_MONGOCRYPTD_URI = "mongodb://localhost:27020";
      }
      constructor(extraOptions = {}) {
        this.spawnPath = "";
        this.spawnArgs = [];
        this.uri = typeof extraOptions.mongocryptdURI === "string" && extraOptions.mongocryptdURI.length > 0 ? extraOptions.mongocryptdURI : _MongocryptdManager.DEFAULT_MONGOCRYPTD_URI;
        this.bypassSpawn = !!extraOptions.mongocryptdBypassSpawn;
        if (Object.hasOwn(extraOptions, "mongocryptdSpawnPath") && extraOptions.mongocryptdSpawnPath) {
          this.spawnPath = extraOptions.mongocryptdSpawnPath;
        }
        if (Object.hasOwn(extraOptions, "mongocryptdSpawnArgs") && Array.isArray(extraOptions.mongocryptdSpawnArgs)) {
          this.spawnArgs = this.spawnArgs.concat(extraOptions.mongocryptdSpawnArgs);
        }
        if (this.spawnArgs.filter((arg) => typeof arg === "string").every((arg) => arg.indexOf("--idleShutdownTimeoutSecs") < 0)) {
          this.spawnArgs.push("--idleShutdownTimeoutSecs", "60");
        }
      }
      /**
       * Will check to see if a mongocryptd is up. If it is not up, it will attempt
       * to spawn a mongocryptd in a detached process, and then wait for it to be up.
       */
      async spawn() {
        const cmdName = this.spawnPath || "mongocryptd";
        const { spawn } = require("child_process");
        this._child = spawn(cmdName, this.spawnArgs, {
          stdio: "ignore",
          detached: true
        });
        this._child.on("error", () => {
        });
        this._child.unref();
      }
      /**
       * @returns the result of `fn` or rejects with an error.
       */
      async withRespawn(fn) {
        try {
          const result2 = await fn();
          return result2;
        } catch (err) {
          const shouldSpawn = err instanceof error_1.MongoNetworkTimeoutError && !this.bypassSpawn;
          if (!shouldSpawn) {
            throw err;
          }
        }
        await this.spawn();
        const result = await fn();
        return result;
      }
    };
    exports2.MongocryptdManager = MongocryptdManager;
  }
});

// node_modules/mongodb/lib/client-side-encryption/auto_encrypter.js
var require_auto_encrypter = __commonJS({
  "node_modules/mongodb/lib/client-side-encryption/auto_encrypter.js"(exports2) {
    "use strict";
    var _a3;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AutoEncrypter = exports2.AutoEncryptionLoggerLevel = void 0;
    var net = require("net");
    var bson_1 = require_bson2();
    var constants_1 = require_constants2();
    var deps_1 = require_deps();
    var error_1 = require_error();
    var mongo_client_1 = require_mongo_client();
    var utils_1 = require_utils();
    var client_encryption_1 = require_client_encryption();
    var errors_1 = require_errors();
    var mongocryptd_manager_1 = require_mongocryptd_manager();
    var providers_1 = require_providers2();
    var state_machine_1 = require_state_machine();
    exports2.AutoEncryptionLoggerLevel = Object.freeze({
      FatalError: 0,
      Error: 1,
      Warning: 2,
      Info: 3,
      Trace: 4
    });
    var AutoEncrypter = class _AutoEncrypter {
      static {
        _a3 = constants_1.kDecorateResult;
      }
      /** @internal */
      static getMongoCrypt() {
        const encryption = (0, deps_1.getMongoDBClientEncryption)();
        if ("kModuleError" in encryption) {
          throw encryption.kModuleError;
        }
        return encryption.MongoCrypt;
      }
      /**
       * Create an AutoEncrypter
       *
       * **Note**: Do not instantiate this class directly. Rather, supply the relevant options to a MongoClient
       *
       * **Note**: Supplying `options.schemaMap` provides more security than relying on JSON Schemas obtained from the server.
       * It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending unencrypted data that should be encrypted.
       * Schemas supplied in the schemaMap only apply to configuring automatic encryption for Client-Side Field Level Encryption.
       * Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.
       *
       * @example <caption>Create an AutoEncrypter that makes use of mongocryptd</caption>
       * ```ts
       * // Enabling autoEncryption via a MongoClient using mongocryptd
       * const { MongoClient } = require('mongodb');
       * const client = new MongoClient(URL, {
       *   autoEncryption: {
       *     kmsProviders: {
       *       aws: {
       *         accessKeyId: AWS_ACCESS_KEY,
       *         secretAccessKey: AWS_SECRET_KEY
       *       }
       *     }
       *   }
       * });
       * ```
       *
       * await client.connect();
       * // From here on, the client will be encrypting / decrypting automatically
       * @example <caption>Create an AutoEncrypter that makes use of libmongocrypt's CSFLE shared library</caption>
       * ```ts
       * // Enabling autoEncryption via a MongoClient using CSFLE shared library
       * const { MongoClient } = require('mongodb');
       * const client = new MongoClient(URL, {
       *   autoEncryption: {
       *     kmsProviders: {
       *       aws: {}
       *     },
       *     extraOptions: {
       *       cryptSharedLibPath: '/path/to/local/crypt/shared/lib',
       *       cryptSharedLibRequired: true
       *     }
       *   }
       * });
       * ```
       *
       * await client.connect();
       * // From here on, the client will be encrypting / decrypting automatically
       */
      constructor(client, options) {
        this[_a3] = false;
        this._client = client;
        this._bypassEncryption = options.bypassAutoEncryption === true;
        this._keyVaultNamespace = options.keyVaultNamespace || "admin.datakeys";
        this._keyVaultClient = options.keyVaultClient || client;
        this._metaDataClient = options.metadataClient || client;
        this._proxyOptions = options.proxyOptions || {};
        this._tlsOptions = options.tlsOptions || {};
        this._kmsProviders = options.kmsProviders || {};
        this._credentialProviders = options.credentialProviders;
        if (options.credentialProviders?.aws && !(0, providers_1.isEmptyCredentials)("aws", this._kmsProviders)) {
          throw new errors_1.MongoCryptInvalidArgumentError("Can only provide a custom AWS credential provider when the state machine is configured for automatic AWS credential fetching");
        }
        const mongoCryptOptions = {
          errorWrapper: errors_1.defaultErrorWrapper
        };
        if (options.schemaMap) {
          if (bson_1.ByteUtils.isUint8Array(options.schemaMap)) {
            mongoCryptOptions.schemaMap = options.schemaMap;
          } else {
            mongoCryptOptions.schemaMap = (0, bson_1.serialize)(options.schemaMap);
          }
        }
        if (options.encryptedFieldsMap) {
          if (bson_1.ByteUtils.isUint8Array(options.encryptedFieldsMap)) {
            mongoCryptOptions.encryptedFieldsMap = options.encryptedFieldsMap;
          } else {
            mongoCryptOptions.encryptedFieldsMap = (0, bson_1.serialize)(options.encryptedFieldsMap);
          }
        }
        if (bson_1.ByteUtils.isUint8Array(this._kmsProviders)) {
          mongoCryptOptions.kmsProviders = this._kmsProviders;
        } else {
          mongoCryptOptions.kmsProviders = (0, bson_1.serialize)(this._kmsProviders);
        }
        if (options.options?.logger) {
          mongoCryptOptions.logger = options.options.logger;
        }
        if (options.extraOptions && options.extraOptions.cryptSharedLibPath) {
          mongoCryptOptions.cryptSharedLibPath = options.extraOptions.cryptSharedLibPath;
        }
        if (options.bypassQueryAnalysis) {
          mongoCryptOptions.bypassQueryAnalysis = options.bypassQueryAnalysis;
        }
        if (options.keyExpirationMS != null) {
          mongoCryptOptions.keyExpirationMS = options.keyExpirationMS;
        }
        this._bypassMongocryptdAndCryptShared = this._bypassEncryption || !!options.bypassQueryAnalysis;
        if (options.extraOptions && options.extraOptions.cryptSharedLibSearchPaths) {
          mongoCryptOptions.cryptSharedLibSearchPaths = options.extraOptions.cryptSharedLibSearchPaths;
        } else if (!this._bypassMongocryptdAndCryptShared) {
          mongoCryptOptions.cryptSharedLibSearchPaths = ["$SYSTEM"];
        }
        const MongoCrypt = _AutoEncrypter.getMongoCrypt();
        this._mongocrypt = new MongoCrypt(mongoCryptOptions);
        this._contextCounter = 0;
        if (options.extraOptions && options.extraOptions.cryptSharedLibRequired && !this.cryptSharedLibVersionInfo) {
          throw new errors_1.MongoCryptInvalidArgumentError("`cryptSharedLibRequired` set but no crypt_shared library loaded");
        }
        if (!this._bypassMongocryptdAndCryptShared && !this.cryptSharedLibVersionInfo) {
          this._mongocryptdManager = new mongocryptd_manager_1.MongocryptdManager(options.extraOptions);
          const clientOptions = {
            serverSelectionTimeoutMS: 1e4
          };
          if ((options.extraOptions == null || typeof options.extraOptions.mongocryptdURI !== "string") && !net.getDefaultAutoSelectFamily) {
            clientOptions.family = 4;
          }
          if (net.getDefaultAutoSelectFamily) {
            Object.assign(clientOptions, (0, client_encryption_1.autoSelectSocketOptions)(this._client.s?.options ?? {}));
          }
          this._mongocryptdClient = new mongo_client_1.MongoClient(this._mongocryptdManager.uri, clientOptions);
        }
      }
      /**
       * Initializes the auto encrypter by spawning a mongocryptd and connecting to it.
       *
       * This function is a no-op when bypassSpawn is set or the crypt shared library is used.
       */
      async init() {
        if (this._bypassMongocryptdAndCryptShared || this.cryptSharedLibVersionInfo) {
          return;
        }
        if (!this._mongocryptdManager) {
          throw new error_1.MongoRuntimeError("Reached impossible state: mongocryptdManager is undefined when neither bypassSpawn nor the shared lib are specified.");
        }
        if (!this._mongocryptdClient) {
          throw new error_1.MongoRuntimeError("Reached impossible state: mongocryptdClient is undefined when neither bypassSpawn nor the shared lib are specified.");
        }
        if (!this._mongocryptdManager.bypassSpawn) {
          await this._mongocryptdManager.spawn();
        }
        try {
          const client = await this._mongocryptdClient.connect();
          return client;
        } catch (error51) {
          throw new error_1.MongoRuntimeError("Unable to connect to `mongocryptd`, please make sure it is running or in your PATH for auto-spawn", { cause: error51 });
        }
      }
      /**
       * Cleans up the `_mongocryptdClient`, if present.
       */
      async close() {
        await this._mongocryptdClient?.close();
      }
      /**
       * Encrypt a command for a given namespace.
       */
      async encrypt(ns, cmd, options = {}) {
        options.signal?.throwIfAborted();
        if (this._bypassEncryption) {
          return cmd;
        }
        const commandBuffer = (0, bson_1.serialize)(cmd, options);
        const context = this._mongocrypt.makeEncryptionContext(utils_1.MongoDBCollectionNamespace.fromString(ns).db, commandBuffer);
        context.id = this._contextCounter++;
        context.ns = ns;
        context.document = cmd;
        const stateMachine = new state_machine_1.StateMachine({
          promoteValues: false,
          promoteLongs: false,
          proxyOptions: this._proxyOptions,
          tlsOptions: this._tlsOptions,
          socketOptions: (0, client_encryption_1.autoSelectSocketOptions)(this._client.s.options)
        });
        return (0, bson_1.deserialize)(await stateMachine.execute(this, context, options), {
          promoteValues: false,
          promoteLongs: false
        });
      }
      /**
       * Decrypt a command response
       */
      async decrypt(response, options = {}) {
        options.signal?.throwIfAborted();
        const context = this._mongocrypt.makeDecryptionContext(response);
        context.id = this._contextCounter++;
        const stateMachine = new state_machine_1.StateMachine({
          ...options,
          proxyOptions: this._proxyOptions,
          tlsOptions: this._tlsOptions,
          socketOptions: (0, client_encryption_1.autoSelectSocketOptions)(this._client.s.options)
        });
        return await stateMachine.execute(this, context, options);
      }
      /**
       * Ask the user for KMS credentials.
       *
       * This returns anything that looks like the kmsProviders original input
       * option. It can be empty, and any provider specified here will override
       * the original ones.
       */
      async askForKMSCredentials() {
        return await (0, providers_1.refreshKMSCredentials)(this._kmsProviders, this._credentialProviders);
      }
      /**
       * Return the current libmongocrypt's CSFLE shared library version
       * as `{ version: bigint, versionStr: string }`, or `null` if no CSFLE
       * shared library was loaded.
       */
      get cryptSharedLibVersionInfo() {
        return this._mongocrypt.cryptSharedLibVersionInfo;
      }
      static get libmongocryptVersion() {
        return _AutoEncrypter.getMongoCrypt().libmongocryptVersion;
      }
    };
    exports2.AutoEncrypter = AutoEncrypter;
  }
});

// node_modules/mongodb/lib/encrypter.js
var require_encrypter = __commonJS({
  "node_modules/mongodb/lib/encrypter.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Encrypter = void 0;
    var auto_encrypter_1 = require_auto_encrypter();
    var constants_1 = require_constants2();
    var deps_1 = require_deps();
    var error_1 = require_error();
    var mongo_client_1 = require_mongo_client();
    var Encrypter = class {
      constructor(client, uri, options) {
        if (typeof options.autoEncryption !== "object") {
          throw new error_1.MongoInvalidArgumentError('Option "autoEncryption" must be specified');
        }
        this.internalClient = null;
        this.bypassAutoEncryption = !!options.autoEncryption.bypassAutoEncryption;
        this.needsConnecting = false;
        if (options.maxPoolSize === 0 && options.autoEncryption.keyVaultClient == null) {
          options.autoEncryption.keyVaultClient = client;
        } else if (options.autoEncryption.keyVaultClient == null) {
          options.autoEncryption.keyVaultClient = this.getInternalClient(client, uri, options);
        }
        if (this.bypassAutoEncryption) {
          options.autoEncryption.metadataClient = void 0;
        } else if (options.maxPoolSize === 0) {
          options.autoEncryption.metadataClient = client;
        } else {
          options.autoEncryption.metadataClient = this.getInternalClient(client, uri, options);
        }
        if (options.proxyHost) {
          options.autoEncryption.proxyOptions = {
            proxyHost: options.proxyHost,
            proxyPort: options.proxyPort,
            proxyUsername: options.proxyUsername,
            proxyPassword: options.proxyPassword
          };
        }
        this.autoEncrypter = new auto_encrypter_1.AutoEncrypter(client, options.autoEncryption);
      }
      getInternalClient(client, uri, options) {
        let internalClient = this.internalClient;
        if (internalClient == null) {
          const clonedOptions = {};
          for (const key of [
            ...Object.getOwnPropertyNames(options),
            ...Object.getOwnPropertySymbols(options)
          ]) {
            if (["autoEncryption", "minPoolSize", "servers", "caseTranslate", "dbName"].includes(key))
              continue;
            Reflect.set(clonedOptions, key, Reflect.get(options, key));
          }
          clonedOptions.minPoolSize = 0;
          internalClient = new mongo_client_1.MongoClient(uri, clonedOptions);
          this.internalClient = internalClient;
          for (const eventName of constants_1.MONGO_CLIENT_EVENTS) {
            for (const listener of client.listeners(eventName)) {
              internalClient.on(eventName, listener);
            }
          }
          client.on("newListener", (eventName, listener) => {
            internalClient?.on(eventName, listener);
          });
          this.needsConnecting = true;
        }
        return internalClient;
      }
      async connectInternalClient() {
        const internalClient = this.internalClient;
        if (this.needsConnecting && internalClient != null) {
          this.needsConnecting = false;
          await internalClient.connect();
        }
      }
      async close(client) {
        let error51;
        try {
          await this.autoEncrypter.close();
        } catch (autoEncrypterError) {
          error51 = autoEncrypterError;
        }
        const internalClient = this.internalClient;
        if (internalClient != null && client !== internalClient) {
          return await internalClient.close();
        }
        if (error51 != null) {
          throw error51;
        }
      }
      static checkForMongoCrypt() {
        const mongodbClientEncryption = (0, deps_1.getMongoDBClientEncryption)();
        if ("kModuleError" in mongodbClientEncryption) {
          throw new error_1.MongoMissingDependencyError("Auto-encryption requested, but the module is not installed. Please add `mongodb-client-encryption` as a dependency of your project", {
            cause: mongodbClientEncryption["kModuleError"],
            dependencyName: "mongodb-client-encryption"
          });
        }
      }
    };
    exports2.Encrypter = Encrypter;
  }
});

// node_modules/mongodb/lib/runtime_adapters.js
var require_runtime_adapters = __commonJS({
  "node_modules/mongodb/lib/runtime_adapters.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ALLOWED_DRIVER_REQUIRE_PROPERTY_NAME = void 0;
    exports2.resolveRuntimeAdapters = resolveRuntimeAdapters;
    exports2.ALLOWED_DRIVER_REQUIRE_PROPERTY_NAME = "allowedDriverRequire";
    function resolveRuntimeAdapters(options) {
      globalThis[exports2.ALLOWED_DRIVER_REQUIRE_PROPERTY_NAME] = true;
      try {
        const runtime = {
          // eslint-disable-next-line @typescript-eslint/no-require-imports
          os: options.runtimeAdapters?.os ?? require("os")
        };
        return runtime;
      } finally {
        globalThis[exports2.ALLOWED_DRIVER_REQUIRE_PROPERTY_NAME] = false;
      }
    }
  }
});

// node_modules/mongodb/lib/cmap/command_monitoring_events.js
var require_command_monitoring_events = __commonJS({
  "node_modules/mongodb/lib/cmap/command_monitoring_events.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SENSITIVE_COMMANDS = exports2.CommandFailedEvent = exports2.CommandSucceededEvent = exports2.CommandStartedEvent = void 0;
    var constants_1 = require_constants2();
    var utils_1 = require_utils();
    var commands_1 = require_commands();
    var CommandStartedEvent = class {
      /**
       * Create a started event
       *
       * @internal
       * @param pool - the pool that originated the command
       * @param command - the command
       */
      constructor(connection, command, serverConnectionId) {
        this.name = constants_1.COMMAND_STARTED;
        const cmd = extractCommand(command);
        const commandName = extractCommandName(cmd);
        const { address, connectionId, serviceId } = extractConnectionDetails(connection);
        if (exports2.SENSITIVE_COMMANDS.has(commandName)) {
          this.commandObj = {};
          this.commandObj[commandName] = true;
        }
        this.address = address;
        this.connectionId = connectionId;
        this.serviceId = serviceId;
        this.requestId = command.requestId;
        this.databaseName = command.databaseName;
        this.commandName = commandName;
        this.command = maybeRedact(commandName, cmd, cmd);
        this.serverConnectionId = serverConnectionId;
      }
      /* @internal */
      get hasServiceId() {
        return !!this.serviceId;
      }
    };
    exports2.CommandStartedEvent = CommandStartedEvent;
    var CommandSucceededEvent = class {
      /**
       * Create a succeeded event
       *
       * @internal
       * @param pool - the pool that originated the command
       * @param command - the command
       * @param reply - the reply for this command from the server
       * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration
       */
      constructor(connection, command, reply, started, serverConnectionId) {
        this.name = constants_1.COMMAND_SUCCEEDED;
        const cmd = extractCommand(command);
        const commandName = extractCommandName(cmd);
        const { address, connectionId, serviceId } = extractConnectionDetails(connection);
        this.address = address;
        this.connectionId = connectionId;
        this.serviceId = serviceId;
        this.requestId = command.requestId;
        this.commandName = commandName;
        this.duration = (0, utils_1.calculateDurationInMs)(started);
        this.reply = maybeRedact(commandName, cmd, extractReply(reply));
        this.serverConnectionId = serverConnectionId;
        this.databaseName = command.databaseName;
      }
      /* @internal */
      get hasServiceId() {
        return !!this.serviceId;
      }
    };
    exports2.CommandSucceededEvent = CommandSucceededEvent;
    var CommandFailedEvent = class {
      /**
       * Create a failure event
       *
       * @internal
       * @param pool - the pool that originated the command
       * @param command - the command
       * @param error - the generated error or a server error response
       * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration
       */
      constructor(connection, command, error51, started, serverConnectionId) {
        this.name = constants_1.COMMAND_FAILED;
        const cmd = extractCommand(command);
        const commandName = extractCommandName(cmd);
        const { address, connectionId, serviceId } = extractConnectionDetails(connection);
        this.address = address;
        this.connectionId = connectionId;
        this.serviceId = serviceId;
        this.requestId = command.requestId;
        this.commandName = commandName;
        this.duration = (0, utils_1.calculateDurationInMs)(started);
        this.failure = maybeRedact(commandName, cmd, error51);
        this.serverConnectionId = serverConnectionId;
        this.databaseName = command.databaseName;
      }
      /* @internal */
      get hasServiceId() {
        return !!this.serviceId;
      }
    };
    exports2.CommandFailedEvent = CommandFailedEvent;
    exports2.SENSITIVE_COMMANDS = /* @__PURE__ */ new Set([
      "authenticate",
      "saslStart",
      "saslContinue",
      "getnonce",
      "createUser",
      "updateUser",
      "copydbgetnonce",
      "copydbsaslstart",
      "copydb"
    ]);
    var HELLO_COMMANDS = /* @__PURE__ */ new Set(["hello", constants_1.LEGACY_HELLO_COMMAND, constants_1.LEGACY_HELLO_COMMAND_CAMEL_CASE]);
    var extractCommandName = (commandDoc) => Object.keys(commandDoc)[0];
    var collectionName = (command) => command.ns.split(".")[1];
    var maybeRedact = (commandName, commandDoc, result) => exports2.SENSITIVE_COMMANDS.has(commandName) || HELLO_COMMANDS.has(commandName) && commandDoc.speculativeAuthenticate ? {} : result;
    var LEGACY_FIND_QUERY_MAP = {
      $query: "filter",
      $orderby: "sort",
      $hint: "hint",
      $comment: "comment",
      $maxScan: "maxScan",
      $max: "max",
      $min: "min",
      $returnKey: "returnKey",
      $showDiskLoc: "showRecordId",
      $maxTimeMS: "maxTimeMS",
      $snapshot: "snapshot"
    };
    var LEGACY_FIND_OPTIONS_MAP = {
      numberToSkip: "skip",
      numberToReturn: "batchSize",
      returnFieldSelector: "projection"
    };
    function extractCommand(command) {
      if (command instanceof commands_1.OpMsgRequest) {
        const cmd = { ...command.command };
        if (cmd.ops instanceof commands_1.DocumentSequence) {
          cmd.ops = cmd.ops.documents;
        }
        if (cmd.nsInfo instanceof commands_1.DocumentSequence) {
          cmd.nsInfo = cmd.nsInfo.documents;
        }
        return cmd;
      }
      if (command.query?.$query) {
        let result;
        if (command.ns === "admin.$cmd") {
          result = Object.assign({}, command.query.$query);
        } else {
          result = { find: collectionName(command) };
          Object.keys(LEGACY_FIND_QUERY_MAP).forEach((key) => {
            if (command.query[key] != null) {
              result[LEGACY_FIND_QUERY_MAP[key]] = { ...command.query[key] };
            }
          });
        }
        Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach((key) => {
          const legacyKey = key;
          if (command[legacyKey] != null) {
            result[LEGACY_FIND_OPTIONS_MAP[legacyKey]] = command[legacyKey];
          }
        });
        return result;
      }
      let clonedQuery = {};
      const clonedCommand = { ...command };
      if (command.query) {
        clonedQuery = { ...command.query };
        clonedCommand.query = clonedQuery;
      }
      return command.query ? clonedQuery : clonedCommand;
    }
    function extractReply(reply) {
      if (!reply) {
        return reply;
      }
      return reply.result ? reply.result : reply;
    }
    function extractConnectionDetails(connection) {
      let connectionId;
      if ("id" in connection) {
        connectionId = connection.id;
      }
      return {
        address: connection.address,
        serviceId: connection.serviceId,
        connectionId
      };
    }
  }
});

// node_modules/mongodb/lib/sdam/server_description.js
var require_server_description = __commonJS({
  "node_modules/mongodb/lib/sdam/server_description.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ServerDescription = void 0;
    exports2.parseServerType = parseServerType;
    exports2.compareTopologyVersion = compareTopologyVersion;
    var bson_1 = require_bson2();
    var error_1 = require_error();
    var utils_1 = require_utils();
    var common_1 = require_common();
    var WRITABLE_SERVER_TYPES = /* @__PURE__ */ new Set([
      common_1.ServerType.RSPrimary,
      common_1.ServerType.Standalone,
      common_1.ServerType.Mongos,
      common_1.ServerType.LoadBalancer
    ]);
    var DATA_BEARING_SERVER_TYPES = /* @__PURE__ */ new Set([
      common_1.ServerType.RSPrimary,
      common_1.ServerType.RSSecondary,
      common_1.ServerType.Mongos,
      common_1.ServerType.Standalone,
      common_1.ServerType.LoadBalancer
    ]);
    var ServerDescription = class {
      /**
       * Create a ServerDescription
       * @internal
       *
       * @param address - The address of the server
       * @param hello - An optional hello response for this server
       */
      constructor(address, hello, options = {}) {
        if (address == null || address === "") {
          throw new error_1.MongoRuntimeError("ServerDescription must be provided with a non-empty address");
        }
        this.address = typeof address === "string" ? utils_1.HostAddress.fromString(address).toString() : address.toString();
        this.type = parseServerType(hello, options);
        this.hosts = hello?.hosts?.map((host) => host.toLowerCase()) ?? [];
        this.passives = hello?.passives?.map((host) => host.toLowerCase()) ?? [];
        this.arbiters = hello?.arbiters?.map((host) => host.toLowerCase()) ?? [];
        this.tags = hello?.tags ?? {};
        this.minWireVersion = hello?.minWireVersion ?? 0;
        this.maxWireVersion = hello?.maxWireVersion ?? 0;
        this.roundTripTime = options?.roundTripTime ?? -1;
        this.minRoundTripTime = options?.minRoundTripTime ?? 0;
        this.lastUpdateTime = (0, utils_1.processTimeMS)();
        this.lastWriteDate = hello?.lastWrite?.lastWriteDate ?? 0;
        this.error = options.error ?? null;
        this.error?.stack;
        this.topologyVersion = this.error?.topologyVersion ?? hello?.topologyVersion ?? null;
        this.setName = hello?.setName ?? null;
        this.setVersion = hello?.setVersion ?? null;
        this.electionId = hello?.electionId ?? null;
        this.logicalSessionTimeoutMinutes = hello?.logicalSessionTimeoutMinutes ?? null;
        this.maxMessageSizeBytes = hello?.maxMessageSizeBytes ?? null;
        this.maxWriteBatchSize = hello?.maxWriteBatchSize ?? null;
        this.maxBsonObjectSize = hello?.maxBsonObjectSize ?? null;
        this.primary = hello?.primary ?? null;
        this.me = hello?.me?.toLowerCase() ?? null;
        this.$clusterTime = hello?.$clusterTime ?? null;
        this.iscryptd = Boolean(hello?.iscryptd);
      }
      get hostAddress() {
        return utils_1.HostAddress.fromString(this.address);
      }
      get allHosts() {
        return this.hosts.concat(this.arbiters).concat(this.passives);
      }
      /** Is this server available for reads*/
      get isReadable() {
        return this.type === common_1.ServerType.RSSecondary || this.isWritable;
      }
      /** Is this server data bearing */
      get isDataBearing() {
        return DATA_BEARING_SERVER_TYPES.has(this.type);
      }
      /** Is this server available for writes */
      get isWritable() {
        return WRITABLE_SERVER_TYPES.has(this.type);
      }
      get host() {
        const chopLength = `:${this.port}`.length;
        return this.address.slice(0, -chopLength);
      }
      get port() {
        const port = this.address.split(":").pop();
        return port ? Number.parseInt(port, 10) : 27017;
      }
      /**
       * Determines if another `ServerDescription` is equal to this one per the rules defined in the SDAM specification.
       * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.md
       */
      equals(other) {
        const topologyVersionsEqual = this.topologyVersion === other?.topologyVersion || compareTopologyVersion(this.topologyVersion, other?.topologyVersion) === 0;
        const electionIdsEqual = this.electionId != null && other?.electionId != null ? (0, utils_1.compareObjectId)(this.electionId, other.electionId) === 0 : this.electionId === other?.electionId;
        return other != null && other.iscryptd === this.iscryptd && (0, utils_1.errorStrictEqual)(this.error, other.error) && this.type === other.type && this.minWireVersion === other.minWireVersion && (0, utils_1.arrayStrictEqual)(this.hosts, other.hosts) && tagsStrictEqual(this.tags, other.tags) && this.setName === other.setName && this.setVersion === other.setVersion && electionIdsEqual && this.primary === other.primary && this.logicalSessionTimeoutMinutes === other.logicalSessionTimeoutMinutes && topologyVersionsEqual;
      }
    };
    exports2.ServerDescription = ServerDescription;
    function parseServerType(hello, options) {
      if (options?.loadBalanced) {
        return common_1.ServerType.LoadBalancer;
      }
      if (!hello || !hello.ok) {
        return common_1.ServerType.Unknown;
      }
      if (hello.isreplicaset) {
        return common_1.ServerType.RSGhost;
      }
      if (hello.msg && hello.msg === "isdbgrid") {
        return common_1.ServerType.Mongos;
      }
      if (hello.setName) {
        if (hello.hidden) {
          return common_1.ServerType.RSOther;
        } else if (hello.isWritablePrimary) {
          return common_1.ServerType.RSPrimary;
        } else if (hello.secondary) {
          return common_1.ServerType.RSSecondary;
        } else if (hello.arbiterOnly) {
          return common_1.ServerType.RSArbiter;
        } else {
          return common_1.ServerType.RSOther;
        }
      }
      return common_1.ServerType.Standalone;
    }
    function tagsStrictEqual(tags, tags2) {
      const tagsKeys = Object.keys(tags);
      const tags2Keys = Object.keys(tags2);
      return tagsKeys.length === tags2Keys.length && tagsKeys.every((key) => tags2[key] === tags[key]);
    }
    function compareTopologyVersion(currentTv, newTv) {
      if (currentTv == null || newTv == null) {
        return -1;
      }
      if (!currentTv.processId.equals(newTv.processId)) {
        return -1;
      }
      const currentCounter = typeof currentTv.counter === "bigint" ? bson_1.Long.fromBigInt(currentTv.counter) : bson_1.Long.isLong(currentTv.counter) ? currentTv.counter : bson_1.Long.fromNumber(currentTv.counter);
      const newCounter = typeof newTv.counter === "bigint" ? bson_1.Long.fromBigInt(newTv.counter) : bson_1.Long.isLong(newTv.counter) ? newTv.counter : bson_1.Long.fromNumber(newTv.counter);
      return currentCounter.compare(newCounter);
    }
  }
});

// node_modules/mongodb/lib/cmap/stream_description.js
var require_stream_description = __commonJS({
  "node_modules/mongodb/lib/cmap/stream_description.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.StreamDescription = void 0;
    var bson_1 = require_bson2();
    var common_1 = require_common();
    var server_description_1 = require_server_description();
    var RESPONSE_FIELDS = [
      "minWireVersion",
      "maxWireVersion",
      "maxBsonObjectSize",
      "maxMessageSizeBytes",
      "maxWriteBatchSize",
      "logicalSessionTimeoutMinutes"
    ];
    var StreamDescription = class {
      constructor(address, options) {
        this.hello = null;
        this.address = address;
        this.type = common_1.ServerType.Unknown;
        this.minWireVersion = void 0;
        this.maxWireVersion = void 0;
        this.maxBsonObjectSize = 16777216;
        this.maxMessageSizeBytes = 48e6;
        this.maxWriteBatchSize = 1e5;
        this.logicalSessionTimeoutMinutes = options?.logicalSessionTimeoutMinutes;
        this.loadBalanced = !!options?.loadBalanced;
        this.compressors = options && options.compressors && Array.isArray(options.compressors) ? options.compressors : [];
        this.serverConnectionId = null;
      }
      receiveResponse(response) {
        if (response == null) {
          return;
        }
        this.hello = response;
        this.type = (0, server_description_1.parseServerType)(response);
        if ("connectionId" in response) {
          this.serverConnectionId = this.parseServerConnectionID(response.connectionId);
        } else {
          this.serverConnectionId = null;
        }
        for (const field of RESPONSE_FIELDS) {
          if (response[field] != null) {
            this[field] = response[field];
          }
          if ("__nodejs_mock_server__" in response) {
            this.__nodejs_mock_server__ = response["__nodejs_mock_server__"];
          }
        }
        if (response.compression) {
          this.compressor = this.compressors.filter((c) => response.compression?.includes(c))[0];
        }
      }
      /* @internal */
      parseServerConnectionID(serverConnectionId) {
        return bson_1.Long.isLong(serverConnectionId) ? serverConnectionId.toBigInt() : (
          // @ts-expect-error: Doubles are coercible to number
          BigInt(serverConnectionId)
        );
      }
    };
    exports2.StreamDescription = StreamDescription;
  }
});

// node_modules/mongodb/lib/cmap/wire_protocol/on_data.js
var require_on_data = __commonJS({
  "node_modules/mongodb/lib/cmap/wire_protocol/on_data.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.onData = onData;
    var utils_1 = require_utils();
    function onData(emitter, { timeoutContext, signal }) {
      signal?.throwIfAborted();
      const unconsumedEvents = new utils_1.List();
      const unconsumedPromises = new utils_1.List();
      let error51 = null;
      let finished = false;
      const iterator = {
        next() {
          const value = unconsumedEvents.shift();
          if (value != null) {
            return Promise.resolve({ value, done: false });
          }
          if (error51 != null) {
            const p = Promise.reject(error51);
            error51 = null;
            return p;
          }
          if (finished)
            return closeHandler();
          const { promise: promise2, resolve: resolve2, reject } = (0, utils_1.promiseWithResolvers)();
          unconsumedPromises.push({ resolve: resolve2, reject });
          return promise2;
        },
        return() {
          return closeHandler();
        },
        throw(err) {
          errorHandler(err);
          return Promise.resolve({ value: void 0, done: true });
        },
        [Symbol.asyncIterator]() {
          return this;
        },
        async [Symbol.asyncDispose]() {
          await closeHandler();
        }
      };
      emitter.on("data", eventHandler);
      emitter.on("error", errorHandler);
      const abortListener = (0, utils_1.addAbortListener)(signal, function() {
        errorHandler(this.reason);
      });
      const timeoutForSocketRead = timeoutContext?.timeoutForSocketRead;
      timeoutForSocketRead?.throwIfExpired();
      timeoutForSocketRead?.then(void 0, errorHandler);
      return iterator;
      function eventHandler(value) {
        const promise2 = unconsumedPromises.shift();
        if (promise2 != null)
          promise2.resolve({ value, done: false });
        else
          unconsumedEvents.push(value);
      }
      function errorHandler(err) {
        const promise2 = unconsumedPromises.shift();
        if (promise2 != null)
          promise2.reject(err);
        else
          error51 = err;
        void closeHandler();
      }
      function closeHandler() {
        emitter.off("data", eventHandler);
        emitter.off("error", errorHandler);
        abortListener?.[utils_1.kDispose]();
        finished = true;
        timeoutForSocketRead?.clear();
        const doneResult = { value: void 0, done: finished };
        for (const promise2 of unconsumedPromises) {
          promise2.resolve(doneResult);
        }
        return Promise.resolve(doneResult);
      }
    }
  }
});

// node_modules/mongodb/lib/sdam/topology_description.js
var require_topology_description = __commonJS({
  "node_modules/mongodb/lib/sdam/topology_description.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.TopologyDescription = void 0;
    var bson_1 = require_bson2();
    var WIRE_CONSTANTS = require_constants();
    var error_1 = require_error();
    var utils_1 = require_utils();
    var common_1 = require_common();
    var server_description_1 = require_server_description();
    var MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION;
    var MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION;
    var MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION;
    var MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION;
    var MONGOS_OR_UNKNOWN = /* @__PURE__ */ new Set([common_1.ServerType.Mongos, common_1.ServerType.Unknown]);
    var MONGOS_OR_STANDALONE = /* @__PURE__ */ new Set([common_1.ServerType.Mongos, common_1.ServerType.Standalone]);
    var NON_PRIMARY_RS_MEMBERS = /* @__PURE__ */ new Set([
      common_1.ServerType.RSSecondary,
      common_1.ServerType.RSArbiter,
      common_1.ServerType.RSOther
    ]);
    var TopologyDescription = class _TopologyDescription {
      /**
       * Create a TopologyDescription
       */
      constructor(topologyType, serverDescriptions = null, setName = null, maxSetVersion = null, maxElectionId = null, commonWireVersion = null, options = null) {
        options = options ?? {};
        this.type = topologyType ?? common_1.TopologyType.Unknown;
        this.servers = serverDescriptions ?? /* @__PURE__ */ new Map();
        this.stale = false;
        this.compatible = true;
        this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 0;
        this.localThresholdMS = options.localThresholdMS ?? 15;
        this.setName = setName ?? null;
        this.maxElectionId = maxElectionId ?? null;
        this.maxSetVersion = maxSetVersion ?? null;
        this.commonWireVersion = commonWireVersion ?? 0;
        for (const serverDescription of this.servers.values()) {
          if (serverDescription.type === common_1.ServerType.Unknown || serverDescription.type === common_1.ServerType.LoadBalancer) {
            continue;
          }
          if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) {
            this.compatible = false;
            this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${serverDescription.minWireVersion}, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`;
          }
          if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) {
            this.compatible = false;
            this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${serverDescription.maxWireVersion}, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`;
            break;
          }
        }
        this.logicalSessionTimeoutMinutes = null;
        for (const [, server] of this.servers) {
          if (server.isReadable) {
            if (server.logicalSessionTimeoutMinutes == null) {
              this.logicalSessionTimeoutMinutes = null;
              break;
            }
            if (this.logicalSessionTimeoutMinutes == null) {
              this.logicalSessionTimeoutMinutes = server.logicalSessionTimeoutMinutes;
              continue;
            }
            this.logicalSessionTimeoutMinutes = Math.min(this.logicalSessionTimeoutMinutes, server.logicalSessionTimeoutMinutes);
          }
        }
      }
      /**
       * Returns a new TopologyDescription based on the SrvPollingEvent
       * @internal
       */
      updateFromSrvPollingEvent(ev, srvMaxHosts = 0) {
        const incomingHostnames = ev.hostnames();
        const currentHostnames = new Set(this.servers.keys());
        const hostnamesToAdd = new Set(incomingHostnames);
        const hostnamesToRemove = /* @__PURE__ */ new Set();
        for (const hostname3 of currentHostnames) {
          hostnamesToAdd.delete(hostname3);
          if (!incomingHostnames.has(hostname3)) {
            hostnamesToRemove.add(hostname3);
          }
        }
        if (hostnamesToAdd.size === 0 && hostnamesToRemove.size === 0) {
          return this;
        }
        const serverDescriptions = new Map(this.servers);
        for (const removedHost of hostnamesToRemove) {
          serverDescriptions.delete(removedHost);
        }
        if (hostnamesToAdd.size > 0) {
          if (srvMaxHosts === 0) {
            for (const hostToAdd of hostnamesToAdd) {
              serverDescriptions.set(hostToAdd, new server_description_1.ServerDescription(hostToAdd));
            }
          } else if (serverDescriptions.size < srvMaxHosts) {
            const selectedHosts = (0, utils_1.shuffle)(hostnamesToAdd, srvMaxHosts - serverDescriptions.size);
            for (const selectedHostToAdd of selectedHosts) {
              serverDescriptions.set(selectedHostToAdd, new server_description_1.ServerDescription(selectedHostToAdd));
            }
          }
        }
        return new _TopologyDescription(this.type, serverDescriptions, this.setName, this.maxSetVersion, this.maxElectionId, this.commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS });
      }
      /**
       * Returns a copy of this description updated with a given ServerDescription
       * @internal
       */
      update(serverDescription) {
        const address = serverDescription.address;
        let { type: topologyType, setName, maxSetVersion, maxElectionId, commonWireVersion } = this;
        const serverType = serverDescription.type;
        const serverDescriptions = new Map(this.servers);
        if (serverDescription.maxWireVersion !== 0) {
          if (commonWireVersion === 0) {
            commonWireVersion = serverDescription.maxWireVersion;
          } else {
            commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion);
          }
        }
        if (typeof serverDescription.setName === "string" && typeof setName === "string" && serverDescription.setName !== setName) {
          if (topologyType === common_1.TopologyType.Single) {
            serverDescription = new server_description_1.ServerDescription(address);
          } else {
            serverDescriptions.delete(address);
          }
        }
        serverDescriptions.set(address, serverDescription);
        if (topologyType === common_1.TopologyType.Single) {
          return new _TopologyDescription(common_1.TopologyType.Single, serverDescriptions, setName, maxSetVersion, maxElectionId, commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS });
        }
        if (topologyType === common_1.TopologyType.Unknown) {
          if (serverType === common_1.ServerType.Standalone && this.servers.size !== 1) {
            serverDescriptions.delete(address);
          } else {
            topologyType = topologyTypeForServerType(serverType);
          }
        }
        if (topologyType === common_1.TopologyType.Sharded) {
          if (!MONGOS_OR_UNKNOWN.has(serverType)) {
            serverDescriptions.delete(address);
          }
        }
        if (topologyType === common_1.TopologyType.ReplicaSetNoPrimary) {
          if (MONGOS_OR_STANDALONE.has(serverType)) {
            serverDescriptions.delete(address);
          }
          if (serverType === common_1.ServerType.RSPrimary) {
            const result = updateRsFromPrimary(serverDescriptions, serverDescription, setName, maxSetVersion, maxElectionId);
            topologyType = result[0];
            setName = result[1];
            maxSetVersion = result[2];
            maxElectionId = result[3];
          } else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) {
            const result = updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName);
            topologyType = result[0];
            setName = result[1];
          }
        }
        if (topologyType === common_1.TopologyType.ReplicaSetWithPrimary) {
          if (MONGOS_OR_STANDALONE.has(serverType)) {
            serverDescriptions.delete(address);
            topologyType = checkHasPrimary(serverDescriptions);
          } else if (serverType === common_1.ServerType.RSPrimary) {
            const result = updateRsFromPrimary(serverDescriptions, serverDescription, setName, maxSetVersion, maxElectionId);
            topologyType = result[0];
            setName = result[1];
            maxSetVersion = result[2];
            maxElectionId = result[3];
          } else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) {
            topologyType = updateRsWithPrimaryFromMember(serverDescriptions, serverDescription, setName);
          } else {
            topologyType = checkHasPrimary(serverDescriptions);
          }
        }
        return new _TopologyDescription(topologyType, serverDescriptions, setName, maxSetVersion, maxElectionId, commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS });
      }
      get error() {
        const descriptionsWithError = Array.from(this.servers.values()).filter((sd) => sd.error);
        if (descriptionsWithError.length > 0) {
          return descriptionsWithError[0].error;
        }
        return null;
      }
      /**
       * Determines if the topology description has any known servers
       */
      get hasKnownServers() {
        return Array.from(this.servers.values()).some((sd) => sd.type !== common_1.ServerType.Unknown);
      }
      /**
       * Determines if this topology description has a data-bearing server available.
       */
      get hasDataBearingServers() {
        return Array.from(this.servers.values()).some((sd) => sd.isDataBearing);
      }
      /**
       * Determines if the topology has a definition for the provided address
       * @internal
       */
      hasServer(address) {
        return this.servers.has(address);
      }
      /**
       * Returns a JSON-serializable representation of the TopologyDescription.  This is primarily
       * intended for use with JSON.stringify().
       *
       * This method will not throw.
       */
      toJSON() {
        return bson_1.EJSON.serialize(this);
      }
    };
    exports2.TopologyDescription = TopologyDescription;
    function topologyTypeForServerType(serverType) {
      switch (serverType) {
        case common_1.ServerType.Standalone:
          return common_1.TopologyType.Single;
        case common_1.ServerType.Mongos:
          return common_1.TopologyType.Sharded;
        case common_1.ServerType.RSPrimary:
          return common_1.TopologyType.ReplicaSetWithPrimary;
        case common_1.ServerType.RSOther:
        case common_1.ServerType.RSSecondary:
          return common_1.TopologyType.ReplicaSetNoPrimary;
        default:
          return common_1.TopologyType.Unknown;
      }
    }
    function updateRsFromPrimary(serverDescriptions, serverDescription, setName = null, maxSetVersion = null, maxElectionId = null) {
      const setVersionElectionIdMismatch = (serverDescription2, maxSetVersion2, maxElectionId2) => {
        return `primary marked stale due to electionId/setVersion mismatch: server setVersion: ${serverDescription2.setVersion}, server electionId: ${serverDescription2.electionId}, topology setVersion: ${maxSetVersion2}, topology electionId: ${maxElectionId2}`;
      };
      setName = setName || serverDescription.setName;
      if (setName !== serverDescription.setName) {
        serverDescriptions.delete(serverDescription.address);
        return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];
      }
      if (serverDescription.maxWireVersion >= 17) {
        const electionIdComparison = (0, utils_1.compareObjectId)(maxElectionId, serverDescription.electionId);
        const maxElectionIdIsEqual = electionIdComparison === 0;
        const maxElectionIdIsLess = electionIdComparison === -1;
        const maxSetVersionIsLessOrEqual = (maxSetVersion ?? -1) <= (serverDescription.setVersion ?? -1);
        if (maxElectionIdIsLess || maxElectionIdIsEqual && maxSetVersionIsLessOrEqual) {
          maxElectionId = serverDescription.electionId;
          maxSetVersion = serverDescription.setVersion;
        } else {
          serverDescriptions.set(serverDescription.address, new server_description_1.ServerDescription(serverDescription.address, void 0, {
            error: new error_1.MongoStalePrimaryError(setVersionElectionIdMismatch(serverDescription, maxSetVersion, maxElectionId))
          }));
          return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];
        }
      } else {
        const electionId = serverDescription.electionId ? serverDescription.electionId : null;
        if (serverDescription.setVersion && electionId) {
          if (maxSetVersion && maxElectionId) {
            if (maxSetVersion > serverDescription.setVersion || (0, utils_1.compareObjectId)(maxElectionId, electionId) > 0) {
              serverDescriptions.set(serverDescription.address, new server_description_1.ServerDescription(serverDescription.address, void 0, {
                error: new error_1.MongoStalePrimaryError(setVersionElectionIdMismatch(serverDescription, maxSetVersion, maxElectionId))
              }));
              return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];
            }
          }
          maxElectionId = serverDescription.electionId;
        }
        if (serverDescription.setVersion != null && (maxSetVersion == null || serverDescription.setVersion > maxSetVersion)) {
          maxSetVersion = serverDescription.setVersion;
        }
      }
      for (const [address, server] of serverDescriptions) {
        if (server.type === common_1.ServerType.RSPrimary && server.address !== serverDescription.address) {
          serverDescriptions.set(address, new server_description_1.ServerDescription(server.address, void 0, {
            error: new error_1.MongoStalePrimaryError("primary marked stale due to discovery of newer primary")
          }));
          break;
        }
      }
      serverDescription.allHosts.forEach((address) => {
        if (!serverDescriptions.has(address)) {
          serverDescriptions.set(address, new server_description_1.ServerDescription(address));
        }
      });
      const currentAddresses = Array.from(serverDescriptions.keys());
      const responseAddresses = serverDescription.allHosts;
      currentAddresses.filter((addr) => responseAddresses.indexOf(addr) === -1).forEach((address) => {
        serverDescriptions.delete(address);
      });
      return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];
    }
    function updateRsWithPrimaryFromMember(serverDescriptions, serverDescription, setName = null) {
      if (setName == null) {
        throw new error_1.MongoRuntimeError('Argument "setName" is required if connected to a replica set');
      }
      if (setName !== serverDescription.setName || serverDescription.me && serverDescription.address !== serverDescription.me) {
        serverDescriptions.delete(serverDescription.address);
      }
      return checkHasPrimary(serverDescriptions);
    }
    function updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName = null) {
      const topologyType = common_1.TopologyType.ReplicaSetNoPrimary;
      setName = setName ?? serverDescription.setName;
      if (setName !== serverDescription.setName) {
        serverDescriptions.delete(serverDescription.address);
        return [topologyType, setName];
      }
      serverDescription.allHosts.forEach((address) => {
        if (!serverDescriptions.has(address)) {
          serverDescriptions.set(address, new server_description_1.ServerDescription(address));
        }
      });
      if (serverDescription.me && serverDescription.address !== serverDescription.me) {
        serverDescriptions.delete(serverDescription.address);
      }
      return [topologyType, setName];
    }
    function checkHasPrimary(serverDescriptions) {
      for (const serverDescription of serverDescriptions.values()) {
        if (serverDescription.type === common_1.ServerType.RSPrimary) {
          return common_1.TopologyType.ReplicaSetWithPrimary;
        }
      }
      return common_1.TopologyType.ReplicaSetNoPrimary;
    }
  }
});

// node_modules/mongodb/lib/cmap/wire_protocol/shared.js
var require_shared = __commonJS({
  "node_modules/mongodb/lib/cmap/wire_protocol/shared.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getReadPreference = getReadPreference;
    exports2.isSharded = isSharded;
    var error_1 = require_error();
    var read_preference_1 = require_read_preference();
    var common_1 = require_common();
    var topology_description_1 = require_topology_description();
    function getReadPreference(options) {
      let readPreference = options?.readPreference ?? read_preference_1.ReadPreference.primary;
      if (typeof readPreference === "string") {
        readPreference = read_preference_1.ReadPreference.fromString(readPreference);
      }
      if (!(readPreference instanceof read_preference_1.ReadPreference)) {
        throw new error_1.MongoInvalidArgumentError('Option "readPreference" must be a ReadPreference instance');
      }
      return readPreference;
    }
    function isSharded(topologyOrServer) {
      if (topologyOrServer == null) {
        return false;
      }
      if (topologyOrServer.description && topologyOrServer.description.type === common_1.ServerType.Mongos) {
        return true;
      }
      if (topologyOrServer.description && topologyOrServer.description instanceof topology_description_1.TopologyDescription) {
        const servers = Array.from(topologyOrServer.description.servers.values());
        return servers.some((server) => server.type === common_1.ServerType.Mongos);
      }
      return false;
    }
  }
});

// node_modules/mongodb/lib/cmap/connection.js
var require_connection = __commonJS({
  "node_modules/mongodb/lib/cmap/connection.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CryptoConnection = exports2.SizedMessageTransform = exports2.Connection = void 0;
    exports2.hasSessionSupport = hasSessionSupport;
    var stream_1 = require("stream");
    var timers_1 = require("timers");
    var bson_1 = require_bson2();
    var constants_1 = require_constants2();
    var error_1 = require_error();
    var mongo_logger_1 = require_mongo_logger();
    var mongo_types_1 = require_mongo_types();
    var read_preference_1 = require_read_preference();
    var common_1 = require_common();
    var sessions_1 = require_sessions();
    var timeout_1 = require_timeout();
    var utils_1 = require_utils();
    var command_monitoring_events_1 = require_command_monitoring_events();
    var commands_1 = require_commands();
    var stream_description_1 = require_stream_description();
    var compression_1 = require_compression();
    var on_data_1 = require_on_data();
    var responses_1 = require_responses();
    var shared_1 = require_shared();
    function hasSessionSupport(conn) {
      const description = conn.description;
      return description.logicalSessionTimeoutMinutes != null;
    }
    function streamIdentifier(stream, options) {
      if (options.proxyHost) {
        return options.hostAddress.toString();
      }
      const { remoteAddress, remotePort } = stream;
      if (typeof remoteAddress === "string" && typeof remotePort === "number") {
        return utils_1.HostAddress.fromHostPort(remoteAddress, remotePort).toString();
      }
      return bson_1.ByteUtils.toHex((0, utils_1.uuidV4)());
    }
    var Connection = class _Connection extends mongo_types_1.TypedEventEmitter {
      static {
        this.COMMAND_STARTED = constants_1.COMMAND_STARTED;
      }
      static {
        this.COMMAND_SUCCEEDED = constants_1.COMMAND_SUCCEEDED;
      }
      static {
        this.COMMAND_FAILED = constants_1.COMMAND_FAILED;
      }
      static {
        this.CLUSTER_TIME_RECEIVED = constants_1.CLUSTER_TIME_RECEIVED;
      }
      static {
        this.CLOSE = constants_1.CLOSE;
      }
      static {
        this.PINNED = constants_1.PINNED;
      }
      static {
        this.UNPINNED = constants_1.UNPINNED;
      }
      constructor(stream, options) {
        super();
        this.lastHelloMS = -1;
        this.helloOk = false;
        this.delayedTimeoutId = null;
        this.closed = false;
        this.clusterTime = null;
        this.error = null;
        this.dataEvents = null;
        this.on("error", utils_1.noop);
        this.socket = stream;
        this.id = options.id;
        this.address = streamIdentifier(stream, options);
        this.socketTimeoutMS = options.socketTimeoutMS ?? 0;
        this.monitorCommands = options.monitorCommands;
        this.serverApi = options.serverApi;
        this.mongoLogger = options.mongoLogger;
        this.established = false;
        this.description = new stream_description_1.StreamDescription(this.address, options);
        this.generation = options.generation;
        this.lastUseTime = (0, utils_1.processTimeMS)();
        this.messageStream = this.socket.on("error", this.onSocketError.bind(this)).pipe(new SizedMessageTransform({ connection: this })).on("error", this.onTransformError.bind(this));
        this.socket.on("close", this.onClose.bind(this));
        this.socket.on("timeout", this.onTimeout.bind(this));
        this.messageStream.pause();
      }
      get hello() {
        return this.description.hello;
      }
      // the `connect` method stores the result of the handshake hello on the connection
      set hello(response) {
        this.description.receiveResponse(response);
        Object.freeze(this.description);
      }
      get serviceId() {
        return this.hello?.serviceId;
      }
      get loadBalanced() {
        return this.description.loadBalanced;
      }
      get idleTime() {
        return (0, utils_1.calculateDurationInMs)(this.lastUseTime);
      }
      get hasSessionSupport() {
        return this.description.logicalSessionTimeoutMinutes != null;
      }
      get supportsOpMsg() {
        return this.description != null && // TODO(NODE-6672,NODE-6287): This guard is primarily for maxWireVersion = 0
        (0, utils_1.maxWireVersion)(this) >= 6 && !this.description.__nodejs_mock_server__;
      }
      get shouldEmitAndLogCommand() {
        return (this.monitorCommands || this.established && !this.authContext?.reauthenticating && this.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.COMMAND, mongo_logger_1.SeverityLevel.DEBUG)) ?? false;
      }
      markAvailable() {
        this.lastUseTime = (0, utils_1.processTimeMS)();
      }
      onSocketError(cause) {
        this.onError(new error_1.MongoNetworkError(cause.message, { cause }));
      }
      onTransformError(error51) {
        this.onError(error51);
      }
      onError(error51) {
        this.cleanup(error51);
      }
      onClose() {
        const message = `connection ${this.id} to ${this.address} closed`;
        this.cleanup(new error_1.MongoNetworkError(message));
      }
      onTimeout() {
        this.delayedTimeoutId = (0, timers_1.setTimeout)(() => {
          const message = `connection ${this.id} to ${this.address} timed out`;
          const beforeHandshake = this.hello == null;
          this.cleanup(new error_1.MongoNetworkTimeoutError(message, { beforeHandshake }));
        }, 1).unref();
      }
      destroy() {
        if (this.closed) {
          return;
        }
        this.removeAllListeners(_Connection.PINNED);
        this.removeAllListeners(_Connection.UNPINNED);
        const message = `connection ${this.id} to ${this.address} closed`;
        this.cleanup(new error_1.MongoNetworkError(message));
      }
      /**
       * A method that cleans up the connection.  When `force` is true, this method
       * forcibly destroys the socket.
       *
       * If an error is provided, any in-flight operations will be closed with the error.
       *
       * This method does nothing if the connection is already closed.
       */
      cleanup(error51) {
        if (this.closed) {
          return;
        }
        this.socket.destroy();
        this.error = error51;
        this.dataEvents?.throw(error51).then(void 0, utils_1.squashError);
        this.closed = true;
        this.emit(_Connection.CLOSE);
      }
      prepareCommand(db, command, options) {
        let cmd = { ...command };
        const readPreference = (0, shared_1.getReadPreference)(options);
        const session = options?.session;
        let clusterTime = this.clusterTime;
        if (this.serverApi) {
          const { version: version2, strict, deprecationErrors } = this.serverApi;
          cmd.apiVersion = version2;
          if (strict != null)
            cmd.apiStrict = strict;
          if (deprecationErrors != null)
            cmd.apiDeprecationErrors = deprecationErrors;
        }
        if (this.hasSessionSupport && session) {
          if (session.clusterTime && clusterTime && session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime)) {
            clusterTime = session.clusterTime;
          }
          const sessionError = (0, sessions_1.applySession)(session, cmd, options);
          if (sessionError)
            throw sessionError;
        } else if (session?.explicit) {
          throw new error_1.MongoCompatibilityError("Current topology does not support sessions");
        }
        if (clusterTime) {
          cmd.$clusterTime = clusterTime;
        }
        if (this.description.type !== common_1.ServerType.Standalone) {
          if (!(0, shared_1.isSharded)(this) && !this.description.loadBalanced && this.supportsOpMsg && options.directConnection === true && readPreference?.mode === "primary") {
            cmd.$readPreference = read_preference_1.ReadPreference.primaryPreferred.toJSON();
          } else if ((0, shared_1.isSharded)(this) && !this.supportsOpMsg && readPreference?.mode !== "primary") {
            cmd = {
              $query: cmd,
              $readPreference: readPreference.toJSON()
            };
          } else if (readPreference?.mode !== "primary") {
            cmd.$readPreference = readPreference.toJSON();
          }
        }
        const commandOptions = {
          numberToSkip: 0,
          numberToReturn: -1,
          checkKeys: false,
          // This value is not overridable
          secondaryOk: readPreference.secondaryOk(),
          ...options
        };
        options.timeoutContext?.addMaxTimeMSToCommand(cmd, options);
        const message = this.supportsOpMsg ? new commands_1.OpMsgRequest(db, cmd, commandOptions) : new commands_1.OpQueryRequest(db, cmd, commandOptions);
        return message;
      }
      async *sendWire(message, options, responseType) {
        this.throwIfAborted();
        const timeout = options.socketTimeoutMS ?? options?.timeoutContext?.getSocketTimeoutMS() ?? this.socketTimeoutMS;
        this.socket.setTimeout(timeout);
        try {
          await this.writeCommand(message, {
            agreedCompressor: this.description.compressor ?? "none",
            zlibCompressionLevel: this.description.zlibCompressionLevel,
            timeoutContext: options.timeoutContext,
            signal: options.signal
          });
          if (message.moreToCome) {
            yield responses_1.MongoDBResponse.empty;
            return;
          }
          this.throwIfAborted();
          if (options.timeoutContext?.csotEnabled() && options.timeoutContext.minRoundTripTime != null && options.timeoutContext.remainingTimeMS < options.timeoutContext.minRoundTripTime) {
            throw new error_1.MongoOperationTimeoutError("Server roundtrip time is greater than the time remaining");
          }
          for await (const response of this.readMany(options)) {
            this.socket.setTimeout(0);
            const bson = response.parse();
            const document2 = (responseType ?? responses_1.MongoDBResponse).make(bson);
            yield document2;
            this.throwIfAborted();
            this.socket.setTimeout(timeout);
          }
        } finally {
          this.socket.setTimeout(0);
        }
      }
      async *sendCommand(ns, command, options, responseType) {
        options?.signal?.throwIfAborted();
        const message = this.prepareCommand(ns.db, command, options);
        let started = 0;
        if (this.shouldEmitAndLogCommand) {
          started = (0, utils_1.processTimeMS)();
          this.emitAndLogCommand(this.monitorCommands, _Connection.COMMAND_STARTED, message.databaseName, this.established, new command_monitoring_events_1.CommandStartedEvent(this, message, this.description.serverConnectionId));
        }
        const bsonOptions = options.documentsReturnedIn == null || !options.raw ? options : {
          ...options,
          raw: false,
          fieldsAsRaw: { [options.documentsReturnedIn]: true }
        };
        let document2 = void 0;
        let object3 = void 0;
        try {
          this.throwIfAborted();
          for await (document2 of this.sendWire(message, options, responseType)) {
            object3 = void 0;
            if (options.session != null) {
              (0, sessions_1.updateSessionFromResponse)(options.session, document2);
            }
            if (document2.$clusterTime) {
              this.clusterTime = document2.$clusterTime;
              this.emit(_Connection.CLUSTER_TIME_RECEIVED, document2.$clusterTime);
            }
            if (document2.ok === 0) {
              if (options.timeoutContext?.csotEnabled() && document2.isMaxTimeExpiredError) {
                throw new error_1.MongoOperationTimeoutError("Server reported a timeout error", {
                  cause: new error_1.MongoServerError(object3 ??= document2.toObject(bsonOptions))
                });
              }
              throw new error_1.MongoServerError(object3 ??= document2.toObject(bsonOptions));
            }
            if (this.shouldEmitAndLogCommand) {
              this.emitAndLogCommand(this.monitorCommands, _Connection.COMMAND_SUCCEEDED, message.databaseName, this.established, new command_monitoring_events_1.CommandSucceededEvent(this, message, message.moreToCome ? { ok: 1 } : object3 ??= document2.toObject(bsonOptions), started, this.description.serverConnectionId));
            }
            if (responseType == null) {
              yield object3 ??= document2.toObject(bsonOptions);
            } else {
              yield document2;
            }
            this.throwIfAborted();
          }
        } catch (error51) {
          if (options.session != null && !(error51 instanceof error_1.MongoServerError)) {
            (0, sessions_1.updateSessionFromResponse)(options.session, responses_1.MongoDBResponse.empty);
          }
          if (this.shouldEmitAndLogCommand) {
            this.emitAndLogCommand(this.monitorCommands, _Connection.COMMAND_FAILED, message.databaseName, this.established, new command_monitoring_events_1.CommandFailedEvent(this, message, error51, started, this.description.serverConnectionId));
          }
          throw error51;
        }
      }
      async command(ns, command, options = {}, responseType) {
        this.throwIfAborted();
        options.signal?.throwIfAborted();
        for await (const document2 of this.sendCommand(ns, command, options, responseType)) {
          if (options.timeoutContext?.csotEnabled()) {
            if (responses_1.MongoDBResponse.is(document2)) {
              if (document2.isMaxTimeExpiredError) {
                throw new error_1.MongoOperationTimeoutError("Server reported a timeout error", {
                  cause: new error_1.MongoServerError(document2.toObject())
                });
              }
            } else {
              if (Array.isArray(document2?.writeErrors) && document2.writeErrors.some((error51) => error51?.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired) || document2?.writeConcernError?.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired) {
                throw new error_1.MongoOperationTimeoutError("Server reported a timeout error", {
                  cause: new error_1.MongoServerError(document2)
                });
              }
            }
          }
          return document2;
        }
        throw new error_1.MongoUnexpectedServerResponseError("Unable to get response from server");
      }
      exhaustCommand(ns, command, options, replyListener) {
        const exhaustLoop = async () => {
          this.throwIfAborted();
          for await (const reply of this.sendCommand(ns, command, options)) {
            replyListener(void 0, reply);
            this.throwIfAborted();
          }
          throw new error_1.MongoUnexpectedServerResponseError("Server ended moreToCome unexpectedly");
        };
        exhaustLoop().then(void 0, replyListener);
      }
      throwIfAborted() {
        if (this.error)
          throw this.error;
      }
      /**
       * @internal
       *
       * Writes an OP_MSG or OP_QUERY request to the socket, optionally compressing the command. This method
       * waits until the socket's buffer has emptied (the Nodejs socket `drain` event has fired).
       */
      async writeCommand(command, options) {
        const finalCommand = options.agreedCompressor === "none" || !commands_1.OpCompressedRequest.canCompress(command) ? command : new commands_1.OpCompressedRequest(command, {
          agreedCompressor: options.agreedCompressor ?? "none",
          zlibCompressionLevel: options.zlibCompressionLevel ?? 0
        });
        const buffer = bson_1.ByteUtils.concat(await finalCommand.toBin());
        if (options.timeoutContext?.csotEnabled()) {
          if (options.timeoutContext.minRoundTripTime != null && options.timeoutContext.remainingTimeMS < options.timeoutContext.minRoundTripTime) {
            throw new error_1.MongoOperationTimeoutError("Server roundtrip time is greater than the time remaining");
          }
        }
        try {
          if (this.socket.write(buffer))
            return;
        } catch (writeError) {
          const networkError = new error_1.MongoNetworkError("unexpected error writing to socket", {
            cause: writeError
          });
          this.onError(networkError);
          throw networkError;
        }
        const drainEvent = (0, utils_1.once)(this.socket, "drain", options);
        const timeout = options?.timeoutContext?.timeoutForSocketWrite;
        const drained = timeout ? Promise.race([drainEvent, timeout]) : drainEvent;
        try {
          return await drained;
        } catch (writeError) {
          if (timeout_1.TimeoutError.is(writeError)) {
            const timeoutError = new error_1.MongoOperationTimeoutError("Timed out at socket write");
            this.onError(timeoutError);
            throw timeoutError;
          } else if (writeError === options.signal?.reason) {
            this.onError(writeError);
          }
          throw writeError;
        } finally {
          timeout?.clear();
        }
      }
      /**
       * @internal
       *
       * Returns an async generator that yields full wire protocol messages from the underlying socket.  This function
       * yields messages until `moreToCome` is false or not present in a response, or the caller cancels the request
       * by calling `return` on the generator.
       *
       * Note that `for-await` loops call `return` automatically when the loop is exited.
       */
      async *readMany(options) {
        try {
          this.dataEvents = (0, on_data_1.onData)(this.messageStream, options);
          this.messageStream.resume();
          for await (const message of this.dataEvents) {
            const response = await (0, compression_1.decompressResponse)(message);
            yield response;
            if (!response.moreToCome) {
              return;
            }
          }
        } catch (readError) {
          if (timeout_1.TimeoutError.is(readError)) {
            const timeoutError = new error_1.MongoOperationTimeoutError(`Timed out during socket read (${readError.duration}ms)`);
            this.dataEvents = null;
            this.onError(timeoutError);
            throw timeoutError;
          } else if (readError === options.signal?.reason) {
            this.onError(readError);
          }
          throw readError;
        } finally {
          this.dataEvents = null;
          this.messageStream.pause();
        }
      }
    };
    exports2.Connection = Connection;
    var SizedMessageTransform = class extends stream_1.Transform {
      constructor({ connection }) {
        super({ writableObjectMode: false, readableObjectMode: true });
        this.bufferPool = new utils_1.BufferPool();
        this.connection = connection;
      }
      _transform(chunk, encoding, callback) {
        if (this.connection.delayedTimeoutId != null) {
          (0, timers_1.clearTimeout)(this.connection.delayedTimeoutId);
          this.connection.delayedTimeoutId = null;
        }
        this.bufferPool.append(chunk);
        while (this.bufferPool.length) {
          const sizeOfMessage = this.bufferPool.getInt32();
          if (sizeOfMessage == null) {
            break;
          }
          if (sizeOfMessage < 0) {
            return callback(new error_1.MongoParseError(`Message size cannot be negative: ${sizeOfMessage}`));
          }
          if (sizeOfMessage > this.bufferPool.length) {
            break;
          }
          const message = this.bufferPool.read(sizeOfMessage);
          if (!this.push(message)) {
            return callback(new error_1.MongoRuntimeError(`SizedMessageTransform does not support backpressure`));
          }
        }
        callback();
      }
    };
    exports2.SizedMessageTransform = SizedMessageTransform;
    var CryptoConnection = class extends Connection {
      constructor(stream, options) {
        super(stream, options);
        this.autoEncrypter = options.autoEncrypter;
      }
      async command(ns, cmd, options, responseType) {
        const { autoEncrypter } = this;
        if (!autoEncrypter) {
          throw new error_1.MongoRuntimeError("No AutoEncrypter available for encryption");
        }
        const serverWireVersion = (0, utils_1.maxWireVersion)(this);
        if (serverWireVersion === 0) {
          return await super.command(ns, cmd, options, responseType);
        }
        const sort = cmd.find || cmd.findAndModify ? cmd.sort : null;
        const indexKeys = cmd.createIndexes ? cmd.indexes.map((index) => index.key) : null;
        const encrypted = await autoEncrypter.encrypt(ns.toString(), cmd, options);
        if (sort != null && (cmd.find || cmd.findAndModify)) {
          encrypted.sort = sort;
        }
        if (indexKeys != null && cmd.createIndexes) {
          for (const [offset, index] of indexKeys.entries()) {
            encrypted.indexes[offset].key = index;
          }
        }
        const encryptedResponse = await super.command(
          ns,
          encrypted,
          options,
          // Eventually we want to require `responseType` which means we would satisfy `T` as the return type.
          // In the meantime, we want encryptedResponse to always be _at least_ a MongoDBResponse if not a more specific subclass
          // So that we can ensure we have access to the on-demand APIs for decorate response
          responseType ?? responses_1.MongoDBResponse
        );
        const result = await autoEncrypter.decrypt(encryptedResponse.toBytes(), options);
        const decryptedResponse = responseType?.make(result) ?? (0, bson_1.deserialize)(result, options);
        if (autoEncrypter[constants_1.kDecorateResult]) {
          if (responseType == null) {
            (0, utils_1.decorateDecryptionResult)(decryptedResponse, encryptedResponse.toObject(), true);
          } else if (decryptedResponse instanceof responses_1.CursorResponse) {
            decryptedResponse.encryptedResponse = encryptedResponse;
          }
        }
        return decryptedResponse;
      }
    };
    exports2.CryptoConnection = CryptoConnection;
  }
});

// node_modules/mongodb/lib/cmap/connect.js
var require_connect = __commonJS({
  "node_modules/mongodb/lib/cmap/connect.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LEGAL_TCP_SOCKET_OPTIONS = exports2.LEGAL_TLS_SOCKET_OPTIONS = exports2.DEFAULT_KEEP_ALIVE_INITIAL_DELAY_MS = void 0;
    exports2.connect = connect;
    exports2.makeConnection = makeConnection;
    exports2.performInitialHandshake = performInitialHandshake;
    exports2.prepareHandshakeDocument = prepareHandshakeDocument;
    exports2.makeSocket = makeSocket;
    var net = require("net");
    var tls = require("tls");
    var constants_1 = require_constants2();
    var deps_1 = require_deps();
    var error_1 = require_error();
    var utils_1 = require_utils();
    var auth_provider_1 = require_auth_provider();
    var providers_1 = require_providers();
    var connection_1 = require_connection();
    var constants_2 = require_constants();
    function applyBackpressureLabels(error51) {
      error51.addErrorLabel(error_1.MongoErrorLabel.SystemOverloadedError);
      error51.addErrorLabel(error_1.MongoErrorLabel.RetryableError);
    }
    async function connect(options) {
      let connection = null;
      try {
        const socket = await makeSocket(options);
        connection = makeConnection(options, socket);
        await performInitialHandshake(connection, options);
        return connection;
      } catch (error51) {
        connection?.destroy();
        throw error51;
      }
    }
    function makeConnection(options, socket) {
      let ConnectionType = options.connectionType ?? connection_1.Connection;
      if (options.autoEncrypter) {
        ConnectionType = connection_1.CryptoConnection;
      }
      return new ConnectionType(socket, options);
    }
    function checkSupportedServer(hello, options) {
      const maxWireVersion = Number(hello.maxWireVersion);
      const minWireVersion = Number(hello.minWireVersion);
      const serverVersionHighEnough = !Number.isNaN(maxWireVersion) && maxWireVersion >= constants_2.MIN_SUPPORTED_WIRE_VERSION;
      const serverVersionLowEnough = !Number.isNaN(minWireVersion) && minWireVersion <= constants_2.MAX_SUPPORTED_WIRE_VERSION;
      if (serverVersionHighEnough) {
        if (serverVersionLowEnough) {
          return null;
        }
        const message2 = `Server at ${options.hostAddress} reports minimum wire version ${JSON.stringify(hello.minWireVersion)}, but this version of the Node.js Driver requires at most ${constants_2.MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${constants_2.MAX_SUPPORTED_SERVER_VERSION})`;
        return new error_1.MongoCompatibilityError(message2);
      }
      const message = `Server at ${options.hostAddress} reports maximum wire version ${JSON.stringify(hello.maxWireVersion) ?? 0}, but this version of the Node.js Driver requires at least ${constants_2.MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${constants_2.MIN_SUPPORTED_SERVER_VERSION})`;
      return new error_1.MongoCompatibilityError(message);
    }
    async function performInitialHandshake(conn, options) {
      const credentials = options.credentials;
      if (credentials) {
        if (!(credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT) && !options.authProviders.getOrCreateProvider(credentials.mechanism, credentials.mechanismProperties)) {
          throw new error_1.MongoInvalidArgumentError(`AuthMechanism '${credentials.mechanism}' not supported`);
        }
      }
      const authContext = new auth_provider_1.AuthContext(conn, credentials, options);
      conn.authContext = authContext;
      const handshakeDoc = await prepareHandshakeDocument(authContext);
      const handshakeOptions = { ...options, raw: false };
      if (typeof options.connectTimeoutMS === "number") {
        handshakeOptions.socketTimeoutMS = options.connectTimeoutMS;
      }
      const start = (/* @__PURE__ */ new Date()).getTime();
      const response = await executeHandshake(handshakeDoc, handshakeOptions);
      if (!("isWritablePrimary" in response)) {
        response.isWritablePrimary = response[constants_1.LEGACY_HELLO_COMMAND];
      }
      if (response.helloOk) {
        conn.helloOk = true;
      }
      const supportedServerErr = checkSupportedServer(response, options);
      if (supportedServerErr) {
        throw supportedServerErr;
      }
      if (options.loadBalanced) {
        if (!response.serviceId) {
          throw new error_1.MongoCompatibilityError("Driver attempted to initialize in load balancing mode, but the server does not support this mode.");
        }
      }
      conn.hello = response;
      conn.lastHelloMS = (/* @__PURE__ */ new Date()).getTime() - start;
      if (!response.arbiterOnly && credentials) {
        authContext.response = response;
        const resolvedCredentials = credentials.resolveAuthMechanism(response);
        const provider = options.authProviders.getOrCreateProvider(resolvedCredentials.mechanism, resolvedCredentials.mechanismProperties);
        if (!provider) {
          throw new error_1.MongoInvalidArgumentError(`No AuthProvider for ${resolvedCredentials.mechanism} defined.`);
        }
        try {
          await provider.auth(authContext);
        } catch (error51) {
          if (error51 instanceof error_1.MongoError) {
            error51.addErrorLabel(error_1.MongoErrorLabel.HandshakeError);
            if ((0, error_1.needsRetryableWriteLabel)(error51, response.maxWireVersion, conn.description.type)) {
              error51.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError);
            }
          }
          throw error51;
        }
      }
      conn.established = true;
      async function executeHandshake(handshakeDoc2, handshakeOptions2) {
        try {
          const handshakeResponse = await conn.command((0, utils_1.ns)("admin.$cmd"), handshakeDoc2, handshakeOptions2);
          return handshakeResponse;
        } catch (error51) {
          if (error51 instanceof error_1.MongoError) {
            error51.addErrorLabel(error_1.MongoErrorLabel.HandshakeError);
          }
          if (error51 instanceof error_1.MongoNetworkError) {
            applyBackpressureLabels(error51);
          }
          throw error51;
        }
      }
    }
    async function prepareHandshakeDocument(authContext) {
      const options = authContext.options;
      const compressors = options.compressors ? options.compressors : [];
      const { serverApi } = authContext.connection;
      const clientMetadata = await options.metadata;
      const handshakeDoc = {
        [serverApi?.version || options.loadBalanced === true ? "hello" : constants_1.LEGACY_HELLO_COMMAND]: 1,
        backpressure: true,
        helloOk: true,
        client: clientMetadata,
        compression: compressors
      };
      if (options.loadBalanced === true) {
        handshakeDoc.loadBalanced = true;
      }
      const credentials = authContext.credentials;
      if (credentials) {
        if (credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT && credentials.username) {
          handshakeDoc.saslSupportedMechs = `${credentials.source}.${credentials.username}`;
          const provider2 = authContext.options.authProviders.getOrCreateProvider(providers_1.AuthMechanism.MONGODB_SCRAM_SHA256, credentials.mechanismProperties);
          if (!provider2) {
            throw new error_1.MongoInvalidArgumentError(`No AuthProvider for ${providers_1.AuthMechanism.MONGODB_SCRAM_SHA256} defined.`);
          }
          return await provider2.prepare(handshakeDoc, authContext);
        }
        const provider = authContext.options.authProviders.getOrCreateProvider(credentials.mechanism, credentials.mechanismProperties);
        if (!provider) {
          throw new error_1.MongoInvalidArgumentError(`No AuthProvider for ${credentials.mechanism} defined.`);
        }
        return await provider.prepare(handshakeDoc, authContext);
      }
      return handshakeDoc;
    }
    exports2.DEFAULT_KEEP_ALIVE_INITIAL_DELAY_MS = 12e4;
    exports2.LEGAL_TLS_SOCKET_OPTIONS = [
      "allowPartialTrustChain",
      "ALPNProtocols",
      "ca",
      "cert",
      "checkServerIdentity",
      "ciphers",
      "crl",
      "ecdhCurve",
      "key",
      "minDHSize",
      "passphrase",
      "pfx",
      "rejectUnauthorized",
      "secureContext",
      "secureProtocol",
      "servername",
      "session"
    ];
    exports2.LEGAL_TCP_SOCKET_OPTIONS = [
      "autoSelectFamily",
      "autoSelectFamilyAttemptTimeout",
      "keepAliveInitialDelay",
      "family",
      "hints",
      "localAddress",
      "localPort",
      "lookup"
    ];
    function parseConnectOptions(options) {
      const hostAddress = options.hostAddress;
      if (!hostAddress)
        throw new error_1.MongoInvalidArgumentError('Option "hostAddress" is required');
      const result = {};
      for (const name of exports2.LEGAL_TCP_SOCKET_OPTIONS) {
        if (options[name] != null) {
          result[name] = options[name];
        }
      }
      result.keepAliveInitialDelay ??= exports2.DEFAULT_KEEP_ALIVE_INITIAL_DELAY_MS;
      result.keepAlive = true;
      result.noDelay = options.noDelay ?? true;
      if (typeof hostAddress.socketPath === "string") {
        result.path = hostAddress.socketPath;
        return result;
      } else if (typeof hostAddress.host === "string") {
        result.host = hostAddress.host;
        result.port = hostAddress.port;
        return result;
      } else {
        throw new error_1.MongoRuntimeError(`Unexpected HostAddress ${JSON.stringify(hostAddress)}`);
      }
    }
    function parseSslOptions(options) {
      const result = parseConnectOptions(options);
      for (const name of exports2.LEGAL_TLS_SOCKET_OPTIONS) {
        if (options[name] != null) {
          result[name] = options[name];
        }
      }
      if (options.existingSocket) {
        result.socket = options.existingSocket;
      }
      if (result.servername == null && result.host && !net.isIP(result.host)) {
        result.servername = result.host;
      }
      return result;
    }
    async function makeSocket(options) {
      const useTLS = options.tls ?? false;
      const connectTimeoutMS = options.connectTimeoutMS ?? 3e4;
      const existingSocket = options.existingSocket;
      const keepAliveInitialDelay = options.keepAliveInitialDelay ?? exports2.DEFAULT_KEEP_ALIVE_INITIAL_DELAY_MS;
      const noDelay = options.noDelay ?? true;
      let socket;
      if (options.proxyHost != null) {
        return await makeSocks5Connection({
          ...options,
          connectTimeoutMS
          // Should always be present for Socks5
        });
      }
      if (useTLS) {
        const tlsSocket = tls.connect(parseSslOptions(options));
        if (typeof tlsSocket.disableRenegotiation === "function") {
          tlsSocket.disableRenegotiation();
        }
        socket = tlsSocket;
      } else if (existingSocket) {
        socket = existingSocket;
      } else {
        socket = net.createConnection(parseConnectOptions(options));
      }
      socket.setKeepAlive(true, keepAliveInitialDelay);
      socket.setNoDelay(noDelay);
      socket.setTimeout(connectTimeoutMS);
      let cancellationHandler = null;
      const { promise: connectedSocket, resolve: resolve2, reject } = (0, utils_1.promiseWithResolvers)();
      if (existingSocket) {
        resolve2(socket);
      } else {
        const start = performance.now();
        const connectEvent = useTLS ? "secureConnect" : "connect";
        socket.once(connectEvent, () => resolve2(socket)).once("error", (cause) => reject(new error_1.MongoNetworkError(error_1.MongoError.buildErrorMessage(cause), { cause }))).once("timeout", () => {
          reject(new error_1.MongoNetworkTimeoutError(`Socket '${connectEvent}' timed out after ${performance.now() - start | 0}ms (connectTimeoutMS: ${connectTimeoutMS})`));
        }).once("close", () => reject(new error_1.MongoNetworkError(`Socket closed after ${performance.now() - start | 0} during connection establishment`)));
        if (options.cancellationToken != null) {
          cancellationHandler = () => reject(new error_1.MongoNetworkError(`Socket connection establishment was cancelled after ${performance.now() - start | 0}`));
          options.cancellationToken.once("cancel", cancellationHandler);
        }
      }
      try {
        socket = await connectedSocket;
        return socket;
      } catch (error51) {
        applyBackpressureLabels(error51);
        socket.destroy();
        throw error51;
      } finally {
        socket.setTimeout(0);
        if (cancellationHandler != null) {
          options.cancellationToken?.removeListener("cancel", cancellationHandler);
        }
      }
    }
    var socks = null;
    function loadSocks() {
      if (socks == null) {
        const socksImport = (0, deps_1.getSocks)();
        if ("kModuleError" in socksImport) {
          throw socksImport.kModuleError;
        }
        socks = socksImport;
      }
      return socks;
    }
    async function makeSocks5Connection(options) {
      const hostAddress = utils_1.HostAddress.fromHostPort(
        options.proxyHost ?? "",
        // proxyHost is guaranteed to set here
        options.proxyPort ?? 1080
      );
      const rawSocket = await makeSocket({
        ...options,
        hostAddress,
        tls: false,
        proxyHost: void 0
      });
      const destination = parseConnectOptions(options);
      if (typeof destination.host !== "string" || typeof destination.port !== "number") {
        throw new error_1.MongoInvalidArgumentError("Can only make Socks5 connections to TCP hosts");
      }
      socks ??= loadSocks();
      let existingSocket;
      try {
        const connection = await socks.SocksClient.createConnection({
          existing_socket: rawSocket,
          timeout: options.connectTimeoutMS,
          command: "connect",
          destination: {
            host: destination.host,
            port: destination.port
          },
          proxy: {
            // host and port are ignored because we pass existing_socket
            host: "iLoveJavaScript",
            port: 0,
            type: 5,
            userId: options.proxyUsername || void 0,
            password: options.proxyPassword || void 0
          }
        });
        existingSocket = connection.socket;
      } catch (cause) {
        throw new error_1.MongoNetworkError(error_1.MongoError.buildErrorMessage(cause), { cause });
      }
      return await makeSocket({ ...options, existingSocket, proxyHost: void 0 });
    }
  }
});

// node_modules/mongodb/lib/sdam/events.js
var require_events = __commonJS({
  "node_modules/mongodb/lib/sdam/events.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ServerHeartbeatFailedEvent = exports2.ServerHeartbeatSucceededEvent = exports2.ServerHeartbeatStartedEvent = exports2.TopologyClosedEvent = exports2.TopologyOpeningEvent = exports2.TopologyDescriptionChangedEvent = exports2.ServerClosedEvent = exports2.ServerOpeningEvent = exports2.ServerDescriptionChangedEvent = void 0;
    var constants_1 = require_constants2();
    var ServerDescriptionChangedEvent = class {
      /** @internal */
      constructor(topologyId, address, previousDescription, newDescription) {
        this.name = constants_1.SERVER_DESCRIPTION_CHANGED;
        this.topologyId = topologyId;
        this.address = address;
        this.previousDescription = previousDescription;
        this.newDescription = newDescription;
      }
    };
    exports2.ServerDescriptionChangedEvent = ServerDescriptionChangedEvent;
    var ServerOpeningEvent = class {
      /** @internal */
      constructor(topologyId, address) {
        this.name = constants_1.SERVER_OPENING;
        this.topologyId = topologyId;
        this.address = address;
      }
    };
    exports2.ServerOpeningEvent = ServerOpeningEvent;
    var ServerClosedEvent = class {
      /** @internal */
      constructor(topologyId, address) {
        this.name = constants_1.SERVER_CLOSED;
        this.topologyId = topologyId;
        this.address = address;
      }
    };
    exports2.ServerClosedEvent = ServerClosedEvent;
    var TopologyDescriptionChangedEvent = class {
      /** @internal */
      constructor(topologyId, previousDescription, newDescription) {
        this.name = constants_1.TOPOLOGY_DESCRIPTION_CHANGED;
        this.topologyId = topologyId;
        this.previousDescription = previousDescription;
        this.newDescription = newDescription;
      }
    };
    exports2.TopologyDescriptionChangedEvent = TopologyDescriptionChangedEvent;
    var TopologyOpeningEvent = class {
      /** @internal */
      constructor(topologyId) {
        this.name = constants_1.TOPOLOGY_OPENING;
        this.topologyId = topologyId;
      }
    };
    exports2.TopologyOpeningEvent = TopologyOpeningEvent;
    var TopologyClosedEvent = class {
      /** @internal */
      constructor(topologyId) {
        this.name = constants_1.TOPOLOGY_CLOSED;
        this.topologyId = topologyId;
      }
    };
    exports2.TopologyClosedEvent = TopologyClosedEvent;
    var ServerHeartbeatStartedEvent = class {
      /** @internal */
      constructor(connectionId, awaited) {
        this.name = constants_1.SERVER_HEARTBEAT_STARTED;
        this.connectionId = connectionId;
        this.awaited = awaited;
      }
    };
    exports2.ServerHeartbeatStartedEvent = ServerHeartbeatStartedEvent;
    var ServerHeartbeatSucceededEvent = class {
      /** @internal */
      constructor(connectionId, duration3, reply, awaited) {
        this.name = constants_1.SERVER_HEARTBEAT_SUCCEEDED;
        this.connectionId = connectionId;
        this.duration = duration3;
        this.reply = reply ?? {};
        this.awaited = awaited;
      }
    };
    exports2.ServerHeartbeatSucceededEvent = ServerHeartbeatSucceededEvent;
    var ServerHeartbeatFailedEvent = class {
      /** @internal */
      constructor(connectionId, duration3, failure, awaited) {
        this.name = constants_1.SERVER_HEARTBEAT_FAILED;
        this.connectionId = connectionId;
        this.duration = duration3;
        this.failure = failure;
        this.awaited = awaited;
      }
    };
    exports2.ServerHeartbeatFailedEvent = ServerHeartbeatFailedEvent;
  }
});

// node_modules/mongodb/lib/cmap/connection_pool_events.js
var require_connection_pool_events = __commonJS({
  "node_modules/mongodb/lib/cmap/connection_pool_events.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ConnectionPoolClearedEvent = exports2.ConnectionCheckedInEvent = exports2.ConnectionCheckedOutEvent = exports2.ConnectionCheckOutFailedEvent = exports2.ConnectionCheckOutStartedEvent = exports2.ConnectionClosedEvent = exports2.ConnectionReadyEvent = exports2.ConnectionCreatedEvent = exports2.ConnectionPoolClosedEvent = exports2.ConnectionPoolReadyEvent = exports2.ConnectionPoolCreatedEvent = exports2.ConnectionPoolMonitoringEvent = void 0;
    var constants_1 = require_constants2();
    var utils_1 = require_utils();
    var ConnectionPoolMonitoringEvent = class {
      /** @internal */
      constructor(pool) {
        this.time = /* @__PURE__ */ new Date();
        this.address = pool.address;
      }
    };
    exports2.ConnectionPoolMonitoringEvent = ConnectionPoolMonitoringEvent;
    var ConnectionPoolCreatedEvent = class extends ConnectionPoolMonitoringEvent {
      /** @internal */
      constructor(pool) {
        super(pool);
        this.name = constants_1.CONNECTION_POOL_CREATED;
        const { maxConnecting, maxPoolSize, minPoolSize, maxIdleTimeMS, waitQueueTimeoutMS } = pool.options;
        this.options = { maxConnecting, maxPoolSize, minPoolSize, maxIdleTimeMS, waitQueueTimeoutMS };
      }
    };
    exports2.ConnectionPoolCreatedEvent = ConnectionPoolCreatedEvent;
    var ConnectionPoolReadyEvent = class extends ConnectionPoolMonitoringEvent {
      /** @internal */
      constructor(pool) {
        super(pool);
        this.name = constants_1.CONNECTION_POOL_READY;
      }
    };
    exports2.ConnectionPoolReadyEvent = ConnectionPoolReadyEvent;
    var ConnectionPoolClosedEvent = class extends ConnectionPoolMonitoringEvent {
      /** @internal */
      constructor(pool) {
        super(pool);
        this.name = constants_1.CONNECTION_POOL_CLOSED;
      }
    };
    exports2.ConnectionPoolClosedEvent = ConnectionPoolClosedEvent;
    var ConnectionCreatedEvent = class extends ConnectionPoolMonitoringEvent {
      /** @internal */
      constructor(pool, connection) {
        super(pool);
        this.name = constants_1.CONNECTION_CREATED;
        this.connectionId = connection.id;
      }
    };
    exports2.ConnectionCreatedEvent = ConnectionCreatedEvent;
    var ConnectionReadyEvent = class extends ConnectionPoolMonitoringEvent {
      /** @internal */
      constructor(pool, connection, connectionCreatedEventTime) {
        super(pool);
        this.name = constants_1.CONNECTION_READY;
        this.durationMS = (0, utils_1.processTimeMS)() - connectionCreatedEventTime;
        this.connectionId = connection.id;
      }
    };
    exports2.ConnectionReadyEvent = ConnectionReadyEvent;
    var ConnectionClosedEvent = class extends ConnectionPoolMonitoringEvent {
      /** @internal */
      constructor(pool, connection, reason, error51) {
        super(pool);
        this.name = constants_1.CONNECTION_CLOSED;
        this.connectionId = connection.id;
        this.reason = reason;
        this.serviceId = connection.serviceId;
        this.error = error51 ?? null;
      }
    };
    exports2.ConnectionClosedEvent = ConnectionClosedEvent;
    var ConnectionCheckOutStartedEvent = class extends ConnectionPoolMonitoringEvent {
      /** @internal */
      constructor(pool) {
        super(pool);
        this.name = constants_1.CONNECTION_CHECK_OUT_STARTED;
      }
    };
    exports2.ConnectionCheckOutStartedEvent = ConnectionCheckOutStartedEvent;
    var ConnectionCheckOutFailedEvent = class extends ConnectionPoolMonitoringEvent {
      /** @internal */
      constructor(pool, reason, checkoutTime, error51) {
        super(pool);
        this.name = constants_1.CONNECTION_CHECK_OUT_FAILED;
        this.durationMS = (0, utils_1.processTimeMS)() - checkoutTime;
        this.reason = reason;
        this.error = error51;
      }
    };
    exports2.ConnectionCheckOutFailedEvent = ConnectionCheckOutFailedEvent;
    var ConnectionCheckedOutEvent = class extends ConnectionPoolMonitoringEvent {
      /** @internal */
      constructor(pool, connection, checkoutTime) {
        super(pool);
        this.name = constants_1.CONNECTION_CHECKED_OUT;
        this.durationMS = (0, utils_1.processTimeMS)() - checkoutTime;
        this.connectionId = connection.id;
      }
    };
    exports2.ConnectionCheckedOutEvent = ConnectionCheckedOutEvent;
    var ConnectionCheckedInEvent = class extends ConnectionPoolMonitoringEvent {
      /** @internal */
      constructor(pool, connection) {
        super(pool);
        this.name = constants_1.CONNECTION_CHECKED_IN;
        this.connectionId = connection.id;
      }
    };
    exports2.ConnectionCheckedInEvent = ConnectionCheckedInEvent;
    var ConnectionPoolClearedEvent = class extends ConnectionPoolMonitoringEvent {
      /** @internal */
      constructor(pool, options = {}) {
        super(pool);
        this.name = constants_1.CONNECTION_POOL_CLEARED;
        this.serviceId = options.serviceId;
        this.interruptInUseConnections = options.interruptInUseConnections;
      }
    };
    exports2.ConnectionPoolClearedEvent = ConnectionPoolClearedEvent;
  }
});

// node_modules/mongodb/lib/cmap/errors.js
var require_errors2 = __commonJS({
  "node_modules/mongodb/lib/cmap/errors.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.WaitQueueTimeoutError = exports2.PoolClearedOnNetworkError = exports2.PoolClearedError = exports2.PoolClosedError = void 0;
    var error_1 = require_error();
    var PoolClosedError = class extends error_1.MongoDriverError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(pool) {
        super("Attempted to check out a connection from closed connection pool");
        this.address = pool.address;
      }
      get name() {
        return "MongoPoolClosedError";
      }
    };
    exports2.PoolClosedError = PoolClosedError;
    var PoolClearedError = class extends error_1.MongoNetworkError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(pool, message) {
        const errorMessage = message ? message : `Connection pool for ${pool.address} was cleared because another operation failed with: "${pool.serverError?.message}"`;
        super(errorMessage, pool.serverError ? { cause: pool.serverError } : void 0);
        this.address = pool.address;
        this.addErrorLabel(error_1.MongoErrorLabel.PoolRequestedRetry);
      }
      get name() {
        return "MongoPoolClearedError";
      }
    };
    exports2.PoolClearedError = PoolClearedError;
    var PoolClearedOnNetworkError = class extends PoolClearedError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(pool) {
        super(pool, `Connection to ${pool.address} interrupted due to server monitor timeout`);
      }
      get name() {
        return "PoolClearedOnNetworkError";
      }
    };
    exports2.PoolClearedOnNetworkError = PoolClearedOnNetworkError;
    var WaitQueueTimeoutError = class extends error_1.MongoDriverError {
      /**
       * **Do not use this constructor!**
       *
       * Meant for internal use only.
       *
       * @remarks
       * This class is only meant to be constructed within the driver. This constructor is
       * not subject to semantic versioning compatibility guarantees and may change at any time.
       *
       * @public
       **/
      constructor(message, address) {
        super(message);
        this.address = address;
      }
      get name() {
        return "MongoWaitQueueTimeoutError";
      }
    };
    exports2.WaitQueueTimeoutError = WaitQueueTimeoutError;
  }
});

// node_modules/mongodb/lib/cmap/connection_pool.js
var require_connection_pool = __commonJS({
  "node_modules/mongodb/lib/cmap/connection_pool.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ConnectionPool = exports2.PoolState = void 0;
    var timers_1 = require("timers");
    var constants_1 = require_constants2();
    var error_1 = require_error();
    var mongo_types_1 = require_mongo_types();
    var timeout_1 = require_timeout();
    var utils_1 = require_utils();
    var connect_1 = require_connect();
    var connection_1 = require_connection();
    var connection_pool_events_1 = require_connection_pool_events();
    var errors_1 = require_errors2();
    var metrics_1 = require_metrics();
    exports2.PoolState = Object.freeze({
      paused: "paused",
      ready: "ready",
      closed: "closed"
    });
    var ConnectionPool = class _ConnectionPool extends mongo_types_1.TypedEventEmitter {
      static {
        this.CONNECTION_POOL_CREATED = constants_1.CONNECTION_POOL_CREATED;
      }
      static {
        this.CONNECTION_POOL_CLOSED = constants_1.CONNECTION_POOL_CLOSED;
      }
      static {
        this.CONNECTION_POOL_CLEARED = constants_1.CONNECTION_POOL_CLEARED;
      }
      static {
        this.CONNECTION_POOL_READY = constants_1.CONNECTION_POOL_READY;
      }
      static {
        this.CONNECTION_CREATED = constants_1.CONNECTION_CREATED;
      }
      static {
        this.CONNECTION_READY = constants_1.CONNECTION_READY;
      }
      static {
        this.CONNECTION_CLOSED = constants_1.CONNECTION_CLOSED;
      }
      static {
        this.CONNECTION_CHECK_OUT_STARTED = constants_1.CONNECTION_CHECK_OUT_STARTED;
      }
      static {
        this.CONNECTION_CHECK_OUT_FAILED = constants_1.CONNECTION_CHECK_OUT_FAILED;
      }
      static {
        this.CONNECTION_CHECKED_OUT = constants_1.CONNECTION_CHECKED_OUT;
      }
      static {
        this.CONNECTION_CHECKED_IN = constants_1.CONNECTION_CHECKED_IN;
      }
      constructor(server, options) {
        super();
        this.on("error", utils_1.noop);
        this.options = Object.freeze({
          connectionType: connection_1.Connection,
          ...options,
          maxPoolSize: options.maxPoolSize ?? 100,
          minPoolSize: options.minPoolSize ?? 0,
          maxConnecting: options.maxConnecting ?? 2,
          maxIdleTimeMS: options.maxIdleTimeMS ?? 0,
          waitQueueTimeoutMS: options.waitQueueTimeoutMS ?? 0,
          minPoolSizeCheckFrequencyMS: options.minPoolSizeCheckFrequencyMS ?? 100,
          autoEncrypter: options.autoEncrypter
        });
        if (this.options.minPoolSize > this.options.maxPoolSize) {
          throw new error_1.MongoInvalidArgumentError("Connection pool minimum size must not be greater than maximum pool size");
        }
        this.poolState = exports2.PoolState.paused;
        this.server = server;
        this.connections = new utils_1.List();
        this.pending = 0;
        this.checkedOut = /* @__PURE__ */ new Set();
        this.minPoolSizeTimer = void 0;
        this.generation = 0;
        this.serviceGenerations = /* @__PURE__ */ new Map();
        this.connectionCounter = (0, utils_1.makeCounter)(1);
        this.cancellationToken = new mongo_types_1.CancellationToken();
        this.cancellationToken.setMaxListeners(Infinity);
        this.waitQueue = new utils_1.List();
        this.metrics = new metrics_1.ConnectionPoolMetrics();
        this.processingWaitQueue = false;
        this.mongoLogger = this.server.topology.client?.mongoLogger;
        this.component = "connection";
        queueMicrotask(() => {
          this.emitAndLog(_ConnectionPool.CONNECTION_POOL_CREATED, new connection_pool_events_1.ConnectionPoolCreatedEvent(this));
        });
      }
      /** The address of the endpoint the pool is connected to */
      get address() {
        return this.options.hostAddress.toString();
      }
      /**
       * Check if the pool has been closed
       *
       * TODO(NODE-3263): We can remove this property once shell no longer needs it
       */
      get closed() {
        return this.poolState === exports2.PoolState.closed;
      }
      /** An integer expressing how many total connections (available + pending + in use) the pool currently has */
      get totalConnectionCount() {
        return this.availableConnectionCount + this.pendingConnectionCount + this.currentCheckedOutCount;
      }
      /** An integer expressing how many connections are currently available in the pool. */
      get availableConnectionCount() {
        return this.connections.length;
      }
      get pendingConnectionCount() {
        return this.pending;
      }
      get currentCheckedOutCount() {
        return this.checkedOut.size;
      }
      get waitQueueSize() {
        return this.waitQueue.length;
      }
      get loadBalanced() {
        return this.options.loadBalanced;
      }
      get serverError() {
        return this.server.description.error;
      }
      /**
       * This is exposed ONLY for use in mongosh, to enable
       * killing all connections if a user quits the shell with
       * operations in progress.
       *
       * This property may be removed as a part of NODE-3263.
       */
      get checkedOutConnections() {
        return this.checkedOut;
      }
      /**
       * Get the metrics information for the pool when a wait queue timeout occurs.
       */
      waitQueueErrorMetrics() {
        return this.metrics.info(this.options.maxPoolSize);
      }
      /**
       * Set the pool state to "ready"
       */
      ready() {
        if (this.poolState !== exports2.PoolState.paused) {
          return;
        }
        this.poolState = exports2.PoolState.ready;
        this.emitAndLog(_ConnectionPool.CONNECTION_POOL_READY, new connection_pool_events_1.ConnectionPoolReadyEvent(this));
        (0, timers_1.clearTimeout)(this.minPoolSizeTimer);
        this.ensureMinPoolSize();
      }
      /**
       * Check a connection out of this pool. The connection will continue to be tracked, but no reference to it
       * will be held by the pool. This means that if a connection is checked out it MUST be checked back in or
       * explicitly destroyed by the new owner.
       */
      async checkOut(options) {
        const checkoutTime = (0, utils_1.processTimeMS)();
        this.emitAndLog(_ConnectionPool.CONNECTION_CHECK_OUT_STARTED, new connection_pool_events_1.ConnectionCheckOutStartedEvent(this));
        const { promise: promise2, resolve: resolve2, reject } = (0, utils_1.promiseWithResolvers)();
        const timeout = options.timeoutContext.connectionCheckoutTimeout;
        const waitQueueMember = {
          resolve: resolve2,
          reject,
          cancelled: false,
          checkoutTime
        };
        const abortListener = (0, utils_1.addAbortListener)(options.signal, function() {
          waitQueueMember.cancelled = true;
          reject(this.reason);
        });
        this.waitQueue.push(waitQueueMember);
        queueMicrotask(() => this.processWaitQueue());
        try {
          timeout?.throwIfExpired();
          return await (timeout ? Promise.race([promise2, timeout]) : promise2);
        } catch (error51) {
          if (timeout_1.TimeoutError.is(error51)) {
            timeout?.clear();
            waitQueueMember.cancelled = true;
            this.emitAndLog(_ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, "timeout", waitQueueMember.checkoutTime));
            const timeoutError = new errors_1.WaitQueueTimeoutError(this.loadBalanced ? this.waitQueueErrorMetrics() : "Timed out while checking out a connection from connection pool", this.address);
            if (options.timeoutContext.csotEnabled()) {
              throw new error_1.MongoOperationTimeoutError("Timed out during connection checkout", {
                cause: timeoutError
              });
            }
            throw timeoutError;
          }
          throw error51;
        } finally {
          abortListener?.[utils_1.kDispose]();
          timeout?.clear();
        }
      }
      /**
       * Check a connection into the pool.
       *
       * @param connection - The connection to check in
       */
      checkIn(connection) {
        if (!this.checkedOut.has(connection)) {
          return;
        }
        const poolClosed = this.closed;
        const stale = this.connectionIsStale(connection);
        const willDestroy = !!(poolClosed || stale || connection.closed);
        if (!willDestroy) {
          connection.markAvailable();
          this.connections.unshift(connection);
        }
        this.checkedOut.delete(connection);
        this.emitAndLog(_ConnectionPool.CONNECTION_CHECKED_IN, new connection_pool_events_1.ConnectionCheckedInEvent(this, connection));
        if (willDestroy) {
          const reason = connection.closed ? "error" : poolClosed ? "poolClosed" : "stale";
          this.destroyConnection(connection, reason);
        }
        queueMicrotask(() => this.processWaitQueue());
      }
      /**
       * Clear the pool
       *
       * Pool reset is handled by incrementing the pool's generation count. Any existing connection of a
       * previous generation will eventually be pruned during subsequent checkouts.
       */
      clear(options = {}) {
        if (this.closed) {
          return;
        }
        if (this.loadBalanced) {
          const { serviceId } = options;
          if (!serviceId) {
            throw new error_1.MongoRuntimeError("ConnectionPool.clear() called in load balanced mode with no serviceId.");
          }
          const sid = serviceId.toHexString();
          const generation = this.serviceGenerations.get(sid);
          if (generation == null) {
            throw new error_1.MongoRuntimeError("Service generations are required in load balancer mode.");
          } else {
            this.serviceGenerations.set(sid, generation + 1);
          }
          this.emitAndLog(_ConnectionPool.CONNECTION_POOL_CLEARED, new connection_pool_events_1.ConnectionPoolClearedEvent(this, { serviceId }));
          return;
        }
        const interruptInUseConnections = options.interruptInUseConnections ?? false;
        const oldGeneration = this.generation;
        this.generation += 1;
        const alreadyPaused = this.poolState === exports2.PoolState.paused;
        this.poolState = exports2.PoolState.paused;
        this.clearMinPoolSizeTimer();
        if (!alreadyPaused) {
          this.emitAndLog(_ConnectionPool.CONNECTION_POOL_CLEARED, new connection_pool_events_1.ConnectionPoolClearedEvent(this, {
            interruptInUseConnections
          }));
        }
        if (interruptInUseConnections) {
          queueMicrotask(() => this.interruptInUseConnections(oldGeneration));
        }
        this.processWaitQueue();
      }
      /**
       * Closes all stale in-use connections in the pool with a resumable PoolClearedOnNetworkError.
       *
       * Only connections where `connection.generation <= minGeneration` are killed.
       */
      interruptInUseConnections(minGeneration) {
        for (const connection of this.checkedOut) {
          if (connection.generation <= minGeneration) {
            connection.onError(new errors_1.PoolClearedOnNetworkError(this));
          }
        }
      }
      /** For MongoClient.close() procedures */
      closeCheckedOutConnections() {
        for (const conn of this.checkedOut) {
          conn.onError(new error_1.MongoClientClosedError());
        }
      }
      /** Close the pool */
      close() {
        if (this.closed) {
          return;
        }
        this.cancellationToken.emit("cancel");
        if (typeof this.connectionCounter.return === "function") {
          this.connectionCounter.return(void 0);
        }
        this.poolState = exports2.PoolState.closed;
        this.clearMinPoolSizeTimer();
        this.processWaitQueue();
        for (const conn of this.connections) {
          this.emitAndLog(_ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, conn, "poolClosed"));
          conn.destroy();
        }
        this.connections.clear();
        this.emitAndLog(_ConnectionPool.CONNECTION_POOL_CLOSED, new connection_pool_events_1.ConnectionPoolClosedEvent(this));
      }
      /**
       * @internal
       * Reauthenticate a connection
       */
      async reauthenticate(connection) {
        const authContext = connection.authContext;
        if (!authContext) {
          throw new error_1.MongoRuntimeError("No auth context found on connection.");
        }
        const credentials = authContext.credentials;
        if (!credentials) {
          throw new error_1.MongoMissingCredentialsError("Connection is missing credentials when asked to reauthenticate");
        }
        const resolvedCredentials = credentials.resolveAuthMechanism(connection.hello);
        const provider = this.server.topology.client.s.authProviders.getOrCreateProvider(resolvedCredentials.mechanism, resolvedCredentials.mechanismProperties);
        if (!provider) {
          throw new error_1.MongoMissingCredentialsError(`Reauthenticate failed due to no auth provider for ${credentials.mechanism}`);
        }
        await provider.reauth(authContext);
        return;
      }
      /** Clear the min pool size timer */
      clearMinPoolSizeTimer() {
        const minPoolSizeTimer = this.minPoolSizeTimer;
        if (minPoolSizeTimer) {
          (0, timers_1.clearTimeout)(minPoolSizeTimer);
        }
      }
      destroyConnection(connection, reason) {
        this.emitAndLog(_ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, connection, reason));
        connection.destroy();
      }
      connectionIsStale(connection) {
        const serviceId = connection.serviceId;
        if (this.loadBalanced && serviceId) {
          const sid = serviceId.toHexString();
          const generation = this.serviceGenerations.get(sid);
          return connection.generation !== generation;
        }
        return connection.generation !== this.generation;
      }
      connectionIsIdle(connection) {
        return !!(this.options.maxIdleTimeMS && connection.idleTime > this.options.maxIdleTimeMS);
      }
      /**
       * Destroys a connection if the connection is perished.
       *
       * @returns `true` if the connection was destroyed, `false` otherwise.
       */
      destroyConnectionIfPerished(connection) {
        const isStale = this.connectionIsStale(connection);
        const isIdle = this.connectionIsIdle(connection);
        if (!isStale && !isIdle && !connection.closed) {
          return false;
        }
        const reason = connection.closed ? "error" : isStale ? "stale" : "idle";
        this.destroyConnection(connection, reason);
        return true;
      }
      createConnection(callback) {
        const connectOptions = {
          ...this.options,
          id: this.connectionCounter.next().value,
          generation: this.generation,
          cancellationToken: this.cancellationToken,
          mongoLogger: this.mongoLogger,
          authProviders: this.server.topology.client.s.authProviders,
          metadata: this.server.topology.client.options.metadata
        };
        this.pending++;
        const connectionCreatedTime = (0, utils_1.processTimeMS)();
        this.emitAndLog(_ConnectionPool.CONNECTION_CREATED, new connection_pool_events_1.ConnectionCreatedEvent(this, { id: connectOptions.id }));
        (0, connect_1.connect)(connectOptions).then((connection) => {
          if (this.poolState !== exports2.PoolState.ready) {
            this.pending--;
            connection.destroy();
            callback(this.closed ? new errors_1.PoolClosedError(this) : new errors_1.PoolClearedError(this));
            return;
          }
          for (const event of [...constants_1.APM_EVENTS, connection_1.Connection.CLUSTER_TIME_RECEIVED]) {
            connection.on(event, (e2) => this.emit(event, e2));
          }
          if (this.loadBalanced) {
            connection.on(connection_1.Connection.PINNED, (pinType) => this.metrics.markPinned(pinType));
            connection.on(connection_1.Connection.UNPINNED, (pinType) => this.metrics.markUnpinned(pinType));
            const serviceId = connection.serviceId;
            if (serviceId) {
              let generation;
              const sid = serviceId.toHexString();
              if (generation = this.serviceGenerations.get(sid)) {
                connection.generation = generation;
              } else {
                this.serviceGenerations.set(sid, 0);
                connection.generation = 0;
              }
            }
          }
          connection.markAvailable();
          this.emitAndLog(_ConnectionPool.CONNECTION_READY, new connection_pool_events_1.ConnectionReadyEvent(this, connection, connectionCreatedTime));
          this.pending--;
          callback(void 0, connection);
        }, (error51) => {
          this.pending--;
          this.server.handleError(error51);
          this.emitAndLog(_ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(
            this,
            { id: connectOptions.id, serviceId: void 0 },
            "error",
            // TODO(NODE-5192): Remove this cast
            error51
          ));
          if (error51 instanceof error_1.MongoNetworkError || error51 instanceof error_1.MongoServerError) {
            error51.connectionGeneration = connectOptions.generation;
          }
          callback(error51 ?? new error_1.MongoRuntimeError("Connection creation failed without error"));
        });
      }
      ensureMinPoolSize() {
        const minPoolSize = this.options.minPoolSize;
        if (this.poolState !== exports2.PoolState.ready) {
          return;
        }
        this.connections.prune((connection) => this.destroyConnectionIfPerished(connection));
        if (this.totalConnectionCount < minPoolSize && this.pendingConnectionCount < this.options.maxConnecting) {
          this.createConnection((err, connection) => {
            if (!err && connection) {
              this.connections.push(connection);
              queueMicrotask(() => this.processWaitQueue());
            }
            if (this.poolState === exports2.PoolState.ready) {
              (0, timers_1.clearTimeout)(this.minPoolSizeTimer);
              this.minPoolSizeTimer = (0, timers_1.setTimeout)(() => this.ensureMinPoolSize(), this.options.minPoolSizeCheckFrequencyMS);
            }
          });
        } else {
          (0, timers_1.clearTimeout)(this.minPoolSizeTimer);
          this.minPoolSizeTimer = (0, timers_1.setTimeout)(() => this.ensureMinPoolSize(), this.options.minPoolSizeCheckFrequencyMS);
        }
      }
      processWaitQueue() {
        if (this.processingWaitQueue) {
          return;
        }
        this.processingWaitQueue = true;
        while (this.waitQueueSize) {
          const waitQueueMember = this.waitQueue.first();
          if (!waitQueueMember) {
            this.waitQueue.shift();
            continue;
          }
          if (waitQueueMember.cancelled) {
            this.waitQueue.shift();
            continue;
          }
          if (this.poolState !== exports2.PoolState.ready) {
            const reason = this.closed ? "poolClosed" : "connectionError";
            const error51 = this.closed ? new errors_1.PoolClosedError(this) : new errors_1.PoolClearedError(this);
            this.emitAndLog(_ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, reason, waitQueueMember.checkoutTime, error51));
            this.waitQueue.shift();
            waitQueueMember.reject(error51);
            continue;
          }
          if (!this.availableConnectionCount) {
            break;
          }
          const connection = this.connections.shift();
          if (!connection) {
            break;
          }
          if (!this.destroyConnectionIfPerished(connection)) {
            this.checkedOut.add(connection);
            this.emitAndLog(_ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(this, connection, waitQueueMember.checkoutTime));
            this.waitQueue.shift();
            waitQueueMember.resolve(connection);
          }
        }
        const { maxPoolSize, maxConnecting } = this.options;
        while (this.waitQueueSize > 0 && this.pendingConnectionCount < maxConnecting && (maxPoolSize === 0 || this.totalConnectionCount < maxPoolSize)) {
          const waitQueueMember = this.waitQueue.shift();
          if (!waitQueueMember || waitQueueMember.cancelled) {
            continue;
          }
          this.createConnection((err, connection) => {
            if (waitQueueMember.cancelled) {
              if (!err && connection) {
                this.connections.push(connection);
              }
            } else {
              if (err) {
                this.emitAndLog(
                  _ConnectionPool.CONNECTION_CHECK_OUT_FAILED,
                  // TODO(NODE-5192): Remove this cast
                  new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, "connectionError", waitQueueMember.checkoutTime, err)
                );
                waitQueueMember.reject(err);
              } else if (connection) {
                this.checkedOut.add(connection);
                this.emitAndLog(_ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(this, connection, waitQueueMember.checkoutTime));
                waitQueueMember.resolve(connection);
              }
            }
            queueMicrotask(() => this.processWaitQueue());
          });
        }
        this.processingWaitQueue = false;
      }
    };
    exports2.ConnectionPool = ConnectionPool;
  }
});

// node_modules/mongodb/lib/sdam/server.js
var require_server = __commonJS({
  "node_modules/mongodb/lib/sdam/server.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Server = void 0;
    var connection_1 = require_connection();
    var connection_pool_1 = require_connection_pool();
    var errors_1 = require_errors2();
    var constants_1 = require_constants2();
    var error_1 = require_error();
    var mongo_types_1 = require_mongo_types();
    var aggregate_1 = require_aggregate();
    var transactions_1 = require_transactions();
    var utils_1 = require_utils();
    var write_concern_1 = require_write_concern();
    var common_1 = require_common();
    var monitor_1 = require_monitor();
    var server_description_1 = require_server_description();
    var server_selection_1 = require_server_selection();
    var stateTransition = (0, utils_1.makeStateMachine)({
      [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, common_1.STATE_CONNECTING],
      [common_1.STATE_CONNECTING]: [common_1.STATE_CONNECTING, common_1.STATE_CLOSING, common_1.STATE_CONNECTED, common_1.STATE_CLOSED],
      [common_1.STATE_CONNECTED]: [common_1.STATE_CONNECTED, common_1.STATE_CLOSING, common_1.STATE_CLOSED],
      [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, common_1.STATE_CLOSED]
    });
    var Server2 = class _Server extends mongo_types_1.TypedEventEmitter {
      static {
        this.SERVER_HEARTBEAT_STARTED = constants_1.SERVER_HEARTBEAT_STARTED;
      }
      static {
        this.SERVER_HEARTBEAT_SUCCEEDED = constants_1.SERVER_HEARTBEAT_SUCCEEDED;
      }
      static {
        this.SERVER_HEARTBEAT_FAILED = constants_1.SERVER_HEARTBEAT_FAILED;
      }
      static {
        this.CONNECT = constants_1.CONNECT;
      }
      static {
        this.DESCRIPTION_RECEIVED = constants_1.DESCRIPTION_RECEIVED;
      }
      static {
        this.CLOSED = constants_1.CLOSED;
      }
      static {
        this.ENDED = constants_1.ENDED;
      }
      /**
       * Create a server
       */
      constructor(topology, description, options) {
        super();
        this.on("error", utils_1.noop);
        this.serverApi = options.serverApi;
        const poolOptions = { hostAddress: description.hostAddress, ...options };
        this.topology = topology;
        this.pool = new connection_pool_1.ConnectionPool(this, poolOptions);
        this.s = {
          description,
          options,
          state: common_1.STATE_CLOSED,
          operationCount: 0
        };
        for (const event of [...constants_1.CMAP_EVENTS, ...constants_1.APM_EVENTS]) {
          this.pool.on(event, (e2) => this.emit(event, e2));
        }
        this.pool.on(connection_1.Connection.CLUSTER_TIME_RECEIVED, (clusterTime) => {
          this.clusterTime = clusterTime;
        });
        if (this.loadBalanced) {
          this.monitor = null;
          return;
        }
        this.monitor = new monitor_1.Monitor(this, this.s.options);
        for (const event of constants_1.HEARTBEAT_EVENTS) {
          this.monitor.on(event, (e2) => this.emit(event, e2));
        }
        this.monitor.on("resetServer", (error51) => markServerUnknown(this, error51));
        this.monitor.on(_Server.SERVER_HEARTBEAT_SUCCEEDED, (event) => {
          this.emit(_Server.DESCRIPTION_RECEIVED, new server_description_1.ServerDescription(this.description.hostAddress, event.reply, {
            roundTripTime: this.monitor?.roundTripTime,
            minRoundTripTime: this.monitor?.minRoundTripTime
          }));
          if (this.s.state === common_1.STATE_CONNECTING) {
            stateTransition(this, common_1.STATE_CONNECTED);
            this.emit(_Server.CONNECT, this);
          }
        });
      }
      get clusterTime() {
        return this.topology.clusterTime;
      }
      set clusterTime(clusterTime) {
        this.topology.clusterTime = clusterTime;
      }
      get description() {
        return this.s.description;
      }
      get name() {
        return this.s.description.address;
      }
      get autoEncrypter() {
        if (this.s.options && this.s.options.autoEncrypter) {
          return this.s.options.autoEncrypter;
        }
        return;
      }
      get loadBalanced() {
        return this.topology.description.type === common_1.TopologyType.LoadBalanced;
      }
      /**
       * Initiate server connect
       */
      connect() {
        if (this.s.state !== common_1.STATE_CLOSED) {
          return;
        }
        stateTransition(this, common_1.STATE_CONNECTING);
        if (!this.loadBalanced) {
          this.monitor?.connect();
        } else {
          stateTransition(this, common_1.STATE_CONNECTED);
          this.emit(_Server.CONNECT, this);
        }
      }
      closeCheckedOutConnections() {
        return this.pool.closeCheckedOutConnections();
      }
      /** Destroy the server connection */
      close() {
        if (this.s.state === common_1.STATE_CLOSED) {
          return;
        }
        stateTransition(this, common_1.STATE_CLOSING);
        if (!this.loadBalanced) {
          this.monitor?.close();
        }
        this.pool.close();
        stateTransition(this, common_1.STATE_CLOSED);
        this.emit("closed");
      }
      /**
       * Immediately schedule monitoring of this server. If there already an attempt being made
       * this will be a no-op.
       */
      requestCheck() {
        if (!this.loadBalanced) {
          this.monitor?.requestCheck();
        }
      }
      async command(operation, timeoutContext) {
        if (this.s.state === common_1.STATE_CLOSING || this.s.state === common_1.STATE_CLOSED) {
          throw new error_1.MongoServerClosedError();
        }
        const session = operation.session;
        let conn = session?.pinnedConnection;
        this.incrementOperationCount();
        if (conn == null) {
          try {
            conn = await this.pool.checkOut({ timeoutContext, signal: operation.options.signal });
          } catch (checkoutError) {
            this.decrementOperationCount();
            if (!(checkoutError instanceof errors_1.PoolClearedError))
              this.handleError(checkoutError);
            throw checkoutError;
          }
        }
        let reauthPromise = null;
        const cleanup = () => {
          this.decrementOperationCount();
          if (session?.pinnedConnection !== conn) {
            if (reauthPromise != null) {
              const checkBackIn = () => {
                this.pool.checkIn(conn);
              };
              void reauthPromise.then(checkBackIn, checkBackIn);
            } else {
              this.pool.checkIn(conn);
            }
          }
        };
        let cmd;
        try {
          cmd = operation.buildCommand(conn, session);
        } catch (e2) {
          cleanup();
          throw e2;
        }
        const options = operation.buildOptions(timeoutContext);
        const ns = operation.ns;
        if (this.loadBalanced && isPinnableCommand(cmd, session) && !session?.pinnedConnection) {
          session?.pin(conn);
        }
        options.directConnection = this.topology.s.options.directConnection;
        const omitReadPreference = operation instanceof aggregate_1.AggregateOperation && operation.hasWriteStage && (0, utils_1.maxWireVersion)(conn) < server_selection_1.MIN_SECONDARY_WRITE_WIRE_VERSION;
        if (omitReadPreference) {
          delete options.readPreference;
        }
        if (this.description.iscryptd) {
          options.omitMaxTimeMS = true;
        }
        try {
          try {
            const res = await conn.command(ns, cmd, options, operation.SERVER_COMMAND_RESPONSE_TYPE);
            (0, write_concern_1.throwIfWriteConcernError)(res);
            return res;
          } catch (commandError) {
            throw this.decorateCommandError(conn, cmd, options, commandError);
          }
        } catch (operationError) {
          if (operationError instanceof error_1.MongoError && operationError.code?.valueOf() === error_1.MONGODB_ERROR_CODES.Reauthenticate) {
            reauthPromise = this.pool.reauthenticate(conn);
            reauthPromise.then(void 0, (error51) => {
              reauthPromise = null;
              (0, utils_1.squashError)(error51);
            });
            await (0, utils_1.abortable)(reauthPromise, options);
            reauthPromise = null;
            try {
              const res = await conn.command(ns, cmd, options, operation.SERVER_COMMAND_RESPONSE_TYPE);
              (0, write_concern_1.throwIfWriteConcernError)(res);
              return res;
            } catch (commandError) {
              throw this.decorateCommandError(conn, cmd, options, commandError);
            }
          } else {
            throw operationError;
          }
        } finally {
          cleanup();
        }
      }
      /**
       * Handle SDAM error
       * @internal
       */
      handleError(error51, connection) {
        if (!(error51 instanceof error_1.MongoError)) {
          return;
        }
        if (isStaleError(this, error51)) {
          return;
        }
        const isNetworkNonTimeoutError = error51 instanceof error_1.MongoNetworkError && !(error51 instanceof error_1.MongoNetworkTimeoutError);
        const isNetworkTimeoutBeforeHandshakeError = error51 instanceof error_1.MongoNetworkError && error51.beforeHandshake;
        const isAuthOrEstablishmentHandshakeError = error51.hasErrorLabel(error_1.MongoErrorLabel.HandshakeError);
        const isSystemOverloadError = error51.hasErrorLabel(error_1.MongoErrorLabel.SystemOverloadedError);
        if ((0, error_1.isStateChangeError)(error51) || error51 instanceof error_1.MongoParseError) {
          const shouldClearPool = (0, error_1.isNodeShuttingDownError)(error51);
          if (!this.loadBalanced) {
            if (shouldClearPool) {
              error51.addErrorLabel(error_1.MongoErrorLabel.ResetPool);
            }
            markServerUnknown(this, error51);
            queueMicrotask(() => this.requestCheck());
            return;
          }
          if (connection && shouldClearPool) {
            this.pool.clear({ serviceId: connection.serviceId });
          }
        } else if (isNetworkNonTimeoutError || isNetworkTimeoutBeforeHandshakeError || isAuthOrEstablishmentHandshakeError) {
          if (isSystemOverloadError) {
            return;
          }
          if (!this.loadBalanced) {
            error51.addErrorLabel(error_1.MongoErrorLabel.ResetPool);
            markServerUnknown(this, error51);
          } else if (connection) {
            this.pool.clear({ serviceId: connection.serviceId });
          }
        }
      }
      /**
       * Ensure that error is properly decorated and internal state is updated before throwing
       * @internal
       */
      decorateCommandError(connection, cmd, options, error51) {
        if (typeof error51 !== "object" || error51 == null || !("name" in error51)) {
          throw new error_1.MongoRuntimeError("An unexpected error type: " + typeof error51);
        }
        if (error51.name === "AbortError" && "cause" in error51 && error51.cause instanceof error_1.MongoError) {
          error51 = error51.cause;
        }
        if (!(error51 instanceof error_1.MongoError)) {
          return error51;
        }
        if (connectionIsStale(this.pool, connection)) {
          return error51;
        }
        const session = options?.session;
        if (error51 instanceof error_1.MongoNetworkError) {
          if (session && !session.hasEnded && session.serverSession) {
            session.serverSession.isDirty = true;
          }
          if (inActiveTransaction(session, cmd) && !error51.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) {
            error51.addErrorLabel(error_1.MongoErrorLabel.TransientTransactionError);
          }
          if ((isRetryableWritesEnabled(this.topology) || (0, transactions_1.isTransactionCommand)(cmd)) && (0, utils_1.supportsRetryableWrites)(this) && !inActiveTransaction(session, cmd)) {
            error51.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError);
          }
        } else {
          if ((isRetryableWritesEnabled(this.topology) || (0, transactions_1.isTransactionCommand)(cmd)) && (0, error_1.needsRetryableWriteLabel)(error51, (0, utils_1.maxWireVersion)(this), this.description.type) && !inActiveTransaction(session, cmd)) {
            error51.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError);
          }
        }
        if (session && session.isPinned && error51.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) {
          session.unpin({ force: true });
        }
        this.handleError(error51, connection);
        return error51;
      }
      /**
       * Decrement the operation count, returning the new count.
       */
      decrementOperationCount() {
        return this.s.operationCount -= 1;
      }
      /**
       * Increment the operation count, returning the new count.
       */
      incrementOperationCount() {
        return this.s.operationCount += 1;
      }
    };
    exports2.Server = Server2;
    function markServerUnknown(server, error51) {
      if (server.loadBalanced) {
        return;
      }
      if (error51 instanceof error_1.MongoNetworkError && !(error51 instanceof error_1.MongoNetworkTimeoutError)) {
        server.monitor?.reset();
      }
      server.emit(Server2.DESCRIPTION_RECEIVED, new server_description_1.ServerDescription(server.description.hostAddress, void 0, { error: error51 }));
    }
    function isPinnableCommand(cmd, session) {
      if (session) {
        return session.inTransaction() || session.transaction.isCommitted && "commitTransaction" in cmd || "aggregate" in cmd || "find" in cmd || "getMore" in cmd || "listCollections" in cmd || "listIndexes" in cmd || "bulkWrite" in cmd;
      }
      return false;
    }
    function connectionIsStale(pool, connection) {
      if (connection.serviceId) {
        return connection.generation !== pool.serviceGenerations.get(connection.serviceId.toHexString());
      }
      return connection.generation !== pool.generation;
    }
    function inActiveTransaction(session, cmd) {
      return session && session.inTransaction() && !(0, transactions_1.isTransactionCommand)(cmd);
    }
    function isRetryableWritesEnabled(topology) {
      return topology.s.options.retryWrites !== false;
    }
    function isStaleError(server, error51) {
      const currentGeneration = server.pool.generation;
      const generation = error51.connectionGeneration;
      if (generation && generation < currentGeneration) {
        return true;
      }
      const currentTopologyVersion = server.description.topologyVersion;
      return (0, server_description_1.compareTopologyVersion)(currentTopologyVersion, error51.topologyVersion) >= 0;
    }
  }
});

// node_modules/mongodb/lib/sdam/monitor.js
var require_monitor = __commonJS({
  "node_modules/mongodb/lib/sdam/monitor.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RTTSampler = exports2.MonitorInterval = exports2.RTTPinger = exports2.Monitor = exports2.ServerMonitoringMode = void 0;
    var timers_1 = require("timers");
    var bson_1 = require_bson2();
    var connect_1 = require_connect();
    var client_metadata_1 = require_client_metadata();
    var constants_1 = require_constants2();
    var error_1 = require_error();
    var mongo_logger_1 = require_mongo_logger();
    var mongo_types_1 = require_mongo_types();
    var utils_1 = require_utils();
    var common_1 = require_common();
    var events_1 = require_events();
    var server_1 = require_server();
    var STATE_IDLE = "idle";
    var STATE_MONITORING = "monitoring";
    var stateTransition = (0, utils_1.makeStateMachine)({
      [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, STATE_IDLE, common_1.STATE_CLOSED],
      [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, STATE_MONITORING],
      [STATE_IDLE]: [STATE_IDLE, STATE_MONITORING, common_1.STATE_CLOSING],
      [STATE_MONITORING]: [STATE_MONITORING, STATE_IDLE, common_1.STATE_CLOSING]
    });
    var INVALID_REQUEST_CHECK_STATES = /* @__PURE__ */ new Set([common_1.STATE_CLOSING, common_1.STATE_CLOSED, STATE_MONITORING]);
    function isInCloseState(monitor) {
      return monitor.s.state === common_1.STATE_CLOSED || monitor.s.state === common_1.STATE_CLOSING;
    }
    exports2.ServerMonitoringMode = Object.freeze({
      auto: "auto",
      poll: "poll",
      stream: "stream"
    });
    var Monitor = class extends mongo_types_1.TypedEventEmitter {
      constructor(server, options) {
        super();
        this.component = mongo_logger_1.MongoLoggableComponent.TOPOLOGY;
        this.on("error", utils_1.noop);
        this.server = server;
        this.connection = null;
        this.cancellationToken = new mongo_types_1.CancellationToken();
        this.cancellationToken.setMaxListeners(Infinity);
        this.monitorId = void 0;
        this.s = {
          state: common_1.STATE_CLOSED
        };
        this.address = server.description.address;
        this.options = Object.freeze({
          connectTimeoutMS: options.connectTimeoutMS ?? 1e4,
          heartbeatFrequencyMS: options.heartbeatFrequencyMS ?? 1e4,
          minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS ?? 500,
          serverMonitoringMode: options.serverMonitoringMode
        });
        this.isRunningInFaasEnv = (0, client_metadata_1.getFAASEnv)() != null;
        this.mongoLogger = this.server.topology.client?.mongoLogger;
        this.rttSampler = new RTTSampler(10);
        const cancellationToken = this.cancellationToken;
        const connectOptions = {
          id: "<monitor>",
          generation: server.pool.generation,
          cancellationToken,
          hostAddress: server.description.hostAddress,
          ...options,
          // force BSON serialization options
          raw: false,
          useBigInt64: false,
          promoteLongs: true,
          promoteValues: true,
          promoteBuffers: true
        };
        delete connectOptions.credentials;
        if (connectOptions.autoEncrypter) {
          delete connectOptions.autoEncrypter;
        }
        this.connectOptions = Object.freeze(connectOptions);
      }
      connect() {
        if (this.s.state !== common_1.STATE_CLOSED) {
          return;
        }
        const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS;
        const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS;
        this.monitorId = new MonitorInterval(monitorServer(this), {
          heartbeatFrequencyMS,
          minHeartbeatFrequencyMS,
          immediate: true
        });
      }
      requestCheck() {
        if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) {
          return;
        }
        this.monitorId?.wake();
      }
      reset() {
        const topologyVersion = this.server.description.topologyVersion;
        if (isInCloseState(this) || topologyVersion == null) {
          return;
        }
        stateTransition(this, common_1.STATE_CLOSING);
        resetMonitorState(this);
        stateTransition(this, STATE_IDLE);
        const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS;
        const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS;
        this.monitorId = new MonitorInterval(monitorServer(this), {
          heartbeatFrequencyMS,
          minHeartbeatFrequencyMS
        });
      }
      close() {
        if (isInCloseState(this)) {
          return;
        }
        stateTransition(this, common_1.STATE_CLOSING);
        resetMonitorState(this);
        this.emit("close");
        stateTransition(this, common_1.STATE_CLOSED);
      }
      get roundTripTime() {
        return this.rttSampler.average();
      }
      get minRoundTripTime() {
        return this.rttSampler.min();
      }
      get latestRtt() {
        return this.rttSampler.last;
      }
      addRttSample(rtt) {
        this.rttSampler.addSample(rtt);
      }
      clearRttSamples() {
        this.rttSampler.clear();
      }
    };
    exports2.Monitor = Monitor;
    function resetMonitorState(monitor) {
      monitor.monitorId?.stop();
      monitor.monitorId = void 0;
      monitor.rttPinger?.close();
      monitor.rttPinger = void 0;
      monitor.cancellationToken.emit("cancel");
      monitor.connection?.destroy();
      monitor.connection = null;
      monitor.clearRttSamples();
    }
    function useStreamingProtocol(monitor, topologyVersion) {
      if (topologyVersion == null)
        return false;
      const serverMonitoringMode = monitor.options.serverMonitoringMode;
      if (serverMonitoringMode === exports2.ServerMonitoringMode.poll)
        return false;
      if (serverMonitoringMode === exports2.ServerMonitoringMode.stream)
        return true;
      if (monitor.isRunningInFaasEnv)
        return false;
      return true;
    }
    function checkServer(monitor, callback) {
      let start;
      let awaited;
      const topologyVersion = monitor.server.description.topologyVersion;
      const isAwaitable = useStreamingProtocol(monitor, topologyVersion);
      monitor.emitAndLogHeartbeat(server_1.Server.SERVER_HEARTBEAT_STARTED, monitor.server.topology.s.id, void 0, new events_1.ServerHeartbeatStartedEvent(monitor.address, isAwaitable));
      function onHeartbeatFailed(err) {
        monitor.connection?.destroy();
        monitor.connection = null;
        monitor.emitAndLogHeartbeat(server_1.Server.SERVER_HEARTBEAT_FAILED, monitor.server.topology.s.id, void 0, new events_1.ServerHeartbeatFailedEvent(monitor.address, (0, utils_1.calculateDurationInMs)(start), err, awaited));
        const error51 = !(err instanceof error_1.MongoError) ? new error_1.MongoError(error_1.MongoError.buildErrorMessage(err), { cause: err }) : err;
        error51.addErrorLabel(error_1.MongoErrorLabel.ResetPool);
        if (error51 instanceof error_1.MongoNetworkTimeoutError) {
          error51.addErrorLabel(error_1.MongoErrorLabel.InterruptInUseConnections);
        }
        monitor.emit("resetServer", error51);
        callback(err);
      }
      function onHeartbeatSucceeded(hello) {
        if (!("isWritablePrimary" in hello)) {
          hello.isWritablePrimary = hello[constants_1.LEGACY_HELLO_COMMAND];
        }
        const duration3 = isAwaitable && monitor.rttPinger ? monitor.rttPinger.latestRtt ?? (0, utils_1.calculateDurationInMs)(start) : (0, utils_1.calculateDurationInMs)(start);
        monitor.addRttSample(duration3);
        monitor.emitAndLogHeartbeat(server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, monitor.server.topology.s.id, hello.connectionId, new events_1.ServerHeartbeatSucceededEvent(monitor.address, duration3, hello, isAwaitable));
        if (isAwaitable) {
          monitor.emitAndLogHeartbeat(server_1.Server.SERVER_HEARTBEAT_STARTED, monitor.server.topology.s.id, void 0, new events_1.ServerHeartbeatStartedEvent(monitor.address, true));
          start = (0, utils_1.processTimeMS)();
        } else {
          monitor.rttPinger?.close();
          monitor.rttPinger = void 0;
          callback(void 0, hello);
        }
      }
      const { connection } = monitor;
      if (connection && !connection.closed) {
        const { serverApi, helloOk } = connection;
        const connectTimeoutMS = monitor.options.connectTimeoutMS;
        const maxAwaitTimeMS = monitor.options.heartbeatFrequencyMS;
        const cmd = {
          [serverApi?.version || helloOk ? "hello" : constants_1.LEGACY_HELLO_COMMAND]: 1,
          ...isAwaitable && topologyVersion ? { maxAwaitTimeMS, topologyVersion: makeTopologyVersion(topologyVersion) } : {}
        };
        const options = isAwaitable ? {
          socketTimeoutMS: connectTimeoutMS ? connectTimeoutMS + maxAwaitTimeMS : 0,
          exhaustAllowed: true
        } : { socketTimeoutMS: connectTimeoutMS };
        if (isAwaitable && monitor.rttPinger == null) {
          monitor.rttPinger = new RTTPinger(monitor);
        }
        start = (0, utils_1.processTimeMS)();
        if (isAwaitable) {
          awaited = true;
          return connection.exhaustCommand((0, utils_1.ns)("admin.$cmd"), cmd, options, (error51, hello) => {
            if (error51)
              return onHeartbeatFailed(error51);
            return onHeartbeatSucceeded(hello);
          });
        }
        awaited = false;
        connection.command((0, utils_1.ns)("admin.$cmd"), cmd, options).then(onHeartbeatSucceeded, onHeartbeatFailed);
        return;
      }
      (async () => {
        const socket = await (0, connect_1.makeSocket)(monitor.connectOptions);
        const connection2 = (0, connect_1.makeConnection)(monitor.connectOptions, socket);
        start = (0, utils_1.processTimeMS)();
        try {
          await (0, connect_1.performInitialHandshake)(connection2, monitor.connectOptions);
          return connection2;
        } catch (error51) {
          connection2.destroy();
          throw error51;
        }
      })().then((connection2) => {
        if (isInCloseState(monitor)) {
          connection2.destroy();
          return;
        }
        const duration3 = (0, utils_1.calculateDurationInMs)(start);
        monitor.addRttSample(duration3);
        monitor.connection = connection2;
        monitor.emitAndLogHeartbeat(server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, monitor.server.topology.s.id, connection2.hello?.connectionId, new events_1.ServerHeartbeatSucceededEvent(monitor.address, duration3, connection2.hello, useStreamingProtocol(monitor, connection2.hello?.topologyVersion)));
        callback(void 0, connection2.hello);
      }, (error51) => {
        monitor.connection = null;
        awaited = false;
        onHeartbeatFailed(error51);
      });
    }
    function monitorServer(monitor) {
      return (callback) => {
        if (monitor.s.state === STATE_MONITORING) {
          queueMicrotask(callback);
          return;
        }
        stateTransition(monitor, STATE_MONITORING);
        function done() {
          if (!isInCloseState(monitor)) {
            stateTransition(monitor, STATE_IDLE);
          }
          callback();
        }
        checkServer(monitor, (err, hello) => {
          if (err) {
            if (monitor.server.description.type === common_1.ServerType.Unknown) {
              return done();
            }
          }
          if (useStreamingProtocol(monitor, hello?.topologyVersion)) {
            (0, timers_1.setTimeout)(() => {
              if (!isInCloseState(monitor)) {
                monitor.monitorId?.wake();
              }
            }, 0);
          }
          done();
        });
      };
    }
    function makeTopologyVersion(tv) {
      return {
        processId: tv.processId,
        // tests mock counter as just number, but in a real situation counter should always be a Long
        // TODO(NODE-2674): Preserve int64 sent from MongoDB
        counter: bson_1.Long.isLong(tv.counter) ? tv.counter : bson_1.Long.fromNumber(tv.counter)
      };
    }
    var RTTPinger = class {
      constructor(monitor) {
        this.connection = void 0;
        this.cancellationToken = monitor.cancellationToken;
        this.closed = false;
        this.monitor = monitor;
        this.latestRtt = monitor.latestRtt ?? void 0;
        const heartbeatFrequencyMS = monitor.options.heartbeatFrequencyMS;
        this.monitorId = (0, timers_1.setTimeout)(() => this.measureRoundTripTime(), heartbeatFrequencyMS);
      }
      get roundTripTime() {
        return this.monitor.roundTripTime;
      }
      get minRoundTripTime() {
        return this.monitor.minRoundTripTime;
      }
      close() {
        this.closed = true;
        (0, timers_1.clearTimeout)(this.monitorId);
        this.connection?.destroy();
        this.connection = void 0;
      }
      measureAndReschedule(start, conn) {
        if (this.closed) {
          conn?.destroy();
          return;
        }
        if (this.connection == null) {
          this.connection = conn;
        }
        this.latestRtt = (0, utils_1.calculateDurationInMs)(start);
        this.monitorId = (0, timers_1.setTimeout)(() => this.measureRoundTripTime(), this.monitor.options.heartbeatFrequencyMS);
      }
      measureRoundTripTime() {
        const start = (0, utils_1.processTimeMS)();
        if (this.closed) {
          return;
        }
        const connection = this.connection;
        if (connection == null) {
          (0, connect_1.connect)(this.monitor.connectOptions).then((connection2) => {
            this.measureAndReschedule(start, connection2);
          }, () => {
            this.connection = void 0;
          });
          return;
        }
        const commandName = connection.serverApi?.version || connection.helloOk ? "hello" : constants_1.LEGACY_HELLO_COMMAND;
        connection.command((0, utils_1.ns)("admin.$cmd"), { [commandName]: 1 }, void 0).then(() => this.measureAndReschedule(start), () => {
          this.connection?.destroy();
          this.connection = void 0;
          return;
        });
      }
    };
    exports2.RTTPinger = RTTPinger;
    var MonitorInterval = class {
      constructor(fn, options = {}) {
        this.isExpeditedCallToFnScheduled = false;
        this.stopped = false;
        this.isExecutionInProgress = false;
        this.hasExecutedOnce = false;
        this._executeAndReschedule = () => {
          if (this.stopped)
            return;
          if (this.timerId) {
            (0, timers_1.clearTimeout)(this.timerId);
          }
          this.isExpeditedCallToFnScheduled = false;
          this.isExecutionInProgress = true;
          this.fn(() => {
            this.lastExecutionEnded = (0, utils_1.processTimeMS)();
            this.isExecutionInProgress = false;
            this._reschedule(this.heartbeatFrequencyMS);
          });
        };
        this.fn = fn;
        this.lastExecutionEnded = -Infinity;
        this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 1e3;
        this.minHeartbeatFrequencyMS = options.minHeartbeatFrequencyMS ?? 500;
        if (options.immediate) {
          this._executeAndReschedule();
        } else {
          this._reschedule(void 0);
        }
      }
      wake() {
        const currentTime = (0, utils_1.processTimeMS)();
        const timeSinceLastCall = currentTime - this.lastExecutionEnded;
        if (timeSinceLastCall < 0) {
          return this._executeAndReschedule();
        }
        if (this.isExecutionInProgress) {
          return;
        }
        if (this.isExpeditedCallToFnScheduled) {
          return;
        }
        if (timeSinceLastCall < this.minHeartbeatFrequencyMS) {
          this.isExpeditedCallToFnScheduled = true;
          this._reschedule(this.minHeartbeatFrequencyMS - timeSinceLastCall);
          return;
        }
        this._executeAndReschedule();
      }
      stop() {
        this.stopped = true;
        if (this.timerId) {
          (0, timers_1.clearTimeout)(this.timerId);
          this.timerId = void 0;
        }
        this.lastExecutionEnded = -Infinity;
        this.isExpeditedCallToFnScheduled = false;
      }
      toString() {
        return JSON.stringify(this);
      }
      toJSON() {
        const currentTime = (0, utils_1.processTimeMS)();
        const timeSinceLastCall = currentTime - this.lastExecutionEnded;
        return {
          timerId: this.timerId != null ? "set" : "cleared",
          lastCallTime: this.lastExecutionEnded,
          isExpeditedCheckScheduled: this.isExpeditedCallToFnScheduled,
          stopped: this.stopped,
          heartbeatFrequencyMS: this.heartbeatFrequencyMS,
          minHeartbeatFrequencyMS: this.minHeartbeatFrequencyMS,
          currentTime,
          timeSinceLastCall
        };
      }
      _reschedule(ms) {
        if (this.stopped)
          return;
        if (this.timerId) {
          (0, timers_1.clearTimeout)(this.timerId);
        }
        this.timerId = (0, timers_1.setTimeout)(this._executeAndReschedule, ms || this.heartbeatFrequencyMS);
      }
    };
    exports2.MonitorInterval = MonitorInterval;
    var RTTSampler = class {
      constructor(windowSize = 10) {
        this.rttSamples = new Float64Array(windowSize);
        this.length = 0;
        this.writeIndex = 0;
      }
      /**
       * Adds an rtt sample to the end of the circular buffer
       * When `windowSize` samples have been collected, `addSample` overwrites the least recently added
       * sample
       */
      addSample(sample) {
        this.rttSamples[this.writeIndex++] = sample;
        if (this.length < this.rttSamples.length) {
          this.length++;
        }
        this.writeIndex %= this.rttSamples.length;
      }
      /**
       * When \< 2 samples have been collected, returns 0
       * Otherwise computes the minimum value samples contained in the buffer
       */
      min() {
        if (this.length < 2)
          return 0;
        let min = this.rttSamples[0];
        for (let i2 = 1; i2 < this.length; i2++) {
          if (this.rttSamples[i2] < min)
            min = this.rttSamples[i2];
        }
        return min;
      }
      /**
       * Returns mean of samples contained in the buffer
       */
      average() {
        if (this.length === 0)
          return 0;
        let sum = 0;
        for (let i2 = 0; i2 < this.length; i2++) {
          sum += this.rttSamples[i2];
        }
        return sum / this.length;
      }
      /**
       * Returns most recently inserted element in the buffer
       * Returns null if the buffer is empty
       * */
      get last() {
        if (this.length === 0)
          return null;
        return this.rttSamples[this.writeIndex === 0 ? this.length - 1 : this.writeIndex - 1];
      }
      /**
       * Clear the buffer
       * NOTE: this does not overwrite the data held in the internal array, just the pointers into
       * this array
       */
      clear() {
        this.length = 0;
        this.writeIndex = 0;
      }
    };
    exports2.RTTSampler = RTTSampler;
  }
});

// node_modules/mongodb/lib/connection_string.js
var require_connection_string = __commonJS({
  "node_modules/mongodb/lib/connection_string.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DEFAULT_OPTIONS = exports2.OPTIONS = void 0;
    exports2.resolveSRVRecord = resolveSRVRecord;
    exports2.parseOptions = parseOptions;
    var dns2 = require("dns");
    var mongodb_connection_string_url_1 = require_lib2();
    var process4 = require("process");
    var url_1 = require("url");
    var mongo_credentials_1 = require_mongo_credentials();
    var providers_1 = require_providers();
    var compression_1 = require_compression();
    var encrypter_1 = require_encrypter();
    var error_1 = require_error();
    var mongo_client_1 = require_mongo_client();
    var mongo_logger_1 = require_mongo_logger();
    var read_concern_1 = require_read_concern();
    var read_preference_1 = require_read_preference();
    var runtime_adapters_1 = require_runtime_adapters();
    var monitor_1 = require_monitor();
    var utils_1 = require_utils();
    var write_concern_1 = require_write_concern();
    var VALID_TXT_RECORDS = ["authSource", "replicaSet", "loadBalanced"];
    var LB_SINGLE_HOST_ERROR = "loadBalanced option only supported with a single host in the URI";
    var LB_REPLICA_SET_ERROR = "loadBalanced option not supported with a replicaSet option";
    var LB_DIRECT_CONNECTION_ERROR = "loadBalanced option not supported when directConnection is provided";
    function retryDNSTimeoutFor(rrtype) {
      const resolve2 = rrtype === "SRV" ? (address) => dns2.promises.resolve(address, "SRV") : (address) => dns2.promises.resolve(address, "TXT");
      return async function dnsReqRetryTimeout(lookupAddress) {
        try {
          return await resolve2(lookupAddress);
        } catch (firstDNSError) {
          if (firstDNSError.code === dns2.TIMEOUT) {
            return await resolve2(lookupAddress);
          } else {
            throw firstDNSError;
          }
        }
      };
    }
    var resolveSrv = retryDNSTimeoutFor("SRV");
    var resolveTxt = retryDNSTimeoutFor("TXT");
    async function resolveSRVRecord(options) {
      if (typeof options.srvHost !== "string") {
        throw new error_1.MongoAPIError('Option "srvHost" must not be empty');
      }
      const lookupAddress = options.srvHost;
      const txtResolutionPromise = resolveTxt(lookupAddress);
      txtResolutionPromise.then(void 0, utils_1.squashError);
      const hostname3 = `_${options.srvServiceName}._tcp.${lookupAddress}`;
      const addresses = await resolveSrv(hostname3);
      if (addresses.length === 0) {
        throw new error_1.MongoAPIError("No addresses found at host");
      }
      for (const { name } of addresses) {
        (0, utils_1.checkParentDomainMatch)(name, lookupAddress);
      }
      const hostAddresses = addresses.map((r2) => utils_1.HostAddress.fromString(`${r2.name}:${r2.port ?? 27017}`));
      validateLoadBalancedOptions(hostAddresses, options, true);
      let record2;
      try {
        record2 = await txtResolutionPromise;
      } catch (error51) {
        if (error51.code !== "ENODATA" && error51.code !== "ENOTFOUND") {
          throw error51;
        }
        return hostAddresses;
      }
      if (record2.length > 1) {
        throw new error_1.MongoParseError("Multiple text records not allowed");
      }
      const txtRecordOptions = new url_1.URLSearchParams(record2[0].join(""));
      const txtRecordOptionKeys = [...txtRecordOptions.keys()];
      if (txtRecordOptionKeys.some((key) => !VALID_TXT_RECORDS.includes(key))) {
        throw new error_1.MongoParseError(`Text record may only set any of: ${VALID_TXT_RECORDS.join(", ")}`);
      }
      if (VALID_TXT_RECORDS.some((option) => txtRecordOptions.get(option) === "")) {
        throw new error_1.MongoParseError("Cannot have empty URI params in DNS TXT Record");
      }
      const source = txtRecordOptions.get("authSource") ?? void 0;
      const replicaSet = txtRecordOptions.get("replicaSet") ?? void 0;
      const loadBalanced = txtRecordOptions.get("loadBalanced") ?? void 0;
      if (!options.userSpecifiedAuthSource && source && options.credentials && !providers_1.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(options.credentials.mechanism)) {
        options.credentials = mongo_credentials_1.MongoCredentials.merge(options.credentials, { source });
      }
      if (!options.userSpecifiedReplicaSet && replicaSet) {
        options.replicaSet = replicaSet;
      }
      if (loadBalanced === "true") {
        options.loadBalanced = true;
      }
      if (options.replicaSet && options.srvMaxHosts > 0) {
        throw new error_1.MongoParseError("Cannot combine replicaSet option with srvMaxHosts");
      }
      validateLoadBalancedOptions(hostAddresses, options, true);
      return hostAddresses;
    }
    function checkTLSOptions(allOptions) {
      if (!allOptions)
        return;
      const check2 = (a, b) => {
        if (allOptions.has(a) && allOptions.has(b)) {
          throw new error_1.MongoAPIError(`The '${a}' option cannot be used with the '${b}' option`);
        }
      };
      check2("tlsInsecure", "tlsAllowInvalidCertificates");
      check2("tlsInsecure", "tlsAllowInvalidHostnames");
    }
    function getBoolean(name, value) {
      if (typeof value === "boolean")
        return value;
      switch (value) {
        case "true":
          return true;
        case "false":
          return false;
        default:
          throw new error_1.MongoParseError(`${name} must be either "true" or "false"`);
      }
    }
    function getIntFromOptions(name, value) {
      const parsedInt = (0, utils_1.parseInteger)(value);
      if (parsedInt != null) {
        return parsedInt;
      }
      throw new error_1.MongoParseError(`Expected ${name} to be stringified int value, got: ${value}`);
    }
    function getUIntFromOptions(name, value) {
      const parsedValue = getIntFromOptions(name, value);
      if (parsedValue < 0) {
        throw new error_1.MongoParseError(`${name} can only be a positive int value, got: ${value}`);
      }
      return parsedValue;
    }
    function* entriesFromString(value) {
      if (value === "") {
        return;
      }
      const keyValuePairs = value.split(",");
      for (const keyValue of keyValuePairs) {
        const [key, value2] = keyValue.split(/:(.*)/);
        if (value2 == null) {
          throw new error_1.MongoParseError("Cannot have undefined values in key value pairs");
        }
        yield [key, value2];
      }
    }
    var CaseInsensitiveMap = class extends Map {
      constructor(entries = []) {
        super(entries.map(([k, v]) => [k.toLowerCase(), v]));
      }
      has(k) {
        return super.has(k.toLowerCase());
      }
      get(k) {
        return super.get(k.toLowerCase());
      }
      set(k, v) {
        return super.set(k.toLowerCase(), v);
      }
      delete(k) {
        return super.delete(k.toLowerCase());
      }
    };
    function parseOptions(uri, mongoClient2 = void 0, options = {}) {
      if (mongoClient2 != null && !(mongoClient2 instanceof mongo_client_1.MongoClient)) {
        options = mongoClient2;
        mongoClient2 = void 0;
      }
      if (options.useBigInt64 && typeof options.promoteLongs === "boolean" && !options.promoteLongs) {
        throw new error_1.MongoAPIError("Must request either bigint or Long for int64 deserialization");
      }
      if (options.useBigInt64 && typeof options.promoteValues === "boolean" && !options.promoteValues) {
        throw new error_1.MongoAPIError("Must request either bigint or Long for int64 deserialization");
      }
      const url2 = new mongodb_connection_string_url_1.default(uri);
      const { hosts, isSRV } = url2;
      const mongoOptions = /* @__PURE__ */ Object.create(null);
      mongoOptions.hosts = isSRV ? [] : hosts.map(utils_1.HostAddress.fromString);
      const urlOptions = new CaseInsensitiveMap();
      if (url2.pathname !== "/" && url2.pathname !== "") {
        const dbName = decodeURIComponent(url2.pathname[0] === "/" ? url2.pathname.slice(1) : url2.pathname);
        if (dbName) {
          urlOptions.set("dbName", [dbName]);
        }
      }
      if (url2.username !== "") {
        const auth = {
          username: decodeURIComponent(url2.username)
        };
        if (typeof url2.password === "string") {
          auth.password = decodeURIComponent(url2.password);
        }
        urlOptions.set("auth", [auth]);
      }
      for (const key of url2.searchParams.keys()) {
        const values = url2.searchParams.getAll(key);
        const isReadPreferenceTags = /readPreferenceTags/i.test(key);
        if (!isReadPreferenceTags && values.length > 1) {
          throw new error_1.MongoInvalidArgumentError(`URI option "${key}" cannot appear more than once in the connection string`);
        }
        if (!isReadPreferenceTags && values.includes("")) {
          throw new error_1.MongoAPIError(`URI option "${key}" cannot be specified with no value`);
        }
        if (!urlOptions.has(key)) {
          urlOptions.set(key, values);
        }
      }
      const objectOptions = new CaseInsensitiveMap(Object.entries(options).filter(([, v]) => v != null));
      if (urlOptions.has("serverApi")) {
        throw new error_1.MongoParseError("URI cannot contain `serverApi`, it can only be passed to the client");
      }
      const uriMechanismProperties = urlOptions.get("authMechanismProperties");
      if (uriMechanismProperties) {
        for (const property of uriMechanismProperties) {
          if (/(^|,)ALLOWED_HOSTS:/.test(property)) {
            throw new error_1.MongoParseError("Auth mechanism property ALLOWED_HOSTS is not allowed in the connection string.");
          }
        }
      }
      if (objectOptions.has("loadBalanced")) {
        throw new error_1.MongoParseError("loadBalanced is only a valid option in the URI");
      }
      const allProvidedOptions = new CaseInsensitiveMap();
      const allProvidedKeys = /* @__PURE__ */ new Set([...urlOptions.keys(), ...objectOptions.keys()]);
      for (const key of allProvidedKeys) {
        const values = [];
        const objectOptionValue = objectOptions.get(key);
        if (objectOptionValue != null) {
          values.push(objectOptionValue);
        }
        const urlValues = urlOptions.get(key) ?? [];
        values.push(...urlValues);
        allProvidedOptions.set(key, values);
      }
      if (allProvidedOptions.has("tls") || allProvidedOptions.has("ssl")) {
        const tlsAndSslOpts = (allProvidedOptions.get("tls") || []).concat(allProvidedOptions.get("ssl") || []).map(getBoolean.bind(null, "tls/ssl"));
        if (new Set(tlsAndSslOpts).size !== 1) {
          throw new error_1.MongoParseError("All values of tls/ssl must be the same.");
        }
      }
      checkTLSOptions(allProvidedOptions);
      const unsupportedOptions = (0, utils_1.setDifference)(allProvidedKeys, Array.from(Object.keys(exports2.OPTIONS)).map((s2) => s2.toLowerCase()));
      if (unsupportedOptions.size !== 0) {
        const optionWord = unsupportedOptions.size > 1 ? "options" : "option";
        const isOrAre = unsupportedOptions.size > 1 ? "are" : "is";
        throw new error_1.MongoParseError(`${optionWord} ${Array.from(unsupportedOptions).join(", ")} ${isOrAre} not supported`);
      }
      for (const [key, descriptor] of Object.entries(exports2.OPTIONS)) {
        const values = allProvidedOptions.get(key);
        if (!values || values.length === 0) {
          if (exports2.DEFAULT_OPTIONS.has(key)) {
            setOption(mongoOptions, key, descriptor, [exports2.DEFAULT_OPTIONS.get(key)]);
          }
        } else {
          const { deprecated } = descriptor;
          if (deprecated) {
            const deprecatedMsg = typeof deprecated === "string" ? `: ${deprecated}` : "";
            (0, utils_1.emitWarning)(`${key} is a deprecated option${deprecatedMsg}`);
          }
          setOption(mongoOptions, key, descriptor, values);
        }
      }
      if (mongoOptions.credentials) {
        const isGssapi = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_GSSAPI;
        const isX509 = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_X509;
        const isAws = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_AWS;
        const isOidc = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_OIDC;
        if ((isGssapi || isX509) && allProvidedOptions.has("authSource") && mongoOptions.credentials.source !== "$external") {
          throw new error_1.MongoParseError(`authMechanism ${mongoOptions.credentials.mechanism} requires an authSource of '$external'`);
        }
        if (!(isGssapi || isX509 || isAws || isOidc) && mongoOptions.dbName && !allProvidedOptions.has("authSource")) {
          mongoOptions.credentials = mongo_credentials_1.MongoCredentials.merge(mongoOptions.credentials, {
            source: mongoOptions.dbName
          });
        }
        if (isAws) {
          const { username, password } = mongoOptions.credentials;
          if (username || password) {
            throw new error_1.MongoAPIError("username and password cannot be provided when using MONGODB-AWS. Credentials must be provided in a manner that can be read by the AWS SDK.");
          }
          if (mongoOptions.credentials.mechanismProperties.AWS_SESSION_TOKEN) {
            throw new error_1.MongoAPIError("AWS_SESSION_TOKEN cannot be provided when using MONGODB-AWS. Credentials must be provided in a manner that can be read by the AWS SDK.");
          }
        }
        mongoOptions.credentials.validate();
        if (mongoOptions.credentials.password === "" && mongoOptions.credentials.username === "" && mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT && Object.keys(mongoOptions.credentials.mechanismProperties).length === 0) {
          delete mongoOptions.credentials;
        }
      }
      if (!mongoOptions.dbName) {
        mongoOptions.dbName = "test";
      }
      validateLoadBalancedOptions(hosts, mongoOptions, isSRV);
      if (mongoClient2 && mongoOptions.autoEncryption) {
        encrypter_1.Encrypter.checkForMongoCrypt();
        mongoOptions.encrypter = new encrypter_1.Encrypter(mongoClient2, uri, options);
        mongoOptions.autoEncrypter = mongoOptions.encrypter.autoEncrypter;
      }
      mongoOptions.userSpecifiedAuthSource = objectOptions.has("authSource") || urlOptions.has("authSource");
      mongoOptions.userSpecifiedReplicaSet = objectOptions.has("replicaSet") || urlOptions.has("replicaSet");
      if (isSRV) {
        mongoOptions.srvHost = hosts[0];
        if (mongoOptions.directConnection) {
          throw new error_1.MongoAPIError("SRV URI does not support directConnection");
        }
        if (mongoOptions.srvMaxHosts > 0 && typeof mongoOptions.replicaSet === "string") {
          throw new error_1.MongoParseError("Cannot use srvMaxHosts option with replicaSet");
        }
        const noUserSpecifiedTLS = !objectOptions.has("tls") && !urlOptions.has("tls");
        const noUserSpecifiedSSL = !objectOptions.has("ssl") && !urlOptions.has("ssl");
        if (noUserSpecifiedTLS && noUserSpecifiedSSL) {
          mongoOptions.tls = true;
        }
      } else {
        const userSpecifiedSrvOptions = urlOptions.has("srvMaxHosts") || objectOptions.has("srvMaxHosts") || urlOptions.has("srvServiceName") || objectOptions.has("srvServiceName");
        if (userSpecifiedSrvOptions) {
          throw new error_1.MongoParseError("Cannot use srvMaxHosts or srvServiceName with a non-srv connection string");
        }
      }
      if (mongoOptions.directConnection && mongoOptions.hosts.length !== 1) {
        throw new error_1.MongoParseError("directConnection option requires exactly one host");
      }
      if (!mongoOptions.proxyHost && (mongoOptions.proxyPort || mongoOptions.proxyUsername || mongoOptions.proxyPassword)) {
        throw new error_1.MongoParseError("Must specify proxyHost if other proxy options are passed");
      }
      if (mongoOptions.proxyUsername && !mongoOptions.proxyPassword || !mongoOptions.proxyUsername && mongoOptions.proxyPassword) {
        throw new error_1.MongoParseError("Can only specify both of proxy username/password or neither");
      }
      const proxyOptions = ["proxyHost", "proxyPort", "proxyUsername", "proxyPassword"].map((key) => urlOptions.get(key) ?? []);
      if (proxyOptions.some((options2) => options2.length > 1)) {
        throw new error_1.MongoParseError("Proxy options cannot be specified multiple times in the connection string");
      }
      mongoOptions.mongoLoggerOptions = mongo_logger_1.MongoLogger.resolveOptions({
        MONGODB_LOG_COMMAND: process4.env.MONGODB_LOG_COMMAND,
        MONGODB_LOG_TOPOLOGY: process4.env.MONGODB_LOG_TOPOLOGY,
        MONGODB_LOG_SERVER_SELECTION: process4.env.MONGODB_LOG_SERVER_SELECTION,
        MONGODB_LOG_CONNECTION: process4.env.MONGODB_LOG_CONNECTION,
        MONGODB_LOG_CLIENT: process4.env.MONGODB_LOG_CLIENT,
        MONGODB_LOG_ALL: process4.env.MONGODB_LOG_ALL,
        MONGODB_LOG_MAX_DOCUMENT_LENGTH: process4.env.MONGODB_LOG_MAX_DOCUMENT_LENGTH,
        MONGODB_LOG_PATH: process4.env.MONGODB_LOG_PATH
      }, {
        mongodbLogPath: mongoOptions.mongodbLogPath,
        mongodbLogComponentSeverities: mongoOptions.mongodbLogComponentSeverities,
        mongodbLogMaxDocumentLength: mongoOptions.mongodbLogMaxDocumentLength
      });
      mongoOptions.runtime = (0, runtime_adapters_1.resolveRuntimeAdapters)(options);
      return mongoOptions;
    }
    function validateLoadBalancedOptions(hosts, mongoOptions, isSrv) {
      if (mongoOptions.loadBalanced) {
        if (hosts.length > 1) {
          throw new error_1.MongoParseError(LB_SINGLE_HOST_ERROR);
        }
        if (mongoOptions.replicaSet) {
          throw new error_1.MongoParseError(LB_REPLICA_SET_ERROR);
        }
        if (mongoOptions.directConnection) {
          throw new error_1.MongoParseError(LB_DIRECT_CONNECTION_ERROR);
        }
        if (isSrv && mongoOptions.srvMaxHosts > 0) {
          throw new error_1.MongoParseError("Cannot limit srv hosts with loadBalanced enabled");
        }
      }
      return;
    }
    function setOption(mongoOptions, key, descriptor, values) {
      const { target, type, transform: transform2 } = descriptor;
      const name = target ?? key;
      switch (type) {
        case "boolean":
          mongoOptions[name] = getBoolean(name, values[0]);
          break;
        case "int":
          mongoOptions[name] = getIntFromOptions(name, values[0]);
          break;
        case "uint":
          mongoOptions[name] = getUIntFromOptions(name, values[0]);
          break;
        case "string":
          if (values[0] == null) {
            break;
          }
          mongoOptions[name] = String(values[0]);
          break;
        case "record":
          if (!(0, utils_1.isRecord)(values[0])) {
            throw new error_1.MongoParseError(`${name} must be an object`);
          }
          mongoOptions[name] = values[0];
          break;
        case "any":
          mongoOptions[name] = values[0];
          break;
        default: {
          if (!transform2) {
            throw new error_1.MongoParseError("Descriptors missing a type must define a transform");
          }
          const transformValue = transform2({ name, options: mongoOptions, values });
          mongoOptions[name] = transformValue;
          break;
        }
      }
    }
    exports2.OPTIONS = {
      enableOverloadRetargeting: {
        default: false,
        type: "boolean"
      },
      appName: {
        type: "string"
      },
      auth: {
        target: "credentials",
        transform({ name, options, values: [value] }) {
          if (!(0, utils_1.isRecord)(value, ["username", "password"])) {
            throw new error_1.MongoParseError(`${name} must be an object with 'username' and 'password' properties`);
          }
          return mongo_credentials_1.MongoCredentials.merge(options.credentials, {
            username: value.username,
            password: value.password
          });
        }
      },
      authMechanism: {
        target: "credentials",
        transform({ options, values: [value] }) {
          const mechanisms = Object.values(providers_1.AuthMechanism);
          const [mechanism] = mechanisms.filter((m2) => m2.match(RegExp(String.raw`\b${value}\b`, "i")));
          if (!mechanism) {
            throw new error_1.MongoParseError(`authMechanism one of ${mechanisms}, got ${value}`);
          }
          let source = options.credentials?.source;
          if (mechanism === providers_1.AuthMechanism.MONGODB_PLAIN || providers_1.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(mechanism)) {
            source = "$external";
          }
          let password = options.credentials?.password;
          if (mechanism === providers_1.AuthMechanism.MONGODB_X509 && password === "") {
            password = void 0;
          }
          return mongo_credentials_1.MongoCredentials.merge(options.credentials, {
            mechanism,
            source,
            password
          });
        }
      },
      // Note that if the authMechanismProperties contain a TOKEN_RESOURCE that has a
      // comma in it, it MUST be supplied as a MongoClient option instead of in the
      // connection string.
      authMechanismProperties: {
        target: "credentials",
        transform({ options, values }) {
          let mechanismProperties = /* @__PURE__ */ Object.create(null);
          for (const optionValue of values) {
            if (typeof optionValue === "string") {
              for (const [key, value] of entriesFromString(optionValue)) {
                try {
                  mechanismProperties[key] = getBoolean(key, value);
                } catch {
                  mechanismProperties[key] = value;
                }
              }
            } else {
              if (!(0, utils_1.isRecord)(optionValue)) {
                throw new error_1.MongoParseError("AuthMechanismProperties must be an object");
              }
              mechanismProperties = { ...optionValue };
            }
          }
          return mongo_credentials_1.MongoCredentials.merge(options.credentials, {
            mechanismProperties
          });
        }
      },
      authSource: {
        target: "credentials",
        transform({ options, values: [value] }) {
          const source = String(value);
          return mongo_credentials_1.MongoCredentials.merge(options.credentials, { source });
        }
      },
      autoEncryption: {
        type: "record"
      },
      autoSelectFamily: {
        type: "boolean",
        default: true
      },
      autoSelectFamilyAttemptTimeout: {
        type: "uint"
      },
      bsonRegExp: {
        type: "boolean"
      },
      serverApi: {
        target: "serverApi",
        transform({ values: [version2] }) {
          const serverApiToValidate = typeof version2 === "string" ? { version: version2 } : version2;
          const versionToValidate = serverApiToValidate && serverApiToValidate.version;
          if (!versionToValidate) {
            throw new error_1.MongoParseError(`Invalid \`serverApi\` property; must specify a version from the following enum: ["${Object.values(mongo_client_1.ServerApiVersion).join('", "')}"]`);
          }
          if (!Object.values(mongo_client_1.ServerApiVersion).some((v) => v === versionToValidate)) {
            throw new error_1.MongoParseError(`Invalid server API version=${versionToValidate}; must be in the following enum: ["${Object.values(mongo_client_1.ServerApiVersion).join('", "')}"]`);
          }
          return serverApiToValidate;
        }
      },
      checkKeys: {
        type: "boolean"
      },
      compressors: {
        default: "none",
        target: "compressors",
        transform({ values }) {
          const compressionList = /* @__PURE__ */ new Set();
          for (const compVal of values) {
            const compValArray = typeof compVal === "string" ? compVal.split(",") : compVal;
            if (!Array.isArray(compValArray)) {
              throw new error_1.MongoInvalidArgumentError("compressors must be an array or a comma-delimited list of strings");
            }
            for (const c of compValArray) {
              if (Object.keys(compression_1.Compressor).includes(String(c))) {
                compressionList.add(String(c));
              } else {
                throw new error_1.MongoInvalidArgumentError(`${c} is not a valid compression mechanism. Must be one of: ${Object.keys(compression_1.Compressor)}.`);
              }
            }
          }
          return [...compressionList];
        }
      },
      connectTimeoutMS: {
        default: 3e4,
        type: "uint"
      },
      dbName: {
        type: "string"
      },
      directConnection: {
        default: false,
        type: "boolean"
      },
      driverInfo: {
        default: {},
        type: "record"
      },
      enableUtf8Validation: { type: "boolean", default: true },
      family: {
        transform({ name, values: [value] }) {
          const transformValue = getIntFromOptions(name, value);
          if (transformValue === 4 || transformValue === 6) {
            return transformValue;
          }
          throw new error_1.MongoParseError(`Option 'family' must be 4 or 6 got ${transformValue}.`);
        }
      },
      fieldsAsRaw: {
        type: "record"
      },
      forceServerObjectId: {
        default: false,
        type: "boolean"
      },
      fsync: {
        deprecated: "Please use journal instead",
        target: "writeConcern",
        transform({ name, options, values: [value] }) {
          const wc = write_concern_1.WriteConcern.fromOptions({
            writeConcern: {
              ...options.writeConcern,
              fsync: getBoolean(name, value)
            }
          });
          if (!wc)
            throw new error_1.MongoParseError(`Unable to make a writeConcern from fsync=${value}`);
          return wc;
        }
      },
      heartbeatFrequencyMS: {
        default: 1e4,
        type: "uint"
      },
      ignoreUndefined: {
        type: "boolean"
      },
      j: {
        deprecated: "Please use journal instead",
        target: "writeConcern",
        transform({ name, options, values: [value] }) {
          const wc = write_concern_1.WriteConcern.fromOptions({
            writeConcern: {
              ...options.writeConcern,
              journal: getBoolean(name, value)
            }
          });
          if (!wc)
            throw new error_1.MongoParseError(`Unable to make a writeConcern from journal=${value}`);
          return wc;
        }
      },
      journal: {
        target: "writeConcern",
        transform({ name, options, values: [value] }) {
          const wc = write_concern_1.WriteConcern.fromOptions({
            writeConcern: {
              ...options.writeConcern,
              journal: getBoolean(name, value)
            }
          });
          if (!wc)
            throw new error_1.MongoParseError(`Unable to make a writeConcern from journal=${value}`);
          return wc;
        }
      },
      loadBalanced: {
        default: false,
        type: "boolean"
      },
      localThresholdMS: {
        default: 15,
        type: "uint"
      },
      maxAdaptiveRetries: {
        default: 2,
        type: "uint"
      },
      maxConnecting: {
        default: 2,
        transform({ name, values: [value] }) {
          const maxConnecting = getUIntFromOptions(name, value);
          if (maxConnecting === 0) {
            throw new error_1.MongoInvalidArgumentError("maxConnecting must be > 0 if specified");
          }
          return maxConnecting;
        }
      },
      maxIdleTimeMS: {
        default: 0,
        type: "uint"
      },
      maxPoolSize: {
        default: 100,
        type: "uint"
      },
      maxStalenessSeconds: {
        target: "readPreference",
        transform({ name, options, values: [value] }) {
          const maxStalenessSeconds = getUIntFromOptions(name, value);
          if (options.readPreference) {
            return read_preference_1.ReadPreference.fromOptions({
              readPreference: { ...options.readPreference, maxStalenessSeconds }
            });
          } else {
            return new read_preference_1.ReadPreference("secondary", void 0, { maxStalenessSeconds });
          }
        }
      },
      minInternalBufferSize: {
        type: "uint"
      },
      minPoolSize: {
        default: 0,
        type: "uint"
      },
      minHeartbeatFrequencyMS: {
        default: 500,
        type: "uint"
      },
      monitorCommands: {
        default: false,
        type: "boolean"
      },
      name: {
        target: "driverInfo",
        transform({ values: [value], options }) {
          return { ...options.driverInfo, name: String(value) };
        }
      },
      noDelay: {
        default: true,
        type: "boolean"
      },
      pkFactory: {
        default: utils_1.DEFAULT_PK_FACTORY,
        transform({ values: [value] }) {
          if ((0, utils_1.isRecord)(value, ["createPk"]) && typeof value.createPk === "function") {
            return value;
          }
          throw new error_1.MongoParseError(`Option pkFactory must be an object with a createPk function, got ${value}`);
        }
      },
      promoteBuffers: {
        type: "boolean"
      },
      promoteLongs: {
        type: "boolean"
      },
      promoteValues: {
        type: "boolean"
      },
      useBigInt64: {
        type: "boolean"
      },
      proxyHost: {
        type: "string"
      },
      proxyPassword: {
        type: "string"
      },
      proxyPort: {
        type: "uint"
      },
      proxyUsername: {
        type: "string"
      },
      raw: {
        default: false,
        type: "boolean"
      },
      readConcern: {
        transform({ values: [value], options }) {
          if (value instanceof read_concern_1.ReadConcern || (0, utils_1.isRecord)(value, ["level"])) {
            return read_concern_1.ReadConcern.fromOptions({ ...options.readConcern, ...value });
          }
          throw new error_1.MongoParseError(`ReadConcern must be an object, got ${JSON.stringify(value)}`);
        }
      },
      readConcernLevel: {
        target: "readConcern",
        transform({ values: [level], options }) {
          return read_concern_1.ReadConcern.fromOptions({
            ...options.readConcern,
            level
          });
        }
      },
      readPreference: {
        default: read_preference_1.ReadPreference.primary,
        transform({ values: [value], options }) {
          if (value instanceof read_preference_1.ReadPreference) {
            return read_preference_1.ReadPreference.fromOptions({
              readPreference: { ...options.readPreference, ...value },
              ...value
            });
          }
          if ((0, utils_1.isRecord)(value, ["mode"])) {
            const rp = read_preference_1.ReadPreference.fromOptions({
              readPreference: { ...options.readPreference, ...value },
              ...value
            });
            if (rp)
              return rp;
            else
              throw new error_1.MongoParseError(`Cannot make read preference from ${JSON.stringify(value)}`);
          }
          if (typeof value === "string") {
            const rpOpts = {
              hedge: options.readPreference?.hedge,
              maxStalenessSeconds: options.readPreference?.maxStalenessSeconds
            };
            return new read_preference_1.ReadPreference(value, options.readPreference?.tags, rpOpts);
          }
          throw new error_1.MongoParseError(`Unknown ReadPreference value: ${value}`);
        }
      },
      readPreferenceTags: {
        target: "readPreference",
        transform({ values, options }) {
          const tags = Array.isArray(values[0]) ? values[0] : values;
          const readPreferenceTags = [];
          for (const tag of tags) {
            const readPreferenceTag = /* @__PURE__ */ Object.create(null);
            if (typeof tag === "string") {
              for (const [k, v] of entriesFromString(tag)) {
                readPreferenceTag[k] = v;
              }
            }
            if ((0, utils_1.isRecord)(tag)) {
              for (const [k, v] of Object.entries(tag)) {
                readPreferenceTag[k] = v;
              }
            }
            readPreferenceTags.push(readPreferenceTag);
          }
          return read_preference_1.ReadPreference.fromOptions({
            readPreference: options.readPreference,
            readPreferenceTags
          });
        }
      },
      replicaSet: {
        type: "string"
      },
      retryReads: {
        default: true,
        type: "boolean"
      },
      retryWrites: {
        default: true,
        type: "boolean"
      },
      runtimeAdapters: {
        type: "record"
      },
      serializeFunctions: {
        type: "boolean"
      },
      serverMonitoringMode: {
        default: "auto",
        transform({ values: [value] }) {
          if (!Object.values(monitor_1.ServerMonitoringMode).includes(value)) {
            throw new error_1.MongoParseError("serverMonitoringMode must be one of `auto`, `poll`, or `stream`");
          }
          return value;
        }
      },
      serverSelectionTimeoutMS: {
        default: 3e4,
        type: "uint"
      },
      servername: {
        type: "string"
      },
      socketTimeoutMS: {
        // TODO(NODE-6491): deprecated: 'Please use timeoutMS instead',
        default: 0,
        type: "uint"
      },
      srvMaxHosts: {
        type: "uint",
        default: 0
      },
      srvServiceName: {
        type: "string",
        default: "mongodb"
      },
      ssl: {
        target: "tls",
        type: "boolean"
      },
      timeoutMS: {
        type: "uint"
      },
      tls: {
        type: "boolean"
      },
      tlsAllowInvalidCertificates: {
        target: "rejectUnauthorized",
        transform({ name, values: [value] }) {
          return !getBoolean(name, value);
        }
      },
      tlsAllowInvalidHostnames: {
        target: "checkServerIdentity",
        transform({ name, values: [value] }) {
          return getBoolean(name, value) ? () => void 0 : void 0;
        }
      },
      tlsCAFile: {
        type: "string"
      },
      tlsCRLFile: {
        type: "string"
      },
      tlsCertificateKeyFile: {
        type: "string"
      },
      tlsCertificateKeyFilePassword: {
        target: "passphrase",
        type: "any"
      },
      tlsInsecure: {
        transform({ name, options, values: [value] }) {
          const tlsInsecure = getBoolean(name, value);
          if (tlsInsecure) {
            options.checkServerIdentity = () => void 0;
            options.rejectUnauthorized = false;
          } else {
            options.checkServerIdentity = options.tlsAllowInvalidHostnames ? () => void 0 : void 0;
            options.rejectUnauthorized = options.tlsAllowInvalidCertificates ? false : true;
          }
          return tlsInsecure;
        }
      },
      w: {
        target: "writeConcern",
        transform({ values: [value], options }) {
          return write_concern_1.WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, w: value } });
        }
      },
      waitQueueTimeoutMS: {
        // TODO(NODE-6491): deprecated: 'Please use timeoutMS instead',
        default: 0,
        type: "uint"
      },
      writeConcern: {
        target: "writeConcern",
        transform({ values: [value], options }) {
          if ((0, utils_1.isRecord)(value) || value instanceof write_concern_1.WriteConcern) {
            return write_concern_1.WriteConcern.fromOptions({
              writeConcern: {
                ...options.writeConcern,
                ...value
              }
            });
          } else if (value === "majority" || typeof value === "number") {
            return write_concern_1.WriteConcern.fromOptions({
              writeConcern: {
                ...options.writeConcern,
                w: value
              }
            });
          }
          throw new error_1.MongoParseError(`Invalid WriteConcern cannot parse: ${JSON.stringify(value)}`);
        }
      },
      wtimeout: {
        deprecated: "Please use wtimeoutMS instead",
        target: "writeConcern",
        transform({ values: [value], options }) {
          const wc = write_concern_1.WriteConcern.fromOptions({
            writeConcern: {
              ...options.writeConcern,
              wtimeout: getUIntFromOptions("wtimeout", value)
            }
          });
          if (wc)
            return wc;
          throw new error_1.MongoParseError(`Cannot make WriteConcern from wtimeout`);
        }
      },
      wtimeoutMS: {
        target: "writeConcern",
        transform({ values: [value], options }) {
          const wc = write_concern_1.WriteConcern.fromOptions({
            writeConcern: {
              ...options.writeConcern,
              wtimeoutMS: getUIntFromOptions("wtimeoutMS", value)
            }
          });
          if (wc)
            return wc;
          throw new error_1.MongoParseError(`Cannot make WriteConcern from wtimeout`);
        }
      },
      zlibCompressionLevel: {
        default: 0,
        type: "int"
      },
      mongodbLogPath: {
        transform({ values: [value] }) {
          if (!(typeof value === "string" && ["stderr", "stdout"].includes(value) || value && typeof value === "object" && "write" in value && typeof value.write === "function")) {
            throw new error_1.MongoAPIError(`Option 'mongodbLogPath' must be of type 'stderr' | 'stdout' | MongoDBLogWritable`);
          }
          return value;
        }
      },
      mongodbLogComponentSeverities: {
        transform({ values: [value] }) {
          if (typeof value !== "object" || !value) {
            throw new error_1.MongoAPIError(`Option 'mongodbLogComponentSeverities' must be a non-null object`);
          }
          for (const [k, v] of Object.entries(value)) {
            if (typeof v !== "string" || typeof k !== "string") {
              throw new error_1.MongoAPIError(`User input for option 'mongodbLogComponentSeverities' object cannot include a non-string key or value`);
            }
            if (!Object.values(mongo_logger_1.MongoLoggableComponent).some((val) => val === k) && k !== "default") {
              throw new error_1.MongoAPIError(`User input for option 'mongodbLogComponentSeverities' contains invalid key: ${k}`);
            }
            if (!Object.values(mongo_logger_1.SeverityLevel).some((val) => val === v)) {
              throw new error_1.MongoAPIError(`Option 'mongodbLogComponentSeverities' does not support ${v} as a value for ${k}`);
            }
          }
          return value;
        }
      },
      mongodbLogMaxDocumentLength: { type: "uint" },
      // Custom types for modifying core behavior
      connectionType: { type: "any" },
      srvPoller: { type: "any" },
      // Accepted Node.js Options
      allowPartialTrustChain: { type: "any" },
      minDHSize: { type: "any" },
      pskCallback: { type: "any" },
      secureContext: { type: "any" },
      enableTrace: { type: "any" },
      requestCert: { type: "any" },
      rejectUnauthorized: { type: "any" },
      checkServerIdentity: { type: "any" },
      keepAliveInitialDelay: { type: "any" },
      ALPNProtocols: { type: "any" },
      SNICallback: { type: "any" },
      session: { type: "any" },
      requestOCSP: { type: "any" },
      localAddress: { type: "any" },
      localPort: { type: "any" },
      hints: { type: "any" },
      lookup: { type: "any" },
      ca: { type: "any" },
      cert: { type: "any" },
      ciphers: { type: "any" },
      crl: { type: "any" },
      ecdhCurve: { type: "any" },
      key: { type: "any" },
      passphrase: { type: "any" },
      pfx: { type: "any" },
      secureProtocol: { type: "any" },
      index: { type: "any" },
      // Legacy options from v3 era
      __skipPingOnConnect: { type: "boolean" }
    };
    exports2.DEFAULT_OPTIONS = new CaseInsensitiveMap(Object.entries(exports2.OPTIONS).filter(([, descriptor]) => descriptor.default != null).map(([k, d]) => [k, d.default]));
  }
});

// node_modules/mongodb/lib/cmap/auth/aws4.js
var require_aws4 = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/aws4.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.aws4Sign = aws4Sign;
    var bson_1 = require_bson2();
    var getHexSha256 = async (str) => {
      const data = stringToBuffer(str);
      const hashBuffer = await crypto.subtle.digest("SHA-256", data);
      const hashHex = bson_1.ByteUtils.toHex(new Uint8Array(hashBuffer));
      return hashHex;
    };
    var getHmacSha256 = async (key, str) => {
      let keyData;
      if (typeof key === "string") {
        keyData = stringToBuffer(key);
      } else {
        keyData = key;
      }
      const importedKey = await crypto.subtle.importKey("raw", keyData, { name: "HMAC", hash: { name: "SHA-256" } }, false, ["sign"]);
      const strData = stringToBuffer(str);
      const signature = await crypto.subtle.sign("HMAC", importedKey, strData);
      const digest = new Uint8Array(signature);
      return digest;
    };
    var convertHeaderValue = (value) => {
      return value.toString().trim().replace(/\s+/g, " ");
    };
    function stringToBuffer(str) {
      const data = new Uint8Array(bson_1.ByteUtils.utf8ByteLength(str));
      bson_1.ByteUtils.encodeUTF8Into(data, str, 0);
      return data;
    }
    async function aws4Sign(options, credentials) {
      const date5 = options.date;
      const requestDateTime = date5.toISOString().replace(/[:-]|\.\d{3}/g, "");
      const requestDate = requestDateTime.substring(0, 8);
      const method = options.method;
      const canonicalUri = options.path;
      const canonicalQuerystring = "";
      const headers = new Headers({
        "content-length": convertHeaderValue(options.headers["Content-Length"]),
        "content-type": convertHeaderValue(options.headers["Content-Type"]),
        host: convertHeaderValue(options.host),
        "x-amz-date": convertHeaderValue(requestDateTime),
        "x-mongodb-gs2-cb-flag": convertHeaderValue(options.headers["X-MongoDB-GS2-CB-Flag"]),
        "x-mongodb-server-nonce": convertHeaderValue(options.headers["X-MongoDB-Server-Nonce"])
      });
      if ("sessionToken" in credentials && credentials.sessionToken) {
        headers.append("x-amz-security-token", convertHeaderValue(credentials.sessionToken));
      }
      const canonicalHeaders = Array.from(headers.entries()).map(([key, value]) => `${key.toLowerCase()}:${value}`).sort().join("\n");
      const canonicalHeaderNames = Array.from(headers.keys()).map((header) => header.toLowerCase());
      const signedHeaders = canonicalHeaderNames.sort().join(";");
      const hashedPayload = await getHexSha256(options.body);
      const canonicalRequest = [
        method,
        canonicalUri,
        canonicalQuerystring,
        canonicalHeaders + "\n",
        signedHeaders,
        hashedPayload
      ].join("\n");
      const hashedCanonicalRequest = await getHexSha256(canonicalRequest);
      const algorithm = "AWS4-HMAC-SHA256";
      const credentialScope = `${requestDate}/${options.region}/${options.service}/aws4_request`;
      const stringToSign = [algorithm, requestDateTime, credentialScope, hashedCanonicalRequest].join("\n");
      const dateKey = await getHmacSha256("AWS4" + credentials.secretAccessKey, requestDate);
      const dateRegionKey = await getHmacSha256(dateKey, options.region);
      const dateRegionServiceKey = await getHmacSha256(dateRegionKey, options.service);
      const signingKey = await getHmacSha256(dateRegionServiceKey, "aws4_request");
      const signatureBuffer = await getHmacSha256(signingKey, stringToSign);
      const signature = bson_1.ByteUtils.toHex(signatureBuffer);
      const authorizationHeader = [
        "AWS4-HMAC-SHA256 Credential=" + credentials.accessKeyId + "/" + credentialScope,
        "SignedHeaders=" + signedHeaders,
        "Signature=" + signature
      ].join(", ");
      return {
        Authorization: authorizationHeader,
        "X-Amz-Date": requestDateTime
      };
    }
  }
});

// node_modules/mongodb/lib/cmap/auth/mongodb_aws.js
var require_mongodb_aws = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/mongodb_aws.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MongoDBAWS = void 0;
    var bson_1 = require_bson2();
    var BSON = require_bson2();
    var error_1 = require_error();
    var utils_1 = require_utils();
    var auth_provider_1 = require_auth_provider();
    var aws_temporary_credentials_1 = require_aws_temporary_credentials();
    var aws4_1 = require_aws4();
    var mongo_credentials_1 = require_mongo_credentials();
    var providers_1 = require_providers();
    var ASCII_N = 110;
    var bsonOptions = {
      useBigInt64: false,
      promoteLongs: true,
      promoteValues: true,
      promoteBuffers: false,
      bsonRegExp: false
    };
    var MongoDBAWS = class extends auth_provider_1.AuthProvider {
      constructor(credentialProvider) {
        super();
        this.credentialFetcher = new aws_temporary_credentials_1.AWSSDKCredentialProvider(credentialProvider);
      }
      async auth(authContext) {
        const { connection } = authContext;
        if (!authContext.credentials) {
          throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials.");
        }
        if ((0, utils_1.maxWireVersion)(connection) < 9) {
          throw new error_1.MongoCompatibilityError("MONGODB-AWS authentication requires MongoDB version 4.4 or later");
        }
        authContext.credentials = await makeTempCredentials(authContext.credentials, this.credentialFetcher);
        const { credentials } = authContext;
        const accessKeyId = credentials.username;
        const secretAccessKey = credentials.password;
        const sessionToken = credentials.mechanismProperties.AWS_SESSION_TOKEN;
        const awsCredentials = sessionToken ? { accessKeyId, secretAccessKey, sessionToken } : { accessKeyId, secretAccessKey };
        const db = credentials.source;
        const nonce = await (0, utils_1.randomBytes)(32);
        const saslStart = {
          saslStart: 1,
          mechanism: "MONGODB-AWS",
          payload: BSON.serialize({ r: nonce, p: ASCII_N }, bsonOptions)
        };
        const saslStartResponse = await connection.command((0, utils_1.ns)(`${db}.$cmd`), saslStart, void 0);
        const serverResponse = BSON.deserialize(saslStartResponse.payload.buffer, bsonOptions);
        const host = serverResponse.h;
        const serverNonce = serverResponse.s.buffer;
        if (serverNonce.length !== 64) {
          throw new error_1.MongoRuntimeError(`Invalid server nonce length ${serverNonce.length}, expected 64`);
        }
        if (!bson_1.ByteUtils.equals(serverNonce.subarray(0, nonce.byteLength), nonce)) {
          throw new error_1.MongoRuntimeError("Server nonce does not begin with client nonce");
        }
        if (host.length < 1 || host.length > 255 || host.indexOf("..") !== -1) {
          throw new error_1.MongoRuntimeError(`Server returned an invalid host: "${host}"`);
        }
        const body = "Action=GetCallerIdentity&Version=2011-06-15";
        const headers = await (0, aws4_1.aws4Sign)({
          method: "POST",
          host,
          region: deriveRegion(serverResponse.h),
          service: "sts",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Content-Length": body.length,
            "X-MongoDB-Server-Nonce": bson_1.ByteUtils.toBase64(serverNonce),
            "X-MongoDB-GS2-CB-Flag": "n"
          },
          path: "/",
          body,
          date: /* @__PURE__ */ new Date()
        }, awsCredentials);
        const payload = {
          a: headers.Authorization,
          d: headers["X-Amz-Date"]
        };
        if (sessionToken) {
          payload.t = sessionToken;
        }
        const saslContinue = {
          saslContinue: 1,
          conversationId: saslStartResponse.conversationId,
          payload: BSON.serialize(payload, bsonOptions)
        };
        await connection.command((0, utils_1.ns)(`${db}.$cmd`), saslContinue, void 0);
      }
    };
    exports2.MongoDBAWS = MongoDBAWS;
    async function makeTempCredentials(credentials, awsCredentialFetcher) {
      function makeMongoCredentialsFromAWSTemp(creds) {
        if (!creds.AccessKeyId || !creds.SecretAccessKey) {
          throw new error_1.MongoMissingCredentialsError("Could not obtain temporary MONGODB-AWS credentials");
        }
        return new mongo_credentials_1.MongoCredentials({
          username: creds.AccessKeyId,
          password: creds.SecretAccessKey,
          source: credentials.source,
          mechanism: providers_1.AuthMechanism.MONGODB_AWS,
          mechanismProperties: {
            AWS_SESSION_TOKEN: creds.Token
          }
        });
      }
      const temporaryCredentials = await awsCredentialFetcher.getCredentials();
      return makeMongoCredentialsFromAWSTemp(temporaryCredentials);
    }
    function deriveRegion(host) {
      const parts = host.split(".");
      if (parts.length === 1 || parts[1] === "amazonaws") {
        return "us-east-1";
      }
      return parts[1];
    }
  }
});

// node_modules/mongodb/lib/cmap/auth/mongodb_oidc/command_builders.js
var require_command_builders = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/mongodb_oidc/command_builders.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.finishCommandDocument = finishCommandDocument;
    exports2.startCommandDocument = startCommandDocument;
    var bson_1 = require_bson2();
    var providers_1 = require_providers();
    function finishCommandDocument(token, conversationId) {
      if (conversationId != null) {
        return {
          saslContinue: 1,
          conversationId,
          payload: new bson_1.Binary(bson_1.BSON.serialize({ jwt: token }))
        };
      }
      return {
        saslStart: 1,
        mechanism: providers_1.AuthMechanism.MONGODB_OIDC,
        payload: new bson_1.Binary(bson_1.BSON.serialize({ jwt: token }))
      };
    }
    function startCommandDocument(credentials) {
      const payload = {};
      if (credentials.username) {
        payload.n = credentials.username;
      }
      return {
        saslStart: 1,
        autoAuthorize: 1,
        mechanism: providers_1.AuthMechanism.MONGODB_OIDC,
        payload: new bson_1.Binary(bson_1.BSON.serialize(payload))
      };
    }
  }
});

// node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_workflow.js
var require_callback_workflow = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_workflow.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CallbackWorkflow = exports2.AUTOMATED_TIMEOUT_MS = exports2.HUMAN_TIMEOUT_MS = void 0;
    var promises_1 = require("timers/promises");
    var error_1 = require_error();
    var utils_1 = require_utils();
    var command_builders_1 = require_command_builders();
    exports2.HUMAN_TIMEOUT_MS = 3e5;
    exports2.AUTOMATED_TIMEOUT_MS = 6e4;
    var RESULT_PROPERTIES = ["accessToken", "expiresInSeconds", "refreshToken"];
    var CALLBACK_RESULT_ERROR = "User provided OIDC callbacks must return a valid object with an accessToken.";
    var THROTTLE_MS = 100;
    var CallbackWorkflow = class {
      /**
       * Instantiate the callback workflow.
       */
      constructor(cache, callback) {
        this.cache = cache;
        this.callback = this.withLock(callback);
        this.lastExecutionTime = Date.now() - THROTTLE_MS;
      }
      /**
       * Get the document to add for speculative authentication. This also needs
       * to add a db field from the credentials source.
       */
      async speculativeAuth(connection, credentials) {
        if (this.cache.hasAccessToken) {
          const accessToken = this.cache.getAccessToken();
          connection.accessToken = accessToken;
          const document2 = (0, command_builders_1.finishCommandDocument)(accessToken);
          document2.db = credentials.source;
          return { speculativeAuthenticate: document2 };
        }
        return {};
      }
      /**
       * Reauthenticate the callback workflow. For this we invalidated the access token
       * in the cache and run the authentication steps again. No initial handshake needs
       * to be sent.
       */
      async reauthenticate(connection, credentials) {
        if (this.cache.hasAccessToken) {
          if (connection.accessToken === this.cache.getAccessToken()) {
            this.cache.removeAccessToken();
            delete connection.accessToken;
          } else {
            connection.accessToken = this.cache.getAccessToken();
          }
        }
        await this.execute(connection, credentials);
      }
      /**
       * Starts the callback authentication process. If there is a speculative
       * authentication document from the initial handshake, then we will use that
       * value to get the issuer, otherwise we will send the saslStart command.
       */
      async startAuthentication(connection, credentials, response) {
        let result;
        if (response?.speculativeAuthenticate) {
          result = response.speculativeAuthenticate;
        } else {
          result = await connection.command((0, utils_1.ns)(credentials.source), (0, command_builders_1.startCommandDocument)(credentials), void 0);
        }
        return result;
      }
      /**
       * Finishes the callback authentication process.
       */
      async finishAuthentication(connection, credentials, token, conversationId) {
        await connection.command((0, utils_1.ns)(credentials.source), (0, command_builders_1.finishCommandDocument)(token, conversationId), void 0);
      }
      /**
       * Executes the callback and validates the output.
       */
      async executeAndValidateCallback(params) {
        const result = await this.callback(params);
        if (isCallbackResultInvalid(result)) {
          throw new error_1.MongoMissingCredentialsError(CALLBACK_RESULT_ERROR);
        }
        return result;
      }
      /**
       * Ensure the callback is only executed one at a time and throttles the calls
       * to every 100ms.
       */
      withLock(callback) {
        let lock = Promise.resolve();
        return async (params) => {
          await lock;
          lock = lock.catch(() => null).then(async () => {
            const difference = Date.now() - this.lastExecutionTime;
            if (difference <= THROTTLE_MS) {
              await (0, promises_1.setTimeout)(THROTTLE_MS - difference, { signal: params.timeoutContext });
            }
            this.lastExecutionTime = Date.now();
            return await callback(params);
          });
          return await lock;
        };
      }
    };
    exports2.CallbackWorkflow = CallbackWorkflow;
    function isCallbackResultInvalid(tokenResult) {
      if (tokenResult == null || typeof tokenResult !== "object")
        return true;
      if (!("accessToken" in tokenResult))
        return true;
      return !Object.getOwnPropertyNames(tokenResult).every((prop) => RESULT_PROPERTIES.includes(prop));
    }
  }
});

// node_modules/mongodb/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js
var require_automated_callback_workflow = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AutomatedCallbackWorkflow = void 0;
    var error_1 = require_error();
    var timeout_1 = require_timeout();
    var mongodb_oidc_1 = require_mongodb_oidc();
    var callback_workflow_1 = require_callback_workflow();
    var AutomatedCallbackWorkflow = class extends callback_workflow_1.CallbackWorkflow {
      /**
       * Instantiate the human callback workflow.
       */
      constructor(cache, callback) {
        super(cache, callback);
      }
      /**
       * Execute the OIDC callback workflow.
       */
      async execute(connection, credentials) {
        if (this.cache.hasAccessToken) {
          const token = this.cache.getAccessToken();
          if (!connection.accessToken) {
            connection.accessToken = token;
          }
          try {
            return await this.finishAuthentication(connection, credentials, token);
          } catch (error51) {
            if (error51 instanceof error_1.MongoError && error51.code === error_1.MONGODB_ERROR_CODES.AuthenticationFailed) {
              this.cache.removeAccessToken();
              return await this.execute(connection, credentials);
            } else {
              throw error51;
            }
          }
        }
        const response = await this.fetchAccessToken(credentials);
        this.cache.put(response);
        connection.accessToken = response.accessToken;
        await this.finishAuthentication(connection, credentials, response.accessToken);
      }
      /**
       * Fetches the access token using the callback.
       */
      async fetchAccessToken(credentials) {
        const controller = new AbortController();
        const params = {
          timeoutContext: controller.signal,
          version: mongodb_oidc_1.OIDC_VERSION
        };
        if (credentials.username) {
          params.username = credentials.username;
        }
        if (credentials.mechanismProperties.TOKEN_RESOURCE) {
          params.tokenAudience = credentials.mechanismProperties.TOKEN_RESOURCE;
        }
        const timeout = timeout_1.Timeout.expires(callback_workflow_1.AUTOMATED_TIMEOUT_MS);
        try {
          return await Promise.race([this.executeAndValidateCallback(params), timeout]);
        } catch (error51) {
          if (timeout_1.TimeoutError.is(error51)) {
            controller.abort();
            throw new error_1.MongoOIDCError(`OIDC callback timed out after ${callback_workflow_1.AUTOMATED_TIMEOUT_MS}ms.`);
          }
          throw error51;
        } finally {
          timeout.clear();
        }
      }
    };
    exports2.AutomatedCallbackWorkflow = AutomatedCallbackWorkflow;
  }
});

// node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_machine_workflow.js
var require_azure_machine_workflow = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_machine_workflow.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.azureCallback = void 0;
    var azure_1 = require_azure();
    var error_1 = require_error();
    var utils_1 = require_utils();
    var AZURE_HEADERS = Object.freeze({ Metadata: "true", Accept: "application/json" });
    var ENDPOINT_RESULT_ERROR = "Azure endpoint did not return a value with only access_token and expires_in properties";
    var TOKEN_RESOURCE_MISSING_ERROR = "TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is azure.";
    var azureCallback = async (params) => {
      const tokenAudience = params.tokenAudience;
      const username = params.username;
      if (!tokenAudience) {
        throw new error_1.MongoAzureError(TOKEN_RESOURCE_MISSING_ERROR);
      }
      const response = await getAzureTokenData(tokenAudience, username);
      if (!isEndpointResultValid(response)) {
        throw new error_1.MongoAzureError(ENDPOINT_RESULT_ERROR);
      }
      return response;
    };
    exports2.azureCallback = azureCallback;
    async function getAzureTokenData(tokenAudience, username) {
      const url2 = new URL(azure_1.AZURE_BASE_URL);
      (0, azure_1.addAzureParams)(url2, tokenAudience, username);
      const response = await (0, utils_1.get)(url2, {
        headers: AZURE_HEADERS
      });
      if (response.status !== 200) {
        throw new error_1.MongoAzureError(`Status code ${response.status} returned from the Azure endpoint. Response body: ${response.body}`);
      }
      const result = JSON.parse(response.body);
      return {
        accessToken: result.access_token,
        expiresInSeconds: Number(result.expires_in)
      };
    }
    function isEndpointResultValid(token) {
      if (token == null || typeof token !== "object")
        return false;
      return "accessToken" in token && typeof token.accessToken === "string" && "expiresInSeconds" in token && typeof token.expiresInSeconds === "number";
    }
  }
});

// node_modules/mongodb/lib/cmap/auth/mongodb_oidc/gcp_machine_workflow.js
var require_gcp_machine_workflow = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/mongodb_oidc/gcp_machine_workflow.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.gcpCallback = void 0;
    var error_1 = require_error();
    var utils_1 = require_utils();
    var GCP_BASE_URL = "http://metadata/computeMetadata/v1/instance/service-accounts/default/identity";
    var GCP_HEADERS = Object.freeze({ "Metadata-Flavor": "Google" });
    var TOKEN_RESOURCE_MISSING_ERROR = "TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is gcp.";
    var gcpCallback = async (params) => {
      const tokenAudience = params.tokenAudience;
      if (!tokenAudience) {
        throw new error_1.MongoGCPError(TOKEN_RESOURCE_MISSING_ERROR);
      }
      return await getGcpTokenData(tokenAudience);
    };
    exports2.gcpCallback = gcpCallback;
    async function getGcpTokenData(tokenAudience) {
      const url2 = new URL(GCP_BASE_URL);
      url2.searchParams.append("audience", tokenAudience);
      const response = await (0, utils_1.get)(url2, {
        headers: GCP_HEADERS
      });
      if (response.status !== 200) {
        throw new error_1.MongoGCPError(`Status code ${response.status} returned from the GCP endpoint. Response body: ${response.body}`);
      }
      return { accessToken: response.body };
    }
  }
});

// node_modules/mongodb/lib/cmap/auth/mongodb_oidc/k8s_machine_workflow.js
var require_k8s_machine_workflow = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/mongodb_oidc/k8s_machine_workflow.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.k8sCallback = void 0;
    var promises_1 = require("fs/promises");
    var process4 = require("process");
    var FALLBACK_FILENAME = "/var/run/secrets/kubernetes.io/serviceaccount/token";
    var AZURE_FILENAME = "AZURE_FEDERATED_TOKEN_FILE";
    var AWS_FILENAME = "AWS_WEB_IDENTITY_TOKEN_FILE";
    var k8sCallback = async () => {
      let filename;
      if (process4.env[AZURE_FILENAME]) {
        filename = process4.env[AZURE_FILENAME];
      } else if (process4.env[AWS_FILENAME]) {
        filename = process4.env[AWS_FILENAME];
      } else {
        filename = FALLBACK_FILENAME;
      }
      const token = await (0, promises_1.readFile)(filename, "utf8");
      return { accessToken: token };
    };
    exports2.k8sCallback = k8sCallback;
  }
});

// node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_cache.js
var require_token_cache = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_cache.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.TokenCache = void 0;
    var error_1 = require_error();
    var MongoOIDCError = class extends error_1.MongoDriverError {
    };
    var TokenCache = class {
      get hasAccessToken() {
        return !!this.accessToken;
      }
      get hasRefreshToken() {
        return !!this.refreshToken;
      }
      get hasIdpInfo() {
        return !!this.idpInfo;
      }
      getAccessToken() {
        if (!this.accessToken) {
          throw new MongoOIDCError("Attempted to get an access token when none exists.");
        }
        return this.accessToken;
      }
      getRefreshToken() {
        if (!this.refreshToken) {
          throw new MongoOIDCError("Attempted to get a refresh token when none exists.");
        }
        return this.refreshToken;
      }
      getIdpInfo() {
        if (!this.idpInfo) {
          throw new MongoOIDCError("Attempted to get IDP information when none exists.");
        }
        return this.idpInfo;
      }
      put(response, idpInfo) {
        this.accessToken = response.accessToken;
        this.refreshToken = response.refreshToken;
        this.expiresInSeconds = response.expiresInSeconds;
        if (idpInfo) {
          this.idpInfo = idpInfo;
        }
      }
      removeAccessToken() {
        this.accessToken = void 0;
      }
      removeRefreshToken() {
        this.refreshToken = void 0;
      }
    };
    exports2.TokenCache = TokenCache;
  }
});

// node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_machine_workflow.js
var require_token_machine_workflow = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_machine_workflow.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.tokenMachineCallback = void 0;
    var fs2 = require("fs");
    var process4 = require("process");
    var error_1 = require_error();
    var TOKEN_MISSING_ERROR = "OIDC_TOKEN_FILE must be set in the environment.";
    var tokenMachineCallback = async () => {
      const tokenFile = process4.env.OIDC_TOKEN_FILE;
      if (!tokenFile) {
        throw new error_1.MongoAWSError(TOKEN_MISSING_ERROR);
      }
      const token = await fs2.promises.readFile(tokenFile, "utf8");
      return { accessToken: token };
    };
    exports2.tokenMachineCallback = tokenMachineCallback;
  }
});

// node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js
var require_mongodb_oidc = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MongoDBOIDC = exports2.OIDC_WORKFLOWS = exports2.OIDC_VERSION = void 0;
    var error_1 = require_error();
    var auth_provider_1 = require_auth_provider();
    var automated_callback_workflow_1 = require_automated_callback_workflow();
    var azure_machine_workflow_1 = require_azure_machine_workflow();
    var gcp_machine_workflow_1 = require_gcp_machine_workflow();
    var k8s_machine_workflow_1 = require_k8s_machine_workflow();
    var token_cache_1 = require_token_cache();
    var token_machine_workflow_1 = require_token_machine_workflow();
    var MISSING_CREDENTIALS_ERROR = "AuthContext must provide credentials.";
    exports2.OIDC_VERSION = 1;
    exports2.OIDC_WORKFLOWS = /* @__PURE__ */ new Map();
    exports2.OIDC_WORKFLOWS.set("test", () => new automated_callback_workflow_1.AutomatedCallbackWorkflow(new token_cache_1.TokenCache(), token_machine_workflow_1.tokenMachineCallback));
    exports2.OIDC_WORKFLOWS.set("azure", () => new automated_callback_workflow_1.AutomatedCallbackWorkflow(new token_cache_1.TokenCache(), azure_machine_workflow_1.azureCallback));
    exports2.OIDC_WORKFLOWS.set("gcp", () => new automated_callback_workflow_1.AutomatedCallbackWorkflow(new token_cache_1.TokenCache(), gcp_machine_workflow_1.gcpCallback));
    exports2.OIDC_WORKFLOWS.set("k8s", () => new automated_callback_workflow_1.AutomatedCallbackWorkflow(new token_cache_1.TokenCache(), k8s_machine_workflow_1.k8sCallback));
    var MongoDBOIDC = class extends auth_provider_1.AuthProvider {
      /**
       * Instantiate the auth provider.
       */
      constructor(workflow) {
        super();
        if (!workflow) {
          throw new error_1.MongoInvalidArgumentError("No workflow provided to the OIDC auth provider.");
        }
        this.workflow = workflow;
      }
      /**
       * Authenticate using OIDC
       */
      async auth(authContext) {
        const { connection, reauthenticating, response } = authContext;
        if (response?.speculativeAuthenticate?.done && !reauthenticating) {
          return;
        }
        const credentials = getCredentials(authContext);
        if (reauthenticating) {
          await this.workflow.reauthenticate(connection, credentials);
        } else {
          await this.workflow.execute(connection, credentials, response);
        }
      }
      /**
       * Add the speculative auth for the initial handshake.
       */
      async prepare(handshakeDoc, authContext) {
        const { connection } = authContext;
        const credentials = getCredentials(authContext);
        const result = await this.workflow.speculativeAuth(connection, credentials);
        return { ...handshakeDoc, ...result };
      }
    };
    exports2.MongoDBOIDC = MongoDBOIDC;
    function getCredentials(authContext) {
      const { credentials } = authContext;
      if (!credentials) {
        throw new error_1.MongoMissingCredentialsError(MISSING_CREDENTIALS_ERROR);
      }
      return credentials;
    }
  }
});

// node_modules/mongodb/lib/cmap/auth/mongodb_oidc/human_callback_workflow.js
var require_human_callback_workflow = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/mongodb_oidc/human_callback_workflow.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.HumanCallbackWorkflow = void 0;
    var bson_1 = require_bson2();
    var error_1 = require_error();
    var timeout_1 = require_timeout();
    var mongodb_oidc_1 = require_mongodb_oidc();
    var callback_workflow_1 = require_callback_workflow();
    var HumanCallbackWorkflow = class extends callback_workflow_1.CallbackWorkflow {
      /**
       * Instantiate the human callback workflow.
       */
      constructor(cache, callback) {
        super(cache, callback);
      }
      /**
       * Execute the OIDC human callback workflow.
       */
      async execute(connection, credentials) {
        if (this.cache.hasAccessToken) {
          const token = this.cache.getAccessToken();
          connection.accessToken = token;
          try {
            return await this.finishAuthentication(connection, credentials, token);
          } catch (error51) {
            if (error51 instanceof error_1.MongoError && error51.code === error_1.MONGODB_ERROR_CODES.AuthenticationFailed) {
              this.cache.removeAccessToken();
              delete connection.accessToken;
              return await this.execute(connection, credentials);
            } else {
              throw error51;
            }
          }
        }
        if (this.cache.hasRefreshToken) {
          const refreshToken = this.cache.getRefreshToken();
          const result = await this.fetchAccessToken(this.cache.getIdpInfo(), credentials, refreshToken);
          this.cache.put(result);
          connection.accessToken = result.accessToken;
          try {
            return await this.finishAuthentication(connection, credentials, result.accessToken);
          } catch (error51) {
            if (error51 instanceof error_1.MongoError && error51.code === error_1.MONGODB_ERROR_CODES.AuthenticationFailed) {
              this.cache.removeRefreshToken();
              delete connection.accessToken;
              return await this.execute(connection, credentials);
            } else {
              throw error51;
            }
          }
        }
        const startResponse = await this.startAuthentication(connection, credentials);
        const conversationId = startResponse.conversationId;
        const idpInfo = bson_1.BSON.deserialize(startResponse.payload.buffer);
        const callbackResponse = await this.fetchAccessToken(idpInfo, credentials);
        this.cache.put(callbackResponse, idpInfo);
        connection.accessToken = callbackResponse.accessToken;
        return await this.finishAuthentication(connection, credentials, callbackResponse.accessToken, conversationId);
      }
      /**
       * Fetches an access token using the callback.
       */
      async fetchAccessToken(idpInfo, credentials, refreshToken) {
        const controller = new AbortController();
        const params = {
          timeoutContext: controller.signal,
          version: mongodb_oidc_1.OIDC_VERSION,
          idpInfo
        };
        if (credentials.username) {
          params.username = credentials.username;
        }
        if (refreshToken) {
          params.refreshToken = refreshToken;
        }
        const timeout = timeout_1.Timeout.expires(callback_workflow_1.HUMAN_TIMEOUT_MS);
        try {
          return await Promise.race([this.executeAndValidateCallback(params), timeout]);
        } catch (error51) {
          if (timeout_1.TimeoutError.is(error51)) {
            controller.abort();
            throw new error_1.MongoOIDCError(`OIDC callback timed out after ${callback_workflow_1.HUMAN_TIMEOUT_MS}ms.`);
          }
          throw error51;
        } finally {
          timeout.clear();
        }
      }
    };
    exports2.HumanCallbackWorkflow = HumanCallbackWorkflow;
  }
});

// node_modules/mongodb/lib/cmap/auth/plain.js
var require_plain = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/plain.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Plain = void 0;
    var bson_1 = require_bson2();
    var error_1 = require_error();
    var utils_1 = require_utils();
    var auth_provider_1 = require_auth_provider();
    var Plain = class extends auth_provider_1.AuthProvider {
      async auth(authContext) {
        const { connection, credentials } = authContext;
        if (!credentials) {
          throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials.");
        }
        const { username, password } = credentials;
        const payload = new bson_1.Binary(bson_1.ByteUtils.fromUTF8(`\0${username}\0${password}`));
        const command = {
          saslStart: 1,
          mechanism: "PLAIN",
          payload,
          autoAuthorize: 1
        };
        await connection.command((0, utils_1.ns)("$external.$cmd"), command, void 0);
      }
    };
    exports2.Plain = Plain;
  }
});

// node_modules/@mongodb-js/saslprep/dist/index.js
var require_dist3 = __commonJS({
  "node_modules/@mongodb-js/saslprep/dist/index.js"(exports2, module2) {
    "use strict";
    var getCodePoint = (character) => character.codePointAt(0);
    var first = (x2) => x2[0];
    var last = (x2) => x2[x2.length - 1];
    function toCodePoints(input) {
      const codepoints = [];
      const size = input.length;
      for (let i2 = 0; i2 < size; i2 += 1) {
        const before = input.charCodeAt(i2);
        if (before >= 55296 && before <= 56319 && size > i2 + 1) {
          const next = input.charCodeAt(i2 + 1);
          if (next >= 56320 && next <= 57343) {
            codepoints.push((before - 55296) * 1024 + next - 56320 + 65536);
            i2 += 1;
            continue;
          }
        }
        codepoints.push(before);
      }
      return codepoints;
    }
    function saslprep({ unassigned_code_points, commonly_mapped_to_nothing, non_ASCII_space_characters, prohibited_characters, bidirectional_r_al, bidirectional_l }, input, opts = {}) {
      const mapping2space = non_ASCII_space_characters;
      const mapping2nothing = commonly_mapped_to_nothing;
      if (typeof input !== "string") {
        throw new TypeError("Expected string.");
      }
      if (input.length === 0) {
        return "";
      }
      const mapped_input = toCodePoints(input).map((character) => mapping2space.get(character) ? 32 : character).filter((character) => !mapping2nothing.get(character));
      const normalized_input = String.fromCodePoint.apply(null, mapped_input).normalize("NFKC");
      const normalized_map = toCodePoints(normalized_input);
      const hasProhibited = normalized_map.some((character) => prohibited_characters.get(character));
      if (hasProhibited) {
        throw new Error("Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3");
      }
      if (opts.allowUnassigned !== true) {
        const hasUnassigned = normalized_map.some((character) => unassigned_code_points.get(character));
        if (hasUnassigned) {
          throw new Error("Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5");
        }
      }
      const hasBidiRAL = normalized_map.some((character) => bidirectional_r_al.get(character));
      const hasBidiL = normalized_map.some((character) => bidirectional_l.get(character));
      if (hasBidiRAL && hasBidiL) {
        throw new Error("String must not contain RandALCat and LCat at the same time, see https://tools.ietf.org/html/rfc3454#section-6");
      }
      const isFirstBidiRAL = bidirectional_r_al.get(getCodePoint(first(normalized_input)));
      const isLastBidiRAL = bidirectional_r_al.get(getCodePoint(last(normalized_input)));
      if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) {
        throw new Error("Bidirectional RandALCat character must be the first and the last character of the string, see https://tools.ietf.org/html/rfc3454#section-6");
      }
      return normalized_input;
    }
    saslprep.saslprep = saslprep;
    saslprep.default = saslprep;
    module2.exports = saslprep;
  }
});

// node_modules/memory-pager/index.js
var require_memory_pager = __commonJS({
  "node_modules/memory-pager/index.js"(exports2, module2) {
    module2.exports = Pager;
    function Pager(pageSize, opts) {
      if (!(this instanceof Pager)) return new Pager(pageSize, opts);
      this.length = 0;
      this.updates = [];
      this.path = new Uint16Array(4);
      this.pages = new Array(32768);
      this.maxPages = this.pages.length;
      this.level = 0;
      this.pageSize = pageSize || 1024;
      this.deduplicate = opts ? opts.deduplicate : null;
      this.zeros = this.deduplicate ? alloc(this.deduplicate.length) : null;
    }
    Pager.prototype.updated = function(page) {
      while (this.deduplicate && page.buffer[page.deduplicate] === this.deduplicate[page.deduplicate]) {
        page.deduplicate++;
        if (page.deduplicate === this.deduplicate.length) {
          page.deduplicate = 0;
          if (page.buffer.equals && page.buffer.equals(this.deduplicate)) page.buffer = this.deduplicate;
          break;
        }
      }
      if (page.updated || !this.updates) return;
      page.updated = true;
      this.updates.push(page);
    };
    Pager.prototype.lastUpdate = function() {
      if (!this.updates || !this.updates.length) return null;
      var page = this.updates.pop();
      page.updated = false;
      return page;
    };
    Pager.prototype._array = function(i2, noAllocate) {
      if (i2 >= this.maxPages) {
        if (noAllocate) return;
        grow(this, i2);
      }
      factor(i2, this.path);
      var arr = this.pages;
      for (var j = this.level; j > 0; j--) {
        var p = this.path[j];
        var next = arr[p];
        if (!next) {
          if (noAllocate) return;
          next = arr[p] = new Array(32768);
        }
        arr = next;
      }
      return arr;
    };
    Pager.prototype.get = function(i2, noAllocate) {
      var arr = this._array(i2, noAllocate);
      var first = this.path[0];
      var page = arr && arr[first];
      if (!page && !noAllocate) {
        page = arr[first] = new Page(i2, alloc(this.pageSize));
        if (i2 >= this.length) this.length = i2 + 1;
      }
      if (page && page.buffer === this.deduplicate && this.deduplicate && !noAllocate) {
        page.buffer = copy(page.buffer);
        page.deduplicate = 0;
      }
      return page;
    };
    Pager.prototype.set = function(i2, buf) {
      var arr = this._array(i2, false);
      var first = this.path[0];
      if (i2 >= this.length) this.length = i2 + 1;
      if (!buf || this.zeros && buf.equals && buf.equals(this.zeros)) {
        arr[first] = void 0;
        return;
      }
      if (this.deduplicate && buf.equals && buf.equals(this.deduplicate)) {
        buf = this.deduplicate;
      }
      var page = arr[first];
      var b = truncate(buf, this.pageSize);
      if (page) page.buffer = b;
      else arr[first] = new Page(i2, b);
    };
    Pager.prototype.toBuffer = function() {
      var list = new Array(this.length);
      var empty = alloc(this.pageSize);
      var ptr = 0;
      while (ptr < list.length) {
        var arr = this._array(ptr, true);
        for (var i2 = 0; i2 < 32768 && ptr < list.length; i2++) {
          list[ptr++] = arr && arr[i2] ? arr[i2].buffer : empty;
        }
      }
      return Buffer.concat(list);
    };
    function grow(pager, index) {
      while (pager.maxPages < index) {
        var old = pager.pages;
        pager.pages = new Array(32768);
        pager.pages[0] = old;
        pager.level++;
        pager.maxPages *= 32768;
      }
    }
    function truncate(buf, len) {
      if (buf.length === len) return buf;
      if (buf.length > len) return buf.slice(0, len);
      var cpy = alloc(len);
      buf.copy(cpy);
      return cpy;
    }
    function alloc(size) {
      if (Buffer.alloc) return Buffer.alloc(size);
      var buf = new Buffer(size);
      buf.fill(0);
      return buf;
    }
    function copy(buf) {
      var cpy = Buffer.allocUnsafe ? Buffer.allocUnsafe(buf.length) : new Buffer(buf.length);
      buf.copy(cpy);
      return cpy;
    }
    function Page(i2, buf) {
      this.offset = i2 * buf.length;
      this.buffer = buf;
      this.updated = false;
      this.deduplicate = 0;
    }
    function factor(n, out) {
      n = (n - (out[0] = n & 32767)) / 32768;
      n = (n - (out[1] = n & 32767)) / 32768;
      out[3] = (n - (out[2] = n & 32767)) / 32768 & 32767;
    }
  }
});

// node_modules/sparse-bitfield/index.js
var require_sparse_bitfield = __commonJS({
  "node_modules/sparse-bitfield/index.js"(exports2, module2) {
    var pager = require_memory_pager();
    module2.exports = Bitfield;
    function Bitfield(opts) {
      if (!(this instanceof Bitfield)) return new Bitfield(opts);
      if (!opts) opts = {};
      if (Buffer.isBuffer(opts)) opts = { buffer: opts };
      this.pageOffset = opts.pageOffset || 0;
      this.pageSize = opts.pageSize || 1024;
      this.pages = opts.pages || pager(this.pageSize);
      this.byteLength = this.pages.length * this.pageSize;
      this.length = 8 * this.byteLength;
      if (!powerOfTwo(this.pageSize)) throw new Error("The page size should be a power of two");
      this._trackUpdates = !!opts.trackUpdates;
      this._pageMask = this.pageSize - 1;
      if (opts.buffer) {
        for (var i2 = 0; i2 < opts.buffer.length; i2 += this.pageSize) {
          this.pages.set(i2 / this.pageSize, opts.buffer.slice(i2, i2 + this.pageSize));
        }
        this.byteLength = opts.buffer.length;
        this.length = 8 * this.byteLength;
      }
    }
    Bitfield.prototype.get = function(i2) {
      var o = i2 & 7;
      var j = (i2 - o) / 8;
      return !!(this.getByte(j) & 128 >> o);
    };
    Bitfield.prototype.getByte = function(i2) {
      var o = i2 & this._pageMask;
      var j = (i2 - o) / this.pageSize;
      var page = this.pages.get(j, true);
      return page ? page.buffer[o + this.pageOffset] : 0;
    };
    Bitfield.prototype.set = function(i2, v) {
      var o = i2 & 7;
      var j = (i2 - o) / 8;
      var b = this.getByte(j);
      return this.setByte(j, v ? b | 128 >> o : b & (255 ^ 128 >> o));
    };
    Bitfield.prototype.toBuffer = function() {
      var all = alloc(this.pages.length * this.pageSize);
      for (var i2 = 0; i2 < this.pages.length; i2++) {
        var next = this.pages.get(i2, true);
        var allOffset = i2 * this.pageSize;
        if (next) next.buffer.copy(all, allOffset, this.pageOffset, this.pageOffset + this.pageSize);
      }
      return all;
    };
    Bitfield.prototype.setByte = function(i2, b) {
      var o = i2 & this._pageMask;
      var j = (i2 - o) / this.pageSize;
      var page = this.pages.get(j, false);
      o += this.pageOffset;
      if (page.buffer[o] === b) return false;
      page.buffer[o] = b;
      if (i2 >= this.byteLength) {
        this.byteLength = i2 + 1;
        this.length = this.byteLength * 8;
      }
      if (this._trackUpdates) this.pages.updated(page);
      return true;
    };
    function alloc(n) {
      if (Buffer.alloc) return Buffer.alloc(n);
      var b = new Buffer(n);
      b.fill(0);
      return b;
    }
    function powerOfTwo(x2) {
      return !(x2 & x2 - 1);
    }
  }
});

// node_modules/@mongodb-js/saslprep/dist/memory-code-points.js
var require_memory_code_points = __commonJS({
  "node_modules/@mongodb-js/saslprep/dist/memory-code-points.js"(exports2) {
    "use strict";
    var __importDefault = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createMemoryCodePoints = createMemoryCodePoints;
    var sparse_bitfield_1 = __importDefault(require_sparse_bitfield());
    function createMemoryCodePoints(data) {
      let offset = 0;
      function read() {
        const size = data.readUInt32BE(offset);
        offset += 4;
        const codepoints = data.slice(offset, offset + size);
        offset += size;
        return (0, sparse_bitfield_1.default)({ buffer: codepoints });
      }
      const unassigned_code_points = read();
      const commonly_mapped_to_nothing = read();
      const non_ASCII_space_characters = read();
      const prohibited_characters = read();
      const bidirectional_r_al = read();
      const bidirectional_l = read();
      return {
        unassigned_code_points,
        commonly_mapped_to_nothing,
        non_ASCII_space_characters,
        prohibited_characters,
        bidirectional_r_al,
        bidirectional_l
      };
    }
  }
});

// node_modules/@mongodb-js/saslprep/dist/code-points-data.js
var require_code_points_data = __commonJS({
  "node_modules/@mongodb-js/saslprep/dist/code-points-data.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var zlib_1 = require("zlib");
    exports2.default = (0, zlib_1.gunzipSync)(Buffer.from("H4sIAAAAAAACA+3dTYgcaRkA4LemO9Mhxm0FITnE9Cwr4jHgwgZ22B6YywqCJ0HQg5CL4sGTuOjCtGSF4CkHEW856MlTQHD3EJnWkU0Owh5VxE3LHlYQdNxd2U6mU59UV/d09fw4M2EySSXPAzNdP1/9fX/99bzVNZEN4jisRDulVFnQmLxm1aXF9Id/2/xMxNJ4XZlg576yuYlGt9gupV6xoFf8jhu9YvulVrFlp5XSx+lfvYhORGPXvqIRWSxERKtIm8bKFd10WNfKDS5Fo9jJWrq2+M2IlW+8uHgl/+BsROfPF4v5L7148Ur68Sha6dqZpYiVVy8tvLCWXo80Sf/lS89dGX2wHGvpzoXVn75/YWH5wmqe8uika82ViJXTy83Ve2k5Urozm38wm4/ls6t5uT6yfsTSJ7J3T0VKt8c5ExEXI8aFkH729c3eT+7EC6ca8cVULZUiYacX0R5PNWNxlh9L1y90q5kyzrpyy+9WcvOV6URntqw7La9sNVstXyczWVaWYbaaTYqzOHpr7pyiNT3/YzKuT63Z/FqKZlFTiuXtFM2vVOtIq7jiyKJbWZaOWD0euz0yoV2Z7kY0xq2x0YhfzVpmM5px9nTEH7JZ0ot5u39p0ma75Z472/s/H+2yr2inYyuq7fMvJivH2rM72N/Z3lyL31F2b1ya1P0zn816k2KP6JU9UzseucdQH5YqVeH/lFajSN2udg+TLJ9rksNxlvV2lki19rXKI43TPLejFu4ov7k3nMbhyhfY3Xb37f8BAGCf0eMTOH5szf154KmnNgKcnLb+Fzi2AfXktbN7fJelwTAiO/W5uQ2KINXRYu+znqo/WTAdLadURHmy3qciazd3bra4T3w16/f7t7Ms9U5gfJu10955sx1r3vmhBAAAAAAAgId20J1iZbDowNvIjuH427Gr5l/eiC+8OplZON8sVjx/qr9y+Pj+YRItT+NqAM+kkZs3AAAAAID6yfx1FwCAI97/dCh1/ub6SA0AAAAAAAAAgNoT/wcAAAAAAACA+hP/BwAAAAAAAID6E/8HAAAAAAAAgPoT/wcAAAAAAACA+hP/BwAAAAAAAID6E/8HAAAAAAAAgPoT/wcAAAAAAACA+hP/BwAAAAAAAID6E/8HAAAAAAAAgPoT/wcAAAAAAACA+hutp5SiQpYAAAAAAAAAQO2MIpZiT804flnAE2fhwjOeAZXr76kOAAAAAAAA8FjNf4N/l0NE3U/vuVQskLpSd4/Yh2xu9xTu0tFeeNYsLI2f/VMdNxTzj6Je9E/+6pp6Nn3awW3A54goe4Bss6v+PGsjQGMAAAAAAOBp5XEgwH6e7J7rwEQHRb/XvAMAAAAAAAA8yzoDeQDwVGjIAgAAAAAAAACoPfF/AAAAAAAAAKg/8X8AAAAAAAAAqD/xfwAAAAAAAACoP/F/AAAAAAAAAKg/8X8AAAAAAAAAqD/xfwAAAAAAAACoP/F/AAAAAAAAAKg/8X8AAAAAAAAAqD/xfwAAAAAAAACoP/F/AAAAAAAAAKg/8X8AAAAAAAAAqL/GSkSkClkCAAAAAAAAALXTSAAAAAAAAABA3Y1kAQAAAAAAAADUX8RSXZ9dsHC9+M8Fg2Ex/em1lAZpEBGttcrVjZqLEa+k0XpKw9mG4zWx4ukPUMhkAQAAAAAAABzBqbSe3//rXOS9HxGdo4TqR2XkutCdBu+LaPZw/lBbO7cbHnh2C7N7AIo4evEznllqLqWUp/LnYOtpM2bnOH66wI1+9GO4sOuISwv/TOlumu56FDv3NZhc4mR9v7zYIrafr40j/Cccvj9Xns3t3mu99E7qxUv3bqS0/ouNH/08++RGemfQ+nsx/5uNXsQPGulynPvv3ZTW37zd+1ovrqaYpP/122X6Xpx779Z3zr/3YOPKW1lkaRDf31pPaf3j/msRsVGkL+d/f+/m4sJsPm1cfSsr16e8m9Ldj/KsnyIuR3nXw83Is3EhxLd/2V773ks3m/cj/THKUummdP9qKhIOImuOU0Xjwb3y+oqt735rpTetVbF9n8R4x9crRfO77TKqVOZpDclv5bfK18lMnk+q0K18UpxF/RrGXE0Zxtqx3tWSj+vxbL4XaasfKb0dRbtLW73JsfPGg177H+OmGKlfvS1msllt7JEJm9XOJqXR+Fkfo1H66uy5H1v3Xx5+uJmGLw9jro2u7Loj4PnuR6+f+e3d261+eazNhzrL7X83MohoHpS4PddV8ki1it61//pw1g7z6p1U/26Nm2llST57B5rUvuG0XqSU/rPd7jYrqWcbd+beJQ77BgPMDwn37/8BAGCf0eMTOH4cPlufv9VGgJOzqf8Fjm1APXkd7B7f5dF57GPMaWy/MTvjvNvtXj6h8W2+GXvnzXaseeeHEgAAAAAAAB7aQXeKlcGiadBoEOeLb2dtpGOL2MyOtf391a3P/zD96c3JzIP3t4oV797vrh8+vn+YRL5bBuj/AQAAAABqJvfHXQAAHkX82zfXAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACeAgkAAAAAAAAAqLuRLAAAAAAAAACA2hv9D1iu/VAYaAYA", "base64"));
  }
});

// node_modules/@mongodb-js/saslprep/dist/node.js
var require_node2 = __commonJS({
  "node_modules/@mongodb-js/saslprep/dist/node.js"(exports2, module2) {
    "use strict";
    var __importDefault = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    var index_1 = __importDefault(require_dist3());
    var memory_code_points_1 = require_memory_code_points();
    var code_points_data_1 = __importDefault(require_code_points_data());
    var codePoints = (0, memory_code_points_1.createMemoryCodePoints)(code_points_data_1.default);
    function saslprep(input, opts) {
      return (0, index_1.default)(codePoints, input, opts);
    }
    saslprep.saslprep = saslprep;
    saslprep.default = saslprep;
    module2.exports = saslprep;
  }
});

// node_modules/mongodb/lib/cmap/auth/scram.js
var require_scram = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/scram.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ScramSHA256 = exports2.ScramSHA1 = void 0;
    var saslprep_1 = require_node2();
    var bson_1 = require_bson2();
    var error_1 = require_error();
    var utils_1 = require_utils();
    var auth_provider_1 = require_auth_provider();
    var providers_1 = require_providers();
    var ScramSHA = class extends auth_provider_1.AuthProvider {
      constructor(cryptoMethod) {
        super();
        this.cryptoMethod = cryptoMethod || "sha1";
      }
      async prepare(handshakeDoc, authContext) {
        const cryptoMethod = this.cryptoMethod;
        const credentials = authContext.credentials;
        if (!credentials) {
          throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials.");
        }
        const nonce = await (0, utils_1.randomBytes)(24);
        authContext.nonce = nonce;
        const request = {
          ...handshakeDoc,
          speculativeAuthenticate: {
            ...makeFirstMessage(cryptoMethod, credentials, nonce),
            db: credentials.source
          }
        };
        return request;
      }
      async auth(authContext) {
        const { reauthenticating, response } = authContext;
        if (response?.speculativeAuthenticate && !reauthenticating) {
          return await continueScramConversation(this.cryptoMethod, response.speculativeAuthenticate, authContext);
        }
        return await executeScram(this.cryptoMethod, authContext);
      }
    };
    function cleanUsername(username) {
      return username.replace("=", "=3D").replace(",", "=2C");
    }
    function clientFirstMessageBare(username, nonce) {
      return bson_1.ByteUtils.concat([
        bson_1.ByteUtils.fromUTF8("n="),
        bson_1.ByteUtils.fromUTF8(username),
        bson_1.ByteUtils.fromUTF8(",r="),
        bson_1.ByteUtils.fromUTF8(bson_1.ByteUtils.toBase64(nonce))
      ]);
    }
    function makeFirstMessage(cryptoMethod, credentials, nonce) {
      const username = cleanUsername(credentials.username);
      const mechanism = cryptoMethod === "sha1" ? providers_1.AuthMechanism.MONGODB_SCRAM_SHA1 : providers_1.AuthMechanism.MONGODB_SCRAM_SHA256;
      return {
        saslStart: 1,
        mechanism,
        payload: new bson_1.Binary(bson_1.ByteUtils.concat([bson_1.ByteUtils.fromUTF8("n,,"), clientFirstMessageBare(username, nonce)])),
        autoAuthorize: 1,
        options: { skipEmptyExchange: true }
      };
    }
    async function executeScram(cryptoMethod, authContext) {
      const { connection, credentials } = authContext;
      if (!credentials) {
        throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials.");
      }
      if (!authContext.nonce) {
        throw new error_1.MongoInvalidArgumentError("AuthContext must contain a valid nonce property");
      }
      const nonce = authContext.nonce;
      const db = credentials.source;
      const saslStartCmd = makeFirstMessage(cryptoMethod, credentials, nonce);
      const response = await connection.command((0, utils_1.ns)(`${db}.$cmd`), saslStartCmd, void 0);
      await continueScramConversation(cryptoMethod, response, authContext);
    }
    async function continueScramConversation(cryptoMethod, response, authContext) {
      const connection = authContext.connection;
      const credentials = authContext.credentials;
      if (!credentials) {
        throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials.");
      }
      if (!authContext.nonce) {
        throw new error_1.MongoInvalidArgumentError("Unable to continue SCRAM without valid nonce");
      }
      const nonce = authContext.nonce;
      const db = credentials.source;
      const username = cleanUsername(credentials.username);
      const password = credentials.password;
      const processedPassword = cryptoMethod === "sha256" ? (0, saslprep_1.saslprep)(password) : passwordDigest(username, password);
      const payload = bson_1.ByteUtils.isUint8Array(response.payload) ? new bson_1.Binary(response.payload) : response.payload;
      const dict = parsePayload(payload);
      const iterations = parseInt(dict.i, 10);
      if (iterations && iterations < 4096) {
        throw new error_1.MongoRuntimeError(`Server returned an invalid iteration count ${iterations}`);
      }
      const salt = dict.s;
      const rnonce = dict.r;
      if (rnonce.startsWith("nonce")) {
        throw new error_1.MongoRuntimeError(`Server returned an invalid nonce: ${rnonce}`);
      }
      const withoutProof = `c=biws,r=${rnonce}`;
      const saltedPassword = await HI(processedPassword, bson_1.ByteUtils.fromBase64(salt), iterations, cryptoMethod);
      const clientKey = await HMAC(cryptoMethod, saltedPassword, "Client Key");
      const serverKey = await HMAC(cryptoMethod, saltedPassword, "Server Key");
      const storedKey = await H(cryptoMethod, clientKey);
      const firstMessageBytes = clientFirstMessageBare(username, nonce);
      const firstMessage = bson_1.ByteUtils.toUTF8(firstMessageBytes, 0, firstMessageBytes.length, false);
      const payloadString = bson_1.ByteUtils.toUTF8(payload.buffer, 0, payload.position, false);
      const authMessage = [firstMessage, payloadString, withoutProof].join(",");
      const clientSignature = await HMAC(cryptoMethod, storedKey, authMessage);
      const clientProof = `p=${xor2(clientKey, clientSignature)}`;
      const clientFinal = [withoutProof, clientProof].join(",");
      const serverSignature = await HMAC(cryptoMethod, serverKey, authMessage);
      const saslContinueCmd = {
        saslContinue: 1,
        conversationId: response.conversationId,
        payload: new bson_1.Binary(bson_1.ByteUtils.fromUTF8(clientFinal))
      };
      const r2 = await connection.command((0, utils_1.ns)(`${db}.$cmd`), saslContinueCmd, void 0);
      const parsedResponse = parsePayload(r2.payload);
      if (!compareDigest(bson_1.ByteUtils.fromBase64(parsedResponse.v), serverSignature)) {
        throw new error_1.MongoRuntimeError("Server returned an invalid signature");
      }
      if (r2.done !== false) {
        return;
      }
      const retrySaslContinueCmd = {
        saslContinue: 1,
        conversationId: r2.conversationId,
        payload: bson_1.ByteUtils.allocate(0)
      };
      await connection.command((0, utils_1.ns)(`${db}.$cmd`), retrySaslContinueCmd, void 0);
    }
    function parsePayload(payload) {
      const payloadStr = bson_1.ByteUtils.toUTF8(payload.buffer, 0, payload.position, false);
      const dict = {};
      const parts = payloadStr.split(",");
      for (let i2 = 0; i2 < parts.length; i2++) {
        const valueParts = (parts[i2].match(/^([^=]*)=(.*)$/) ?? []).slice(1);
        dict[valueParts[0]] = valueParts[1];
      }
      return dict;
    }
    function passwordDigest(username, password) {
      if (typeof username !== "string") {
        throw new error_1.MongoInvalidArgumentError("Username must be a string");
      }
      if (typeof password !== "string") {
        throw new error_1.MongoInvalidArgumentError("Password must be a string");
      }
      if (password.length === 0) {
        throw new error_1.MongoInvalidArgumentError("Password cannot be empty");
      }
      let nodeCrypto;
      try {
        nodeCrypto = require("crypto");
      } catch (e2) {
        throw new error_1.MongoRuntimeError("Node.js crypto module is required for SCRAM-SHA-1 authentication", {
          cause: e2
        });
      }
      try {
        const md5 = nodeCrypto.createHash("md5");
        md5.update(`${username}:mongo:${password}`, "utf8");
        return md5.digest("hex");
      } catch (err) {
        if (nodeCrypto.getFips()) {
          throw new Error("Auth mechanism SCRAM-SHA-1 is not supported in FIPS mode");
        }
        throw err;
      }
    }
    function xor2(a, b) {
      const length = Math.max(a.length, b.length);
      const res = [];
      for (let i2 = 0; i2 < length; i2 += 1) {
        res.push(a[i2] ^ b[i2]);
      }
      return bson_1.ByteUtils.toBase64(bson_1.ByteUtils.fromNumberArray(res));
    }
    async function H(method, text) {
      const buffer = await crypto.subtle.digest(method === "sha256" ? "SHA-256" : "SHA-1", text);
      return new Uint8Array(buffer);
    }
    async function HMAC(method, key, text) {
      const keyBuffer = bson_1.ByteUtils.toLocalBufferType(key);
      const cryptoKey = await crypto.subtle.importKey("raw", keyBuffer, { name: "HMAC", hash: { name: method === "sha256" ? "SHA-256" : "SHA-1" } }, false, ["sign", "verify"]);
      const textData = typeof text === "string" ? new TextEncoder().encode(text) : text;
      const textBuffer = bson_1.ByteUtils.toLocalBufferType(textData);
      const signature = await crypto.subtle.sign("HMAC", cryptoKey, textBuffer);
      return new Uint8Array(signature);
    }
    var _hiCache = {};
    var _hiCacheCount = 0;
    function _hiCachePurge() {
      _hiCache = {};
      _hiCacheCount = 0;
    }
    var hiLengthMap = {
      sha256: 32,
      sha1: 20
    };
    async function HI(data, salt, iterations, cryptoMethod) {
      const key = [data, bson_1.ByteUtils.toBase64(salt), iterations].join("_");
      if (_hiCache[key] != null) {
        return _hiCache[key];
      }
      const keyMaterial = await crypto.subtle.importKey("raw", new TextEncoder().encode(data), { name: "PBKDF2" }, false, ["deriveBits"]);
      const params = {
        name: "PBKDF2",
        salt,
        iterations,
        hash: { name: cryptoMethod === "sha256" ? "SHA-256" : "SHA-1" }
      };
      const derivedBits = await crypto.subtle.deriveBits(params, keyMaterial, hiLengthMap[cryptoMethod] * 8);
      const saltedData = new Uint8Array(derivedBits);
      if (_hiCacheCount >= 200) {
        _hiCachePurge();
      }
      _hiCache[key] = saltedData;
      _hiCacheCount += 1;
      return saltedData;
    }
    function compareDigest(lhs, rhs) {
      if (lhs.length !== rhs.length) {
        return false;
      }
      let result = 0;
      for (let i2 = 0; i2 < lhs.length; i2++) {
        result |= lhs[i2] ^ rhs[i2];
      }
      return result === 0;
    }
    var ScramSHA1 = class extends ScramSHA {
      constructor() {
        super("sha1");
      }
    };
    exports2.ScramSHA1 = ScramSHA1;
    var ScramSHA256 = class extends ScramSHA {
      constructor() {
        super("sha256");
      }
    };
    exports2.ScramSHA256 = ScramSHA256;
  }
});

// node_modules/mongodb/lib/cmap/auth/x509.js
var require_x509 = __commonJS({
  "node_modules/mongodb/lib/cmap/auth/x509.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.X509 = void 0;
    var error_1 = require_error();
    var utils_1 = require_utils();
    var auth_provider_1 = require_auth_provider();
    var X509 = class extends auth_provider_1.AuthProvider {
      async prepare(handshakeDoc, authContext) {
        const { credentials } = authContext;
        if (!credentials) {
          throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials.");
        }
        return { ...handshakeDoc, speculativeAuthenticate: x509AuthenticateCommand(credentials) };
      }
      async auth(authContext) {
        const connection = authContext.connection;
        const credentials = authContext.credentials;
        if (!credentials) {
          throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials.");
        }
        const response = authContext.response;
        if (response?.speculativeAuthenticate) {
          return;
        }
        await connection.command((0, utils_1.ns)("$external.$cmd"), x509AuthenticateCommand(credentials), void 0);
      }
    };
    exports2.X509 = X509;
    function x509AuthenticateCommand(credentials) {
      const command = { authenticate: 1, mechanism: "MONGODB-X509" };
      if (credentials.username) {
        command.user = credentials.username;
      }
      return command;
    }
  }
});

// node_modules/mongodb/lib/mongo_client_auth_providers.js
var require_mongo_client_auth_providers = __commonJS({
  "node_modules/mongodb/lib/mongo_client_auth_providers.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MongoClientAuthProviders = void 0;
    var gssapi_1 = require_gssapi();
    var mongodb_aws_1 = require_mongodb_aws();
    var mongodb_oidc_1 = require_mongodb_oidc();
    var automated_callback_workflow_1 = require_automated_callback_workflow();
    var human_callback_workflow_1 = require_human_callback_workflow();
    var token_cache_1 = require_token_cache();
    var plain_1 = require_plain();
    var providers_1 = require_providers();
    var scram_1 = require_scram();
    var x509_1 = require_x509();
    var error_1 = require_error();
    var AUTH_PROVIDERS = /* @__PURE__ */ new Map([
      [
        providers_1.AuthMechanism.MONGODB_AWS,
        ({ AWS_CREDENTIAL_PROVIDER }) => new mongodb_aws_1.MongoDBAWS(AWS_CREDENTIAL_PROVIDER)
      ],
      [providers_1.AuthMechanism.MONGODB_GSSAPI, () => new gssapi_1.GSSAPI()],
      [providers_1.AuthMechanism.MONGODB_OIDC, (properties) => new mongodb_oidc_1.MongoDBOIDC(getWorkflow(properties))],
      [providers_1.AuthMechanism.MONGODB_PLAIN, () => new plain_1.Plain()],
      [providers_1.AuthMechanism.MONGODB_SCRAM_SHA1, () => new scram_1.ScramSHA1()],
      [providers_1.AuthMechanism.MONGODB_SCRAM_SHA256, () => new scram_1.ScramSHA256()],
      [providers_1.AuthMechanism.MONGODB_X509, () => new x509_1.X509()]
    ]);
    var MongoClientAuthProviders = class {
      constructor() {
        this.existingProviders = /* @__PURE__ */ new Map();
      }
      /**
       * Get or create an authentication provider based on the provided mechanism.
       * We don't want to create all providers at once, as some providers may not be used.
       * @param name - The name of the provider to get or create.
       * @param credentials - The credentials.
       * @returns The provider.
       * @throws MongoInvalidArgumentError if the mechanism is not supported.
       * @internal
       */
      getOrCreateProvider(name, authMechanismProperties) {
        const authProvider = this.existingProviders.get(name);
        if (authProvider) {
          return authProvider;
        }
        const providerFunction = AUTH_PROVIDERS.get(name);
        if (!providerFunction) {
          throw new error_1.MongoInvalidArgumentError(`authMechanism ${name} not supported`);
        }
        const provider = providerFunction(authMechanismProperties);
        this.existingProviders.set(name, provider);
        return provider;
      }
    };
    exports2.MongoClientAuthProviders = MongoClientAuthProviders;
    function getWorkflow(authMechanismProperties) {
      if (authMechanismProperties.OIDC_HUMAN_CALLBACK) {
        return new human_callback_workflow_1.HumanCallbackWorkflow(new token_cache_1.TokenCache(), authMechanismProperties.OIDC_HUMAN_CALLBACK);
      } else if (authMechanismProperties.OIDC_CALLBACK) {
        return new automated_callback_workflow_1.AutomatedCallbackWorkflow(new token_cache_1.TokenCache(), authMechanismProperties.OIDC_CALLBACK);
      } else {
        const environment = authMechanismProperties.ENVIRONMENT;
        const workflow = mongodb_oidc_1.OIDC_WORKFLOWS.get(environment)?.();
        if (!workflow) {
          throw new error_1.MongoInvalidArgumentError(`Could not load workflow for environment ${authMechanismProperties.ENVIRONMENT}`);
        }
        return workflow;
      }
    }
  }
});

// node_modules/mongodb/lib/operations/client_bulk_write/client_bulk_write.js
var require_client_bulk_write = __commonJS({
  "node_modules/mongodb/lib/operations/client_bulk_write/client_bulk_write.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ClientBulkWriteOperation = void 0;
    var responses_1 = require_responses();
    var utils_1 = require_utils();
    var command_1 = require_command();
    var operation_1 = require_operation();
    var ClientBulkWriteOperation = class extends command_1.CommandOperation {
      get commandName() {
        return "bulkWrite";
      }
      constructor(commandBuilder, options) {
        super(void 0, options);
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.ClientBulkWriteCursorResponse;
        this.commandBuilder = commandBuilder;
        this.options = options;
        this.ns = new utils_1.MongoDBNamespace("admin", "$cmd");
      }
      resetBatch() {
        return this.commandBuilder.resetBatch();
      }
      get canRetryWrite() {
        return this.commandBuilder.isBatchRetryable;
      }
      handleOk(response) {
        return response;
      }
      buildCommandDocument(connection, _session) {
        const command = this.commandBuilder.buildBatch(connection.description.maxMessageSizeBytes, connection.description.maxWriteBatchSize, connection.description.maxBsonObjectSize);
        if (!this.canRetryWrite) {
          this.options.willRetryWrite = false;
        }
        return command;
      }
    };
    exports2.ClientBulkWriteOperation = ClientBulkWriteOperation;
    (0, operation_1.defineAspects)(ClientBulkWriteOperation, [
      operation_1.Aspect.WRITE_OPERATION,
      operation_1.Aspect.SKIP_COLLATION,
      operation_1.Aspect.CURSOR_CREATING,
      operation_1.Aspect.RETRYABLE,
      operation_1.Aspect.COMMAND_BATCHING,
      operation_1.Aspect.SUPPORTS_RAW_DATA
    ]);
  }
});

// node_modules/mongodb/lib/cursor/client_bulk_write_cursor.js
var require_client_bulk_write_cursor = __commonJS({
  "node_modules/mongodb/lib/cursor/client_bulk_write_cursor.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ClientBulkWriteCursor = void 0;
    var client_bulk_write_1 = require_client_bulk_write();
    var execute_operation_1 = require_execute_operation();
    var utils_1 = require_utils();
    var abstract_cursor_1 = require_abstract_cursor();
    var ClientBulkWriteCursor = class _ClientBulkWriteCursor extends abstract_cursor_1.AbstractCursor {
      /** @internal */
      constructor(client, commandBuilder, options = {}) {
        super(client, new utils_1.MongoDBNamespace("admin", "$cmd"), options);
        this.commandBuilder = commandBuilder;
        this.clientBulkWriteOptions = options;
      }
      /**
       * We need a way to get the top level cursor response fields for
       * generating the bulk write result, so we expose this here.
       */
      get response() {
        if (this.cursorResponse)
          return this.cursorResponse;
        return null;
      }
      get operations() {
        return this.commandBuilder.lastOperations;
      }
      clone() {
        const clonedOptions = (0, utils_1.mergeOptions)({}, this.clientBulkWriteOptions);
        delete clonedOptions.session;
        return new _ClientBulkWriteCursor(this.client, this.commandBuilder, {
          ...clonedOptions
        });
      }
      /** @internal */
      async _initialize(session) {
        const clientBulkWriteOperation = new client_bulk_write_1.ClientBulkWriteOperation(this.commandBuilder, {
          ...this.clientBulkWriteOptions,
          ...this.cursorOptions,
          session
        });
        const response = await (0, execute_operation_1.executeOperation)(this.client, clientBulkWriteOperation, this.timeoutContext);
        this.cursorResponse = response;
        return { server: clientBulkWriteOperation.server, session, response };
      }
    };
    exports2.ClientBulkWriteCursor = ClientBulkWriteCursor;
  }
});

// node_modules/mongodb/lib/operations/client_bulk_write/command_builder.js
var require_command_builder = __commonJS({
  "node_modules/mongodb/lib/operations/client_bulk_write/command_builder.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.buildReplaceOneOperation = exports2.buildUpdateManyOperation = exports2.buildUpdateOneOperation = exports2.buildDeleteManyOperation = exports2.buildDeleteOneOperation = exports2.buildInsertOneOperation = exports2.ClientBulkWriteCommandBuilder = void 0;
    exports2.buildOperation = buildOperation;
    var bson_1 = require_bson2();
    var commands_1 = require_commands();
    var error_1 = require_error();
    var sort_1 = require_sort();
    var utils_1 = require_utils();
    var MESSAGE_OVERHEAD_BYTES = 1e3;
    var ClientBulkWriteCommandBuilder = class {
      /**
       * Create the command builder.
       * @param models - The client write models.
       */
      constructor(models, options, pkFactory) {
        this.models = models;
        this.options = options;
        this.pkFactory = pkFactory ?? utils_1.DEFAULT_PK_FACTORY;
        this.currentModelIndex = 0;
        this.previousModelIndex = 0;
        this.lastOperations = [];
        this.isBatchRetryable = true;
      }
      /**
       * Gets the errorsOnly value for the command, which is the inverse of the
       * user provided verboseResults option. Defaults to true.
       */
      get errorsOnly() {
        if ("verboseResults" in this.options) {
          return !this.options.verboseResults;
        }
        return true;
      }
      /**
       * Determines if there is another batch to process.
       * @returns True if not all batches have been built.
       */
      hasNextBatch() {
        return this.currentModelIndex < this.models.length;
      }
      /**
       * When we need to retry a command we need to set the current
       * model index back to its previous value.
       */
      resetBatch() {
        this.currentModelIndex = this.previousModelIndex;
        return true;
      }
      /**
       * Build a single batch of a client bulk write command.
       * @param maxMessageSizeBytes - The max message size in bytes.
       * @param maxWriteBatchSize - The max write batch size.
       * @returns The client bulk write command.
       */
      buildBatch(maxMessageSizeBytes, maxWriteBatchSize, maxBsonObjectSize) {
        this.isBatchRetryable = true;
        let commandLength = 0;
        let currentNamespaceIndex = 0;
        const command = this.baseCommand();
        const namespaces = /* @__PURE__ */ new Map();
        this.previousModelIndex = this.currentModelIndex;
        while (this.currentModelIndex < this.models.length) {
          const model = this.models[this.currentModelIndex];
          const ns = model.namespace;
          const nsIndex = namespaces.get(ns);
          if (model.name === "deleteMany" || model.name === "updateMany") {
            this.isBatchRetryable = false;
          }
          if (nsIndex != null) {
            const operation = buildOperation(model, nsIndex, this.pkFactory, this.options);
            let operationBuffer;
            try {
              operationBuffer = bson_1.BSON.serialize(operation);
            } catch (cause) {
              throw new error_1.MongoInvalidArgumentError(`Could not serialize operation to BSON`, { cause });
            }
            validateBufferSize("ops", operationBuffer, maxBsonObjectSize);
            if (commandLength + operationBuffer.length < maxMessageSizeBytes && command.ops.documents.length < maxWriteBatchSize) {
              commandLength = MESSAGE_OVERHEAD_BYTES + command.ops.push(operation, operationBuffer);
              this.currentModelIndex++;
            } else {
              break;
            }
          } else {
            namespaces.set(ns, currentNamespaceIndex);
            const nsInfo = { ns };
            const operation = buildOperation(model, currentNamespaceIndex, this.pkFactory, this.options);
            let nsInfoBuffer;
            let operationBuffer;
            try {
              nsInfoBuffer = bson_1.BSON.serialize(nsInfo);
              operationBuffer = bson_1.BSON.serialize(operation);
            } catch (cause) {
              throw new error_1.MongoInvalidArgumentError(`Could not serialize ns info to BSON`, { cause });
            }
            validateBufferSize("nsInfo", nsInfoBuffer, maxBsonObjectSize);
            validateBufferSize("ops", operationBuffer, maxBsonObjectSize);
            if (commandLength + nsInfoBuffer.length + operationBuffer.length < maxMessageSizeBytes && command.ops.documents.length < maxWriteBatchSize) {
              commandLength = MESSAGE_OVERHEAD_BYTES + command.nsInfo.push(nsInfo, nsInfoBuffer) + command.ops.push(operation, operationBuffer);
              currentNamespaceIndex++;
              this.currentModelIndex++;
            } else {
              break;
            }
          }
        }
        this.lastOperations = command.ops.documents;
        return command;
      }
      baseCommand() {
        const command = {
          bulkWrite: 1,
          errorsOnly: this.errorsOnly,
          ordered: this.options.ordered ?? true,
          ops: new commands_1.DocumentSequence("ops"),
          nsInfo: new commands_1.DocumentSequence("nsInfo")
        };
        if (this.options.bypassDocumentValidation != null) {
          command.bypassDocumentValidation = this.options.bypassDocumentValidation;
        }
        if (this.options.let) {
          command.let = this.options.let;
        }
        if (this.options.comment !== void 0) {
          command.comment = this.options.comment;
        }
        return command;
      }
    };
    exports2.ClientBulkWriteCommandBuilder = ClientBulkWriteCommandBuilder;
    function validateBufferSize(name, buffer, maxBsonObjectSize) {
      if (buffer.length > maxBsonObjectSize) {
        throw new error_1.MongoInvalidArgumentError(`Client bulk write operation ${name} of length ${buffer.length} exceeds the max bson object size of ${maxBsonObjectSize}`);
      }
    }
    var buildInsertOneOperation = (model, index, pkFactory) => {
      const document2 = {
        insert: index,
        document: model.document
      };
      document2.document._id = model.document._id ?? pkFactory.createPk();
      return document2;
    };
    exports2.buildInsertOneOperation = buildInsertOneOperation;
    var buildDeleteOneOperation = (model, index) => {
      return createDeleteOperation(model, index, false);
    };
    exports2.buildDeleteOneOperation = buildDeleteOneOperation;
    var buildDeleteManyOperation = (model, index) => {
      return createDeleteOperation(model, index, true);
    };
    exports2.buildDeleteManyOperation = buildDeleteManyOperation;
    function createDeleteOperation(model, index, multi) {
      const document2 = {
        delete: index,
        multi,
        filter: model.filter
      };
      if (model.hint) {
        document2.hint = model.hint;
      }
      if (model.collation) {
        document2.collation = model.collation;
      }
      return document2;
    }
    var buildUpdateOneOperation = (model, index, options) => {
      return createUpdateOperation(model, index, false, options);
    };
    exports2.buildUpdateOneOperation = buildUpdateOneOperation;
    var buildUpdateManyOperation = (model, index, options) => {
      return createUpdateOperation(model, index, true, options);
    };
    exports2.buildUpdateManyOperation = buildUpdateManyOperation;
    function validateUpdate(update, options) {
      if (!(0, utils_1.hasAtomicOperators)(update, options)) {
        throw new error_1.MongoAPIError("Client bulk write update models must only contain atomic modifiers (start with $) and must not be empty.");
      }
    }
    function createUpdateOperation(model, index, multi, options) {
      validateUpdate(model.update, options);
      const document2 = {
        update: index,
        multi,
        filter: model.filter,
        updateMods: model.update
      };
      if (model.hint) {
        document2.hint = model.hint;
      }
      if (model.upsert) {
        document2.upsert = model.upsert;
      }
      if (model.arrayFilters) {
        document2.arrayFilters = model.arrayFilters;
      }
      if (model.collation) {
        document2.collation = model.collation;
      }
      if (!multi && "sort" in model && model.sort != null) {
        document2.sort = (0, sort_1.formatSort)(model.sort);
      }
      return document2;
    }
    var buildReplaceOneOperation = (model, index) => {
      if ((0, utils_1.hasAtomicOperators)(model.replacement)) {
        throw new error_1.MongoAPIError("Client bulk write replace models must not contain atomic modifiers (start with $) and must not be empty.");
      }
      const document2 = {
        update: index,
        multi: false,
        filter: model.filter,
        updateMods: model.replacement
      };
      if (model.hint) {
        document2.hint = model.hint;
      }
      if (model.upsert) {
        document2.upsert = model.upsert;
      }
      if (model.collation) {
        document2.collation = model.collation;
      }
      if (model.sort != null) {
        document2.sort = (0, sort_1.formatSort)(model.sort);
      }
      return document2;
    };
    exports2.buildReplaceOneOperation = buildReplaceOneOperation;
    function buildOperation(model, index, pkFactory, options) {
      switch (model.name) {
        case "insertOne":
          return (0, exports2.buildInsertOneOperation)(model, index, pkFactory);
        case "deleteOne":
          return (0, exports2.buildDeleteOneOperation)(model, index);
        case "deleteMany":
          return (0, exports2.buildDeleteManyOperation)(model, index);
        case "updateOne":
          return (0, exports2.buildUpdateOneOperation)(model, index, options);
        case "updateMany":
          return (0, exports2.buildUpdateManyOperation)(model, index, options);
        case "replaceOne":
          return (0, exports2.buildReplaceOneOperation)(model, index);
      }
    }
  }
});

// node_modules/mongodb/lib/operations/client_bulk_write/results_merger.js
var require_results_merger = __commonJS({
  "node_modules/mongodb/lib/operations/client_bulk_write/results_merger.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ClientBulkWriteResultsMerger = void 0;
    var __1 = require_lib3();
    var error_1 = require_error();
    var UNACKNOWLEDGED = {
      acknowledged: false,
      insertedCount: 0,
      upsertedCount: 0,
      matchedCount: 0,
      modifiedCount: 0,
      deletedCount: 0,
      insertResults: void 0,
      updateResults: void 0,
      deleteResults: void 0
    };
    var ClientBulkWriteResultsMerger = class {
      /**
       * @returns The standard unacknowledged bulk write result.
       */
      static unacknowledged() {
        return UNACKNOWLEDGED;
      }
      /**
       * Instantiate the merger.
       * @param options - The options.
       */
      constructor(options) {
        this.options = options;
        this.currentBatchOffset = 0;
        this.writeConcernErrors = [];
        this.writeErrors = /* @__PURE__ */ new Map();
        this.result = {
          acknowledged: true,
          insertedCount: 0,
          upsertedCount: 0,
          matchedCount: 0,
          modifiedCount: 0,
          deletedCount: 0,
          insertResults: void 0,
          updateResults: void 0,
          deleteResults: void 0
        };
        if (options.verboseResults) {
          this.result.insertResults = /* @__PURE__ */ new Map();
          this.result.updateResults = /* @__PURE__ */ new Map();
          this.result.deleteResults = /* @__PURE__ */ new Map();
        }
      }
      /**
       * Get the bulk write result object.
       */
      get bulkWriteResult() {
        return {
          acknowledged: this.result.acknowledged,
          insertedCount: this.result.insertedCount,
          upsertedCount: this.result.upsertedCount,
          matchedCount: this.result.matchedCount,
          modifiedCount: this.result.modifiedCount,
          deletedCount: this.result.deletedCount,
          insertResults: this.result.insertResults,
          updateResults: this.result.updateResults,
          deleteResults: this.result.deleteResults
        };
      }
      /**
       * Merge the results in the cursor to the existing result.
       * @param currentBatchOffset - The offset index to the original models.
       * @param response - The cursor response.
       * @param documents - The documents in the cursor.
       * @returns The current result.
       */
      async merge(cursor) {
        let writeConcernErrorResult;
        try {
          for await (const document2 of cursor) {
            if (document2.ok === 1) {
              if (this.options.verboseResults) {
                this.processDocument(cursor, document2);
              }
            } else {
              if (this.options.ordered) {
                const error51 = new error_1.MongoClientBulkWriteError({
                  message: "Mongo client ordered bulk write encountered a write error."
                });
                error51.writeErrors.set(document2.idx + this.currentBatchOffset, {
                  code: document2.code,
                  message: document2.errmsg
                });
                error51.partialResult = this.result;
                throw error51;
              } else {
                this.writeErrors.set(document2.idx + this.currentBatchOffset, {
                  code: document2.code,
                  message: document2.errmsg
                });
              }
            }
          }
        } catch (error51) {
          if (error51 instanceof __1.MongoWriteConcernError) {
            const result = error51.result;
            writeConcernErrorResult = {
              insertedCount: result.nInserted,
              upsertedCount: result.nUpserted,
              matchedCount: result.nMatched,
              modifiedCount: result.nModified,
              deletedCount: result.nDeleted,
              writeConcernError: result.writeConcernError
            };
            if (this.options.verboseResults && result.cursor.firstBatch) {
              for (const document2 of result.cursor.firstBatch) {
                if (document2.ok === 1) {
                  this.processDocument(cursor, document2);
                }
              }
            }
          } else {
            throw error51;
          }
        } finally {
          if (cursor.response) {
            const response = cursor.response;
            this.incrementCounts(response);
          }
          this.currentBatchOffset += cursor.operations.length;
        }
        if (writeConcernErrorResult) {
          const writeConcernError = writeConcernErrorResult.writeConcernError;
          this.incrementCounts(writeConcernErrorResult);
          this.writeConcernErrors.push({
            code: writeConcernError.code,
            message: writeConcernError.errmsg
          });
        }
        return this.result;
      }
      /**
       * Process an individual document in the results.
       * @param cursor - The cursor.
       * @param document - The document to process.
       */
      processDocument(cursor, document2) {
        const operation = cursor.operations[document2.idx];
        if ("insert" in operation) {
          this.result.insertResults?.set(document2.idx + this.currentBatchOffset, {
            insertedId: operation.document._id
          });
        }
        if ("update" in operation) {
          const result = {
            matchedCount: document2.n,
            modifiedCount: document2.nModified ?? 0,
            // Check if the bulk did actually upsert.
            didUpsert: document2.upserted != null
          };
          if (document2.upserted) {
            result.upsertedId = document2.upserted._id;
          }
          this.result.updateResults?.set(document2.idx + this.currentBatchOffset, result);
        }
        if ("delete" in operation) {
          this.result.deleteResults?.set(document2.idx + this.currentBatchOffset, {
            deletedCount: document2.n
          });
        }
      }
      /**
       * Increment the result counts.
       * @param document - The document with the results.
       */
      incrementCounts(document2) {
        this.result.insertedCount += document2.insertedCount;
        this.result.upsertedCount += document2.upsertedCount;
        this.result.matchedCount += document2.matchedCount;
        this.result.modifiedCount += document2.modifiedCount;
        this.result.deletedCount += document2.deletedCount;
      }
    };
    exports2.ClientBulkWriteResultsMerger = ClientBulkWriteResultsMerger;
  }
});

// node_modules/mongodb/lib/operations/client_bulk_write/executor.js
var require_executor = __commonJS({
  "node_modules/mongodb/lib/operations/client_bulk_write/executor.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ClientBulkWriteExecutor = void 0;
    var abstract_cursor_1 = require_abstract_cursor();
    var client_bulk_write_cursor_1 = require_client_bulk_write_cursor();
    var error_1 = require_error();
    var timeout_1 = require_timeout();
    var utils_1 = require_utils();
    var write_concern_1 = require_write_concern();
    var execute_operation_1 = require_execute_operation();
    var client_bulk_write_1 = require_client_bulk_write();
    var command_builder_1 = require_command_builder();
    var results_merger_1 = require_results_merger();
    var ClientBulkWriteExecutor = class {
      /**
       * Instantiate the executor.
       * @param client - The mongo client.
       * @param operations - The user supplied bulk write models.
       * @param options - The bulk write options.
       */
      constructor(client, operations, options) {
        if (operations.length === 0) {
          throw new error_1.MongoClientBulkWriteExecutionError("No client bulk write models were provided.");
        }
        this.client = client;
        this.operations = operations;
        this.options = {
          ordered: true,
          bypassDocumentValidation: false,
          verboseResults: false,
          ...options
        };
        if (!this.options.writeConcern) {
          this.options.writeConcern = write_concern_1.WriteConcern.fromOptions(this.client.s.options);
        }
        if (this.options.writeConcern?.w === 0) {
          if (this.options.verboseResults) {
            throw new error_1.MongoInvalidArgumentError("Cannot request unacknowledged write concern and verbose results");
          }
          if (this.options.ordered) {
            throw new error_1.MongoInvalidArgumentError("Cannot request unacknowledged write concern and ordered writes");
          }
        }
      }
      /**
       * Execute the client bulk write. Will split commands into batches and exhaust the cursors
       * for each, then merge the results into one.
       * @returns The result.
       */
      async execute() {
        const pkFactory = this.client.s.options.pkFactory;
        const commandBuilder = new command_builder_1.ClientBulkWriteCommandBuilder(this.operations, this.options, pkFactory);
        const resolvedOptions = (0, utils_1.resolveTimeoutOptions)(this.client, this.options);
        const context = timeout_1.TimeoutContext.create(resolvedOptions);
        if (this.options.writeConcern?.w === 0) {
          while (commandBuilder.hasNextBatch()) {
            const operation = new client_bulk_write_1.ClientBulkWriteOperation(commandBuilder, this.options);
            await (0, execute_operation_1.executeOperation)(this.client, operation, context);
          }
          return results_merger_1.ClientBulkWriteResultsMerger.unacknowledged();
        } else {
          const resultsMerger = new results_merger_1.ClientBulkWriteResultsMerger(this.options);
          while (commandBuilder.hasNextBatch()) {
            const cursorContext = new abstract_cursor_1.CursorTimeoutContext(context, /* @__PURE__ */ Symbol());
            const options = {
              ...this.options,
              timeoutContext: cursorContext,
              ...resolvedOptions.timeoutMS != null && { timeoutMode: abstract_cursor_1.CursorTimeoutMode.LIFETIME }
            };
            const cursor = new client_bulk_write_cursor_1.ClientBulkWriteCursor(this.client, commandBuilder, options);
            try {
              await resultsMerger.merge(cursor);
            } catch (error51) {
              if (error51 instanceof error_1.MongoServerError && !(error51 instanceof error_1.MongoClientBulkWriteError)) {
                const bulkWriteError = new error_1.MongoClientBulkWriteError({
                  message: "Mongo client bulk write encountered an error during execution"
                });
                bulkWriteError.cause = error51;
                bulkWriteError.partialResult = resultsMerger.bulkWriteResult;
                throw bulkWriteError;
              } else {
                throw error51;
              }
            }
          }
          if (resultsMerger.writeConcernErrors.length > 0 || resultsMerger.writeErrors.size > 0) {
            const error51 = new error_1.MongoClientBulkWriteError({
              message: "Mongo client bulk write encountered errors during execution."
            });
            error51.writeConcernErrors = resultsMerger.writeConcernErrors;
            error51.writeErrors = resultsMerger.writeErrors;
            error51.partialResult = resultsMerger.bulkWriteResult;
            throw error51;
          }
          return resultsMerger.bulkWriteResult;
        }
      }
    };
    exports2.ClientBulkWriteExecutor = ClientBulkWriteExecutor;
  }
});

// node_modules/mongodb/lib/operations/end_sessions.js
var require_end_sessions = __commonJS({
  "node_modules/mongodb/lib/operations/end_sessions.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.EndSessionsOperation = void 0;
    var responses_1 = require_responses();
    var command_1 = require_command();
    var read_preference_1 = require_read_preference();
    var utils_1 = require_utils();
    var operation_1 = require_operation();
    var EndSessionsOperation = class extends command_1.CommandOperation {
      constructor(sessions) {
        super();
        this.writeConcern = { w: 0 };
        this.ns = utils_1.MongoDBNamespace.fromString("admin.$cmd");
        this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
        this.sessions = sessions;
      }
      buildCommandDocument(_connection, _session) {
        return {
          endSessions: this.sessions
        };
      }
      buildOptions(timeoutContext) {
        return {
          timeoutContext,
          readPreference: read_preference_1.ReadPreference.primaryPreferred
        };
      }
      get commandName() {
        return "endSessions";
      }
    };
    exports2.EndSessionsOperation = EndSessionsOperation;
    (0, operation_1.defineAspects)(EndSessionsOperation, operation_1.Aspect.WRITE_OPERATION);
  }
});

// node_modules/mongodb/lib/sdam/server_selection_events.js
var require_server_selection_events = __commonJS({
  "node_modules/mongodb/lib/sdam/server_selection_events.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.WaitingForSuitableServerEvent = exports2.ServerSelectionSucceededEvent = exports2.ServerSelectionFailedEvent = exports2.ServerSelectionStartedEvent = exports2.ServerSelectionEvent = void 0;
    var utils_1 = require_utils();
    var constants_1 = require_constants2();
    var ServerSelectionEvent = class {
      /** @internal */
      constructor(selector, topologyDescription, operation) {
        this.selector = selector;
        this.operation = operation;
        this.topologyDescription = topologyDescription;
      }
    };
    exports2.ServerSelectionEvent = ServerSelectionEvent;
    var ServerSelectionStartedEvent = class extends ServerSelectionEvent {
      /** @internal */
      constructor(selector, topologyDescription, operation) {
        super(selector, topologyDescription, operation);
        this.name = constants_1.SERVER_SELECTION_STARTED;
        this.message = "Server selection started";
      }
    };
    exports2.ServerSelectionStartedEvent = ServerSelectionStartedEvent;
    var ServerSelectionFailedEvent = class extends ServerSelectionEvent {
      /** @internal */
      constructor(selector, topologyDescription, error51, operation) {
        super(selector, topologyDescription, operation);
        this.name = constants_1.SERVER_SELECTION_FAILED;
        this.message = "Server selection failed";
        this.failure = error51;
      }
    };
    exports2.ServerSelectionFailedEvent = ServerSelectionFailedEvent;
    var ServerSelectionSucceededEvent = class extends ServerSelectionEvent {
      /** @internal */
      constructor(selector, topologyDescription, address, operation) {
        super(selector, topologyDescription, operation);
        this.name = constants_1.SERVER_SELECTION_SUCCEEDED;
        this.message = "Server selection succeeded";
        const { host, port } = utils_1.HostAddress.fromString(address).toHostPort();
        this.serverHost = host;
        this.serverPort = port;
      }
    };
    exports2.ServerSelectionSucceededEvent = ServerSelectionSucceededEvent;
    var WaitingForSuitableServerEvent = class extends ServerSelectionEvent {
      /** @internal */
      constructor(selector, topologyDescription, remainingTimeMS, operation) {
        super(selector, topologyDescription, operation);
        this.name = constants_1.WAITING_FOR_SUITABLE_SERVER;
        this.message = "Waiting for suitable server to become available";
        this.remainingTimeMS = remainingTimeMS;
      }
    };
    exports2.WaitingForSuitableServerEvent = WaitingForSuitableServerEvent;
  }
});

// node_modules/mongodb/lib/sdam/srv_polling.js
var require_srv_polling = __commonJS({
  "node_modules/mongodb/lib/sdam/srv_polling.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SrvPoller = exports2.SrvPollingEvent = void 0;
    var dns2 = require("dns");
    var timers_1 = require("timers");
    var error_1 = require_error();
    var mongo_types_1 = require_mongo_types();
    var utils_1 = require_utils();
    var SrvPollingEvent = class {
      constructor(srvRecords) {
        this.srvRecords = srvRecords;
      }
      hostnames() {
        return new Set(this.srvRecords.map((r2) => utils_1.HostAddress.fromSrvRecord(r2).toString()));
      }
    };
    exports2.SrvPollingEvent = SrvPollingEvent;
    var SrvPoller = class _SrvPoller extends mongo_types_1.TypedEventEmitter {
      static {
        this.SRV_RECORD_DISCOVERY = "srvRecordDiscovery";
      }
      constructor(options) {
        super();
        this.on("error", utils_1.noop);
        if (!options || !options.srvHost) {
          throw new error_1.MongoRuntimeError("Options for SrvPoller must exist and include srvHost");
        }
        this.srvHost = options.srvHost;
        this.srvMaxHosts = options.srvMaxHosts ?? 0;
        this.srvServiceName = options.srvServiceName ?? "mongodb";
        this.rescanSrvIntervalMS = 6e4;
        this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 1e4;
        this.haMode = false;
        this.generation = 0;
        this._timeout = void 0;
      }
      get srvAddress() {
        return `_${this.srvServiceName}._tcp.${this.srvHost}`;
      }
      get intervalMS() {
        return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMS;
      }
      start() {
        if (!this._timeout) {
          this.schedule();
        }
      }
      stop() {
        if (this._timeout) {
          (0, timers_1.clearTimeout)(this._timeout);
          this.generation += 1;
          this._timeout = void 0;
        }
      }
      // TODO(NODE-4994): implement new logging logic for SrvPoller failures
      schedule() {
        if (this._timeout) {
          (0, timers_1.clearTimeout)(this._timeout);
        }
        this._timeout = (0, timers_1.setTimeout)(() => {
          this._poll().then(void 0, utils_1.squashError);
        }, this.intervalMS);
      }
      success(srvRecords) {
        this.haMode = false;
        this.schedule();
        this.emit(_SrvPoller.SRV_RECORD_DISCOVERY, new SrvPollingEvent(srvRecords));
      }
      failure() {
        this.haMode = true;
        this.schedule();
      }
      async _poll() {
        const generation = this.generation;
        let srvRecords;
        try {
          srvRecords = await dns2.promises.resolve(this.srvAddress, "SRV");
        } catch {
          this.failure();
          return;
        }
        if (generation !== this.generation) {
          return;
        }
        const finalAddresses = [];
        for (const record2 of srvRecords) {
          try {
            (0, utils_1.checkParentDomainMatch)(record2.name, this.srvHost);
            finalAddresses.push(record2);
          } catch (error51) {
            (0, utils_1.squashError)(error51);
          }
        }
        if (!finalAddresses.length) {
          this.failure();
          return;
        }
        this.success(finalAddresses);
      }
    };
    exports2.SrvPoller = SrvPoller;
  }
});

// node_modules/mongodb/lib/sdam/topology.js
var require_topology = __commonJS({
  "node_modules/mongodb/lib/sdam/topology.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Topology = void 0;
    var connection_string_1 = require_connection_string();
    var constants_1 = require_constants2();
    var error_1 = require_error();
    var mongo_logger_1 = require_mongo_logger();
    var mongo_types_1 = require_mongo_types();
    var read_preference_1 = require_read_preference();
    var timeout_1 = require_timeout();
    var utils_1 = require_utils();
    var common_1 = require_common();
    var events_1 = require_events();
    var server_1 = require_server();
    var server_description_1 = require_server_description();
    var server_selection_1 = require_server_selection();
    var server_selection_events_1 = require_server_selection_events();
    var srv_polling_1 = require_srv_polling();
    var topology_description_1 = require_topology_description();
    var globalTopologyCounter = 0;
    var stateTransition = (0, utils_1.makeStateMachine)({
      [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, common_1.STATE_CONNECTING],
      [common_1.STATE_CONNECTING]: [common_1.STATE_CONNECTING, common_1.STATE_CLOSING, common_1.STATE_CONNECTED, common_1.STATE_CLOSED],
      [common_1.STATE_CONNECTED]: [common_1.STATE_CONNECTED, common_1.STATE_CLOSING, common_1.STATE_CLOSED],
      [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, common_1.STATE_CLOSED]
    });
    var Topology = class _Topology extends mongo_types_1.TypedEventEmitter {
      static {
        this.SERVER_OPENING = constants_1.SERVER_OPENING;
      }
      static {
        this.SERVER_CLOSED = constants_1.SERVER_CLOSED;
      }
      static {
        this.SERVER_DESCRIPTION_CHANGED = constants_1.SERVER_DESCRIPTION_CHANGED;
      }
      static {
        this.TOPOLOGY_OPENING = constants_1.TOPOLOGY_OPENING;
      }
      static {
        this.TOPOLOGY_CLOSED = constants_1.TOPOLOGY_CLOSED;
      }
      static {
        this.TOPOLOGY_DESCRIPTION_CHANGED = constants_1.TOPOLOGY_DESCRIPTION_CHANGED;
      }
      static {
        this.ERROR = constants_1.ERROR;
      }
      static {
        this.OPEN = constants_1.OPEN;
      }
      static {
        this.CONNECT = constants_1.CONNECT;
      }
      static {
        this.CLOSE = constants_1.CLOSE;
      }
      static {
        this.TIMEOUT = constants_1.TIMEOUT;
      }
      /**
       * @param seedlist - a list of HostAddress instances to connect to
       */
      constructor(client, seeds, options) {
        super();
        this.on("error", utils_1.noop);
        this.client = client;
        options = options ?? {
          hosts: [utils_1.HostAddress.fromString("localhost:27017")],
          ...Object.fromEntries(connection_string_1.DEFAULT_OPTIONS.entries())
        };
        if (typeof seeds === "string") {
          seeds = [utils_1.HostAddress.fromString(seeds)];
        } else if (!Array.isArray(seeds)) {
          seeds = [seeds];
        }
        const seedlist = [];
        for (const seed of seeds) {
          if (typeof seed === "string") {
            seedlist.push(utils_1.HostAddress.fromString(seed));
          } else if (seed instanceof utils_1.HostAddress) {
            seedlist.push(seed);
          } else {
            throw new error_1.MongoRuntimeError(`Topology cannot be constructed from ${JSON.stringify(seed)}`);
          }
        }
        const topologyType = topologyTypeFromOptions(options);
        const topologyId = globalTopologyCounter++;
        const selectedHosts = options.srvMaxHosts == null || options.srvMaxHosts === 0 || options.srvMaxHosts >= seedlist.length ? seedlist : (0, utils_1.shuffle)(seedlist, options.srvMaxHosts);
        const serverDescriptions = /* @__PURE__ */ new Map();
        for (const hostAddress of selectedHosts) {
          serverDescriptions.set(hostAddress.toString(), new server_description_1.ServerDescription(hostAddress));
        }
        this.waitQueue = new utils_1.List();
        this.s = {
          // the id of this topology
          id: topologyId,
          // passed in options
          options,
          // initial seedlist of servers to connect to
          seedlist,
          // initial state
          state: common_1.STATE_CLOSED,
          // the topology description
          description: new topology_description_1.TopologyDescription(topologyType, serverDescriptions, options.replicaSet, void 0, void 0, void 0, options),
          serverSelectionTimeoutMS: options.serverSelectionTimeoutMS,
          heartbeatFrequencyMS: options.heartbeatFrequencyMS,
          minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS,
          // a map of server instances to normalized addresses
          servers: /* @__PURE__ */ new Map(),
          credentials: options?.credentials,
          clusterTime: void 0,
          detectShardedTopology: (ev) => this.detectShardedTopology(ev),
          detectSrvRecords: (ev) => this.detectSrvRecords(ev)
        };
        this.mongoLogger = client.mongoLogger;
        this.component = "topology";
        if (options.srvHost && !options.loadBalanced) {
          this.s.srvPoller = options.srvPoller ?? new srv_polling_1.SrvPoller({
            heartbeatFrequencyMS: this.s.heartbeatFrequencyMS,
            srvHost: options.srvHost,
            srvMaxHosts: options.srvMaxHosts,
            srvServiceName: options.srvServiceName
          });
          this.on(_Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology);
        }
        this.connectionLock = void 0;
      }
      detectShardedTopology(event) {
        const previousType = event.previousDescription.type;
        const newType = event.newDescription.type;
        const transitionToSharded = previousType !== common_1.TopologyType.Sharded && newType === common_1.TopologyType.Sharded;
        const srvListeners = this.s.srvPoller?.listeners(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY);
        const listeningToSrvPolling = !!srvListeners?.includes(this.s.detectSrvRecords);
        if (transitionToSharded && !listeningToSrvPolling) {
          this.s.srvPoller?.on(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords);
          this.s.srvPoller?.start();
        }
      }
      detectSrvRecords(ev) {
        const previousTopologyDescription = this.s.description;
        this.s.description = this.s.description.updateFromSrvPollingEvent(ev, this.s.options.srvMaxHosts);
        if (this.s.description === previousTopologyDescription) {
          return;
        }
        updateServers(this);
        this.emitAndLog(_Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(this.s.id, previousTopologyDescription, this.s.description));
      }
      /**
       * @returns A `TopologyDescription` for this topology
       */
      get description() {
        return this.s.description;
      }
      get loadBalanced() {
        return this.s.options.loadBalanced;
      }
      get serverApi() {
        return this.s.options.serverApi;
      }
      /** Initiate server connect */
      async connect(options) {
        this.connectionLock ??= this._connect(options);
        try {
          await this.connectionLock;
          return this;
        } finally {
          this.connectionLock = void 0;
        }
      }
      async _connect(options) {
        options = options ?? {};
        if (this.s.state === common_1.STATE_CONNECTED) {
          return this;
        }
        stateTransition(this, common_1.STATE_CONNECTING);
        this.emitAndLog(_Topology.TOPOLOGY_OPENING, new events_1.TopologyOpeningEvent(this.s.id));
        this.emitAndLog(_Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(
          this.s.id,
          new topology_description_1.TopologyDescription(common_1.TopologyType.Unknown),
          // initial is always Unknown
          this.s.description
        ));
        const serverDescriptions = Array.from(this.s.description.servers.values());
        this.s.servers = new Map(serverDescriptions.map((serverDescription) => [
          serverDescription.address,
          createAndConnectServer(this, serverDescription)
        ]));
        if (this.s.options.loadBalanced) {
          for (const description of serverDescriptions) {
            const newDescription = new server_description_1.ServerDescription(description.hostAddress, void 0, {
              loadBalanced: this.s.options.loadBalanced
            });
            this.serverUpdateHandler(newDescription);
          }
        }
        const serverSelectionTimeoutMS = this.client.s.options.serverSelectionTimeoutMS;
        const readPreference = options.readPreference ?? read_preference_1.ReadPreference.primary;
        const timeoutContext = timeout_1.TimeoutContext.create({
          // TODO(NODE-6448): auto-connect ignores timeoutMS; potential future feature
          timeoutMS: void 0,
          serverSelectionTimeoutMS,
          waitQueueTimeoutMS: this.client.s.options.waitQueueTimeoutMS
        });
        const selectServerOptions = {
          operationName: "handshake",
          ...options,
          timeoutContext,
          deprioritizedServers: new server_selection_1.DeprioritizedServers()
        };
        try {
          const server = await this.selectServer((0, server_selection_1.readPreferenceServerSelector)(readPreference), selectServerOptions);
          const skipPingOnConnect = this.s.options.__skipPingOnConnect === true;
          if (!skipPingOnConnect) {
            const connection = await server.pool.checkOut({ timeoutContext });
            server.pool.checkIn(connection);
            stateTransition(this, common_1.STATE_CONNECTED);
            this.emit(_Topology.OPEN, this);
            this.emit(_Topology.CONNECT, this);
            return this;
          }
          stateTransition(this, common_1.STATE_CONNECTED);
          this.emit(_Topology.OPEN, this);
          this.emit(_Topology.CONNECT, this);
          return this;
        } catch (error51) {
          this.close();
          throw error51;
        }
      }
      closeCheckedOutConnections() {
        for (const server of this.s.servers.values()) {
          server.closeCheckedOutConnections();
        }
      }
      /** Close this topology */
      close() {
        if (this.s.state === common_1.STATE_CLOSED || this.s.state === common_1.STATE_CLOSING) {
          return;
        }
        for (const server of this.s.servers.values()) {
          closeServer(server, this);
        }
        this.s.servers.clear();
        stateTransition(this, common_1.STATE_CLOSING);
        drainWaitQueue(this.waitQueue, new error_1.MongoTopologyClosedError());
        if (this.s.srvPoller) {
          this.s.srvPoller.stop();
          this.s.srvPoller.removeListener(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords);
        }
        this.removeListener(_Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology);
        stateTransition(this, common_1.STATE_CLOSED);
        this.emitAndLog(_Topology.TOPOLOGY_CLOSED, new events_1.TopologyClosedEvent(this.s.id));
      }
      /**
       * Selects a server according to the selection predicate provided
       *
       * @param selector - An optional selector to select servers by, defaults to a random selection within a latency window
       * @param options - Optional settings related to server selection
       * @param callback - The callback used to indicate success or failure
       * @returns An instance of a `Server` meeting the criteria of the predicate provided
       */
      async selectServer(selector, options) {
        let serverSelector;
        if (typeof selector !== "function") {
          if (typeof selector === "string") {
            serverSelector = (0, server_selection_1.readPreferenceServerSelector)(read_preference_1.ReadPreference.fromString(selector));
          } else {
            let readPreference;
            if (selector instanceof read_preference_1.ReadPreference) {
              readPreference = selector;
            } else {
              read_preference_1.ReadPreference.translate(options);
              readPreference = options.readPreference || read_preference_1.ReadPreference.primary;
            }
            serverSelector = (0, server_selection_1.readPreferenceServerSelector)(readPreference);
          }
        } else {
          serverSelector = selector;
        }
        options = { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS, ...options };
        if (this.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) {
          this.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionStartedEvent(selector, this.description, options.operationName));
        }
        let timeout;
        if (options.timeoutContext)
          timeout = options.timeoutContext.serverSelectionTimeout;
        else {
          timeout = timeout_1.Timeout.expires(options.serverSelectionTimeoutMS ?? 0);
        }
        const isSharded = this.description.type === common_1.TopologyType.Sharded;
        const session = options.session;
        const transaction = session && session.transaction;
        if (isSharded && transaction && transaction.server) {
          if (this.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) {
            this.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionSucceededEvent(selector, this.description, transaction.server.pool.address, options.operationName));
          }
          if (!options.timeoutContext || options.timeoutContext.clearServerSelectionTimeout) {
            timeout?.clear();
          }
          return transaction.server;
        }
        const { promise: serverPromise, resolve: resolve2, reject } = (0, utils_1.promiseWithResolvers)();
        const waitQueueMember = {
          serverSelector,
          topologyDescription: this.description,
          mongoLogger: this.client.mongoLogger,
          transaction,
          resolve: resolve2,
          reject,
          cancelled: false,
          startTime: (0, utils_1.processTimeMS)(),
          operationName: options.operationName,
          waitingLogged: false,
          deprioritizedServers: options.deprioritizedServers
        };
        const abortListener = (0, utils_1.addAbortListener)(options.signal, function() {
          waitQueueMember.cancelled = true;
          reject(this.reason);
        });
        this.waitQueue.push(waitQueueMember);
        processWaitQueue(this);
        try {
          timeout?.throwIfExpired();
          const server = await (timeout ? Promise.race([serverPromise, timeout]) : serverPromise);
          if (options.timeoutContext?.csotEnabled() && server.description.minRoundTripTime !== 0) {
            options.timeoutContext.minRoundTripTime = server.description.minRoundTripTime;
          }
          return server;
        } catch (error51) {
          if (timeout_1.TimeoutError.is(error51)) {
            waitQueueMember.cancelled = true;
            const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${timeout?.duration} ms`, this.description);
            if (this.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) {
              this.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(selector, this.description, timeoutError, options.operationName));
            }
            if (options.timeoutContext?.csotEnabled()) {
              throw new error_1.MongoOperationTimeoutError("Timed out during server selection", {
                cause: timeoutError
              });
            }
            throw timeoutError;
          }
          throw error51;
        } finally {
          abortListener?.[utils_1.kDispose]();
          if (!options.timeoutContext || options.timeoutContext.clearServerSelectionTimeout) {
            timeout?.clear();
          }
        }
      }
      /**
       * Update the internal TopologyDescription with a ServerDescription
       *
       * @param serverDescription - The server to update in the internal list of server descriptions
       */
      serverUpdateHandler(serverDescription) {
        if (!this.s.description.hasServer(serverDescription.address)) {
          return;
        }
        if (isStaleServerDescription(this.s.description, serverDescription)) {
          return;
        }
        const previousTopologyDescription = this.s.description;
        const previousServerDescription = this.s.description.servers.get(serverDescription.address);
        if (!previousServerDescription) {
          return;
        }
        const clusterTime = serverDescription.$clusterTime;
        if (clusterTime) {
          (0, common_1._advanceClusterTime)(this, clusterTime);
        }
        const equalDescriptions = previousServerDescription && previousServerDescription.equals(serverDescription);
        this.s.description = this.s.description.update(serverDescription);
        if (this.s.description.compatibilityError) {
          this.emit(_Topology.ERROR, new error_1.MongoCompatibilityError(this.s.description.compatibilityError));
          return;
        }
        if (!equalDescriptions) {
          const newDescription = this.s.description.servers.get(serverDescription.address);
          if (newDescription) {
            this.emit(_Topology.SERVER_DESCRIPTION_CHANGED, new events_1.ServerDescriptionChangedEvent(this.s.id, serverDescription.address, previousServerDescription, newDescription));
          }
        }
        updateServers(this, serverDescription);
        if (this.waitQueue.length > 0) {
          processWaitQueue(this);
        }
        if (!equalDescriptions) {
          this.emitAndLog(_Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(this.s.id, previousTopologyDescription, this.s.description));
        }
      }
      auth(credentials, callback) {
        if (typeof credentials === "function")
          callback = credentials, credentials = void 0;
        if (typeof callback === "function")
          callback(void 0, true);
      }
      isConnected() {
        return this.s.state === common_1.STATE_CONNECTED;
      }
      isDestroyed() {
        return this.s.state === common_1.STATE_CLOSED;
      }
      // NOTE: There are many places in code where we explicitly check the last hello
      //       to do feature support detection. This should be done any other way, but for
      //       now we will just return the first hello seen, which should suffice.
      lastHello() {
        const serverDescriptions = Array.from(this.description.servers.values());
        if (serverDescriptions.length === 0)
          return {};
        const sd = serverDescriptions.filter((sd2) => sd2.type !== common_1.ServerType.Unknown)[0];
        const result = sd || { maxWireVersion: this.description.commonWireVersion };
        return result;
      }
      get commonWireVersion() {
        return this.description.commonWireVersion;
      }
      get logicalSessionTimeoutMinutes() {
        return this.description.logicalSessionTimeoutMinutes;
      }
      get clusterTime() {
        return this.s.clusterTime;
      }
      set clusterTime(clusterTime) {
        this.s.clusterTime = clusterTime;
      }
    };
    exports2.Topology = Topology;
    function closeServer(server, topology) {
      for (const event of constants_1.LOCAL_SERVER_EVENTS) {
        server.removeAllListeners(event);
      }
      server.close();
      topology.emitAndLog(Topology.SERVER_CLOSED, new events_1.ServerClosedEvent(topology.s.id, server.description.address));
      for (const event of constants_1.SERVER_RELAY_EVENTS) {
        server.removeAllListeners(event);
      }
    }
    function topologyTypeFromOptions(options) {
      if (options?.directConnection) {
        return common_1.TopologyType.Single;
      }
      if (options?.replicaSet) {
        return common_1.TopologyType.ReplicaSetNoPrimary;
      }
      if (options?.loadBalanced) {
        return common_1.TopologyType.LoadBalanced;
      }
      return common_1.TopologyType.Unknown;
    }
    function createAndConnectServer(topology, serverDescription) {
      topology.emitAndLog(Topology.SERVER_OPENING, new events_1.ServerOpeningEvent(topology.s.id, serverDescription.address));
      const server = new server_1.Server(topology, serverDescription, topology.s.options);
      for (const event of constants_1.SERVER_RELAY_EVENTS) {
        server.on(event, (e2) => topology.emit(event, e2));
      }
      server.on(server_1.Server.DESCRIPTION_RECEIVED, (description) => topology.serverUpdateHandler(description));
      server.connect();
      return server;
    }
    function updateServers(topology, incomingServerDescription) {
      if (incomingServerDescription && topology.s.servers.has(incomingServerDescription.address)) {
        const server = topology.s.servers.get(incomingServerDescription.address);
        if (server) {
          server.s.description = incomingServerDescription;
          if (incomingServerDescription.error instanceof error_1.MongoError && incomingServerDescription.error.hasErrorLabel(error_1.MongoErrorLabel.ResetPool)) {
            const interruptInUseConnections = incomingServerDescription.error.hasErrorLabel(error_1.MongoErrorLabel.InterruptInUseConnections);
            server.pool.clear({ interruptInUseConnections });
          } else if (incomingServerDescription.error == null) {
            const newTopologyType = topology.s.description.type;
            const shouldMarkPoolReady = incomingServerDescription.isDataBearing || incomingServerDescription.type !== common_1.ServerType.Unknown && newTopologyType === common_1.TopologyType.Single;
            if (shouldMarkPoolReady) {
              server.pool.ready();
            }
          }
        }
      }
      for (const serverDescription of topology.description.servers.values()) {
        if (!topology.s.servers.has(serverDescription.address)) {
          const server = createAndConnectServer(topology, serverDescription);
          topology.s.servers.set(serverDescription.address, server);
        }
      }
      for (const entry of topology.s.servers) {
        const serverAddress = entry[0];
        if (topology.description.hasServer(serverAddress)) {
          continue;
        }
        if (!topology.s.servers.has(serverAddress)) {
          continue;
        }
        const server = topology.s.servers.get(serverAddress);
        topology.s.servers.delete(serverAddress);
        if (server) {
          closeServer(server, topology);
        }
      }
    }
    function drainWaitQueue(queue, drainError) {
      while (queue.length) {
        const waitQueueMember = queue.shift();
        if (!waitQueueMember) {
          continue;
        }
        if (!waitQueueMember.cancelled) {
          if (waitQueueMember.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) {
            waitQueueMember.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(waitQueueMember.serverSelector, waitQueueMember.topologyDescription, drainError, waitQueueMember.operationName));
          }
          waitQueueMember.reject(drainError);
        }
      }
    }
    function processWaitQueue(topology) {
      if (topology.s.state === common_1.STATE_CLOSED) {
        drainWaitQueue(topology.waitQueue, new error_1.MongoTopologyClosedError());
        return;
      }
      const isSharded = topology.description.type === common_1.TopologyType.Sharded;
      const serverDescriptions = Array.from(topology.description.servers.values());
      const membersToProcess = topology.waitQueue.length;
      for (let i2 = 0; i2 < membersToProcess; ++i2) {
        const waitQueueMember = topology.waitQueue.shift();
        if (!waitQueueMember) {
          continue;
        }
        if (waitQueueMember.cancelled) {
          continue;
        }
        let selectedDescriptions;
        try {
          const serverSelector = waitQueueMember.serverSelector;
          const deprioritizedServers = waitQueueMember.deprioritizedServers;
          selectedDescriptions = serverSelector ? serverSelector(topology.description, serverDescriptions, deprioritizedServers) : serverDescriptions;
        } catch (selectorError) {
          if (topology.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) {
            topology.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(waitQueueMember.serverSelector, topology.description, selectorError, waitQueueMember.operationName));
          }
          waitQueueMember.reject(selectorError);
          continue;
        }
        let selectedServer;
        if (selectedDescriptions.length === 0) {
          if (!waitQueueMember.waitingLogged) {
            if (topology.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.INFORMATIONAL)) {
              topology.client.mongoLogger?.info(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.WaitingForSuitableServerEvent(waitQueueMember.serverSelector, topology.description, topology.s.serverSelectionTimeoutMS !== 0 ? topology.s.serverSelectionTimeoutMS - ((0, utils_1.processTimeMS)() - waitQueueMember.startTime) : -1, waitQueueMember.operationName));
            }
            waitQueueMember.waitingLogged = true;
          }
          topology.waitQueue.push(waitQueueMember);
          continue;
        } else if (selectedDescriptions.length === 1) {
          selectedServer = topology.s.servers.get(selectedDescriptions[0].address);
        } else {
          const descriptions = (0, utils_1.shuffle)(selectedDescriptions, 2);
          const server1 = topology.s.servers.get(descriptions[0].address);
          const server2 = topology.s.servers.get(descriptions[1].address);
          selectedServer = server1 && server2 && server1.s.operationCount < server2.s.operationCount ? server1 : server2;
        }
        if (!selectedServer) {
          const serverSelectionError = new error_1.MongoServerSelectionError("server selection returned a server description but the server was not found in the topology", topology.description);
          if (topology.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) {
            topology.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(waitQueueMember.serverSelector, topology.description, serverSelectionError, waitQueueMember.operationName));
          }
          waitQueueMember.reject(serverSelectionError);
          return;
        }
        const transaction = waitQueueMember.transaction;
        if (isSharded && transaction && transaction.isActive && selectedServer) {
          transaction.pinServer(selectedServer);
        }
        if (topology.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) {
          topology.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionSucceededEvent(waitQueueMember.serverSelector, waitQueueMember.topologyDescription, selectedServer.pool.address, waitQueueMember.operationName));
        }
        waitQueueMember.resolve(selectedServer);
      }
      if (topology.waitQueue.length > 0) {
        for (const [, server] of topology.s.servers) {
          queueMicrotask(function scheduleServerCheck() {
            return server.requestCheck();
          });
        }
      }
    }
    function isStaleServerDescription(topologyDescription, incomingServerDescription) {
      const currentServerDescription = topologyDescription.servers.get(incomingServerDescription.address);
      const currentTopologyVersion = currentServerDescription?.topologyVersion;
      return (0, server_description_1.compareTopologyVersion)(currentTopologyVersion, incomingServerDescription.topologyVersion) > 0;
    }
  }
});

// node_modules/mongodb/lib/mongo_client.js
var require_mongo_client = __commonJS({
  "node_modules/mongodb/lib/mongo_client.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MongoClient = exports2.ServerApiVersion = void 0;
    var fs_1 = require("fs");
    var _1 = require_lib3();
    var bson_1 = require_bson2();
    var change_stream_1 = require_change_stream();
    var mongo_credentials_1 = require_mongo_credentials();
    var providers_1 = require_providers();
    var client_metadata_1 = require_client_metadata();
    var connection_string_1 = require_connection_string();
    var constants_1 = require_constants2();
    var db_1 = require_db();
    var error_1 = require_error();
    var mongo_client_auth_providers_1 = require_mongo_client_auth_providers();
    var mongo_logger_1 = require_mongo_logger();
    var mongo_types_1 = require_mongo_types();
    var executor_1 = require_executor();
    var end_sessions_1 = require_end_sessions();
    var execute_operation_1 = require_execute_operation();
    var read_preference_1 = require_read_preference();
    var server_selection_1 = require_server_selection();
    var topology_1 = require_topology();
    var sessions_1 = require_sessions();
    var utils_1 = require_utils();
    exports2.ServerApiVersion = Object.freeze({
      v1: "1"
    });
    var MongoClient2 = class extends mongo_types_1.TypedEventEmitter {
      constructor(url2, options) {
        super();
        this.driverInfoList = [];
        this.on("error", utils_1.noop);
        this.options = (0, connection_string_1.parseOptions)(url2, this, options);
        this.appendMetadata(this.options.driverInfo);
        const shouldSetLogger = Object.values(this.options.mongoLoggerOptions.componentSeverities).some((value) => value !== mongo_logger_1.SeverityLevel.OFF);
        this.mongoLogger = shouldSetLogger ? new mongo_logger_1.MongoLogger(this.options.mongoLoggerOptions) : void 0;
        const client = this;
        this.s = {
          url: url2,
          bsonOptions: (0, bson_1.resolveBSONOptions)(this.options),
          namespace: (0, utils_1.ns)("admin"),
          hasBeenClosed: false,
          sessionPool: new sessions_1.ServerSessionPool(this),
          activeSessions: /* @__PURE__ */ new Set(),
          activeCursors: /* @__PURE__ */ new Set(),
          authProviders: new mongo_client_auth_providers_1.MongoClientAuthProviders(),
          get options() {
            return client.options;
          },
          get readConcern() {
            return client.options.readConcern;
          },
          get writeConcern() {
            return client.options.writeConcern;
          },
          get readPreference() {
            return client.options.readPreference;
          },
          get isMongoClient() {
            return true;
          }
        };
        this.checkForNonGenuineHosts();
      }
      /**
       * An alias for {@link MongoClient.close|MongoClient.close()}.
       */
      async [Symbol.asyncDispose]() {
        await this.close();
      }
      /**
       * Append metadata to the client metadata after instantiation.
       * @param driverInfo - Information about the application or library.
       */
      appendMetadata(driverInfo) {
        const isDuplicateDriverInfo = this.driverInfoList.some((info) => (0, client_metadata_1.isDriverInfoEqual)(info, driverInfo));
        if (isDuplicateDriverInfo)
          return;
        this.driverInfoList.push(driverInfo);
        this.options.metadata = (0, client_metadata_1.makeClientMetadata)(this.driverInfoList, this.options).then(void 0, utils_1.squashError).then((result) => result ?? {});
      }
      /** @internal */
      checkForNonGenuineHosts() {
        const documentDBHostnames = this.options.hosts.filter((hostAddress) => (0, utils_1.isHostMatch)(utils_1.DOCUMENT_DB_CHECK, hostAddress.host));
        const srvHostIsDocumentDB = (0, utils_1.isHostMatch)(utils_1.DOCUMENT_DB_CHECK, this.options.srvHost);
        const cosmosDBHostnames = this.options.hosts.filter((hostAddress) => (0, utils_1.isHostMatch)(utils_1.COSMOS_DB_CHECK, hostAddress.host));
        const srvHostIsCosmosDB = (0, utils_1.isHostMatch)(utils_1.COSMOS_DB_CHECK, this.options.srvHost);
        if (documentDBHostnames.length !== 0 || srvHostIsDocumentDB) {
          this.mongoLogger?.info("client", utils_1.DOCUMENT_DB_MSG);
        } else if (cosmosDBHostnames.length !== 0 || srvHostIsCosmosDB) {
          this.mongoLogger?.info("client", utils_1.COSMOS_DB_MSG);
        }
      }
      get serverApi() {
        return this.options.serverApi && Object.freeze({ ...this.options.serverApi });
      }
      /**
       * Intended for APM use only
       * @internal
       */
      get monitorCommands() {
        return this.options.monitorCommands;
      }
      set monitorCommands(value) {
        this.options.monitorCommands = value;
      }
      /** @internal */
      get autoEncrypter() {
        return this.options.autoEncrypter;
      }
      get readConcern() {
        return this.s.readConcern;
      }
      get writeConcern() {
        return this.s.writeConcern;
      }
      get readPreference() {
        return this.s.readPreference;
      }
      get bsonOptions() {
        return this.s.bsonOptions;
      }
      get timeoutMS() {
        return this.s.options.timeoutMS;
      }
      /**
       * Executes a client bulk write operation, available on server 8.0+.
       * @param models - The client bulk write models.
       * @param options - The client bulk write options.
       * @returns A ClientBulkWriteResult for acknowledged writes and ok: 1 for unacknowledged writes.
       */
      async bulkWrite(models, options) {
        if (this.autoEncrypter) {
          throw new error_1.MongoInvalidArgumentError("MongoClient bulkWrite does not currently support automatic encryption.");
        }
        return await new executor_1.ClientBulkWriteExecutor(this, models, (0, utils_1.resolveOptions)(this, options)).execute();
      }
      /**
       * An optional method to verify a handful of assumptions that are generally useful at application boot-time before using a MongoClient.
       * For detailed information about the connect process see the MongoClient.connect static method documentation.
       *
       * @param url - The MongoDB connection string (supports `mongodb://` and `mongodb+srv://` schemes)
       * @param options - Optional configuration options for the client
       *
       * @see https://www.mongodb.com/docs/manual/reference/connection-string/
       */
      async connect() {
        if (this.connectionLock) {
          return await this.connectionLock;
        }
        try {
          this.connectionLock = this._connect();
          await this.connectionLock;
        } finally {
          this.connectionLock = void 0;
        }
        return this;
      }
      /**
       * Create a topology to open the connection, must be locked to avoid topology leaks in concurrency scenario.
       * Locking is enforced by the connect method.
       *
       * @internal
       */
      async _connect() {
        if (this.topology && this.topology.isConnected()) {
          return this;
        }
        const options = this.options;
        if (options.tls) {
          if (typeof options.tlsCAFile === "string") {
            options.ca ??= await fs_1.promises.readFile(options.tlsCAFile);
          }
          if (typeof options.tlsCRLFile === "string") {
            options.crl ??= await fs_1.promises.readFile(options.tlsCRLFile);
          }
          if (typeof options.tlsCertificateKeyFile === "string") {
            if (!options.key || !options.cert) {
              const contents = await fs_1.promises.readFile(options.tlsCertificateKeyFile);
              options.key ??= contents;
              options.cert ??= contents;
            }
          }
        }
        if (typeof options.srvHost === "string") {
          const hosts = await (0, connection_string_1.resolveSRVRecord)(options);
          for (const [index, host] of hosts.entries()) {
            options.hosts[index] = host;
          }
        }
        if (options.credentials?.mechanism === providers_1.AuthMechanism.MONGODB_OIDC) {
          const allowedHosts = options.credentials?.mechanismProperties?.ALLOWED_HOSTS || mongo_credentials_1.DEFAULT_ALLOWED_HOSTS;
          const isServiceAuth = !!options.credentials?.mechanismProperties?.ENVIRONMENT;
          if (!isServiceAuth) {
            for (const host of options.hosts) {
              if (!(0, utils_1.hostMatchesWildcards)(host.toHostPort().host, allowedHosts)) {
                throw new error_1.MongoInvalidArgumentError(`Host '${host}' is not valid for OIDC authentication with ALLOWED_HOSTS of '${allowedHosts.join(",")}'`);
              }
            }
          }
        }
        this.topology = new topology_1.Topology(this, options.hosts, options);
        this.topology.once(topology_1.Topology.OPEN, () => this.emit("open", this));
        for (const event of constants_1.MONGO_CLIENT_EVENTS) {
          this.topology.on(event, (...args) => this.emit(event, ...args));
        }
        const topologyConnect = async () => {
          try {
            await this.topology?.connect(options);
          } catch (error51) {
            this.topology?.close();
            throw error51;
          }
        };
        if (this.autoEncrypter) {
          await this.autoEncrypter?.init();
          await topologyConnect();
          await options.encrypter.connectInternalClient();
        } else {
          await topologyConnect();
        }
        return this;
      }
      /**
       * Cleans up resources managed by the MongoClient.
       *
       * The close method clears and closes all resources whose lifetimes are managed by the MongoClient.
       * Please refer to the `MongoClient` class documentation for a high level overview of the client's key features and responsibilities.
       *
       * **However,** the close method does not handle the cleanup of resources explicitly created by the user.
       * Any user-created driver resource with its own `close()` method should be explicitly closed by the user before calling MongoClient.close().
       * This method is written as a "best effort" attempt to leave behind the least amount of resources server-side when possible.
       *
       * The following list defines ideal preconditions and consequent pitfalls if they are not met.
       * The MongoClient, ClientSession, Cursors and ChangeStreams all support [explicit resource management](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html).
       * By using explicit resource management to manage the lifetime of driver resources instead of manually managing their lifetimes, the pitfalls outlined below can be avoided.
       *
       * The close method performs the following in the order listed:
       * - Client-side:
       *   - **Close in-use connections**: Any connections that are currently waiting on a response from the server will be closed.
       *     This is performed _first_ to avoid reaching the next step (server-side clean up) and having no available connections to check out.
       *     - _Ideal_: All operations have been awaited or cancelled, and the outcomes, regardless of success or failure, have been processed before closing the client servicing the operation.
       *     - _Pitfall_: When `client.close()` is called and all connections are in use, after closing them, the client must create new connections for cleanup operations, which comes at the cost of new TLS/TCP handshakes and authentication steps.
       * - Server-side:
       *   - **Close active cursors**: All cursors that haven't been completed will have a `killCursor` operation sent to the server they were initialized on, freeing the server-side resource.
       *     - _Ideal_: Cursors are explicitly closed or completed before `client.close()` is called.
       *     - _Pitfall_: `killCursors` may have to build a new connection if the in-use closure ended all pooled connections.
       *   - **End active sessions**: In-use sessions created with `client.startSession()` or `client.withSession()` or implicitly by the driver will have their `.endSession()` method called.
       *     Contrary to the name of the method, `endSession()` returns the session to the client's pool of sessions rather than end them on the server.
       *     - _Ideal_: Transaction outcomes are awaited and their corresponding explicit sessions are ended before `client.close()` is called.
       *     - _Pitfall_: **This step aborts in-progress transactions**. It is advisable to observe the outcome of a transaction before closing your client.
       *   - **End all pooled sessions**: The `endSessions` command with all session IDs the client has pooled is sent to the server to inform the cluster it can clean them up.
       *     - _Ideal_: No user intervention is expected.
       *     - _Pitfall_: None.
       *
       * The remaining shutdown is of the MongoClient resources that are intended to be entirely internal but is documented here as their existence relates to the JS event loop.
       *
       * - Client-side (again):
       *   - **Stop all server monitoring**: Connections kept live for detecting cluster changes and roundtrip time measurements are shutdown.
       *   - **Close all pooled connections**: Each server node in the cluster has a corresponding connection pool and all connections in the pool are closed. Any operations waiting to check out a connection will have an error thrown instead of a connection returned.
       *   - **Clear out server selection queue**: Any operations that are in the process of waiting for a server to be selected will have an error thrown instead of a server returned.
       *   - **Close encryption-related resources**: An internal MongoClient created for communicating with `mongocryptd` or other encryption purposes is closed. (Using this same method of course!)
       *
       * After the close method completes there should be no MongoClient related resources [ref-ed in Node.js' event loop](https://docs.libuv.org/en/v1.x/handle.html#reference-counting).
       * This should allow Node.js to exit gracefully if MongoClient resources were the only active handles in the event loop.
       *
       * @param _force - currently an unused flag that has no effect. Defaults to `false`.
       */
      async close(_force = false) {
        if (this.closeLock) {
          return await this.closeLock;
        }
        try {
          this.closeLock = this._close();
          await this.closeLock;
        } finally {
          this.closeLock = void 0;
        }
      }
      /* @internal */
      async _close() {
        Object.defineProperty(this.s, "hasBeenClosed", {
          value: true,
          enumerable: true,
          configurable: false,
          writable: false
        });
        this.topology?.closeCheckedOutConnections();
        const activeCursorCloses = Array.from(this.s.activeCursors, (cursor) => cursor.close());
        this.s.activeCursors.clear();
        await Promise.all(activeCursorCloses);
        const activeSessionEnds = Array.from(this.s.activeSessions, (session) => session.endSession());
        this.s.activeSessions.clear();
        await Promise.all(activeSessionEnds);
        if (this.topology == null) {
          return;
        }
        const supportsSessions = this.topology.description.type === _1.TopologyType.LoadBalanced || this.topology.description.logicalSessionTimeoutMinutes != null;
        if (supportsSessions) {
          await endSessions(this, this.topology);
        }
        const topology = this.topology;
        this.topology = void 0;
        topology.close();
        const { encrypter } = this.options;
        if (encrypter) {
          await encrypter.close(this);
        }
        async function endSessions(client, { description: topologyDescription }) {
          const selector = (0, server_selection_1.readPreferenceServerSelector)(read_preference_1.ReadPreference.primaryPreferred);
          const serverDescriptions = Array.from(topologyDescription.servers.values());
          const servers = selector(topologyDescription, serverDescriptions, new server_selection_1.DeprioritizedServers());
          if (servers.length !== 0) {
            const endSessions2 = Array.from(client.s.sessionPool.sessions, ({ id }) => id);
            if (endSessions2.length !== 0) {
              try {
                await (0, execute_operation_1.executeOperation)(client, new end_sessions_1.EndSessionsOperation(endSessions2));
              } catch (error51) {
                (0, utils_1.squashError)(error51);
              }
            }
          }
        }
      }
      /**
       * Create a new Db instance sharing the current socket connections.
       *
       * @param dbName - The name of the database we want to use. If not provided, use database name from connection string.
       * @param options - Optional settings for Db construction
       */
      db(dbName, options) {
        options = options ?? {};
        if (!dbName) {
          dbName = this.s.options.dbName;
        }
        const finalOptions = Object.assign({}, this.options, options);
        const db = new db_1.Db(this, dbName, finalOptions);
        return db;
      }
      /**
       * Creates a new MongoClient instance and immediately connects it to MongoDB.
       * This convenience method combines `new MongoClient(url, options)` and `client.connect()` in a single step.
       *
       * Connect can be helpful to detect configuration issues early by validating:
       * - **DNS Resolution**: Verifies that SRV records and hostnames in the connection string resolve DNS entries
       * - **Network Connectivity**: Confirms that host addresses are reachable and ports are open
       * - **TLS Configuration**: Validates SSL/TLS certificates, CA files, and encryption settings are correct
       * - **Authentication**: Verifies that provided credentials are valid
       * - **Server Compatibility**: Ensures the MongoDB server version is supported by this driver version
       * - **Load Balancer Setup**: For load-balanced deployments, confirms the service is properly configured
       *
       * @returns A promise that resolves to the same MongoClient instance once connected
       *
       * @remarks
       * **Connection is Optional:** Calling `connect` is optional since any operation method (`find`, `insertOne`, etc.)
       * will automatically perform these same validation steps if the client is not already connected.
       * However, explicitly calling `connect` can make sense for:
       * - **Fail-fast Error Detection**: Non-transient connection issues (hostname unresolved, port refused connection) are discovered immediately rather than during your first operation
       * - **Predictable Performance**: Eliminates first connection overhead from your first database operation
       *
       * @remarks
       * **Connection Pooling Impact:** Calling `connect` will populate the connection pool with one connection
       * to a server selected by the client's configured `readPreference` (defaults to primary).
       *
       * @remarks
       * **Timeout Behavior:** When using `timeoutMS`, the connection establishment time does not count against
       * the timeout for subsequent operations. This means `connect` runs without a `timeoutMS` limit, while
       * your database operations will still respect the configured timeout. If you need predictable operation
       * timing with `timeoutMS`, call `connect` explicitly before performing operations.
       *
       * @see https://www.mongodb.com/docs/manual/reference/connection-string/
       */
      static async connect(url2, options) {
        const client = new this(url2, options);
        return await client.connect();
      }
      /**
       * Creates a new ClientSession. When using the returned session in an operation
       * a corresponding ServerSession will be created.
       *
       * @remarks
       * A ClientSession instance may only be passed to operations being performed on the same
       * MongoClient it was started from.
       */
      startSession(options) {
        const session = new sessions_1.ClientSession(this, this.s.sessionPool, { explicit: true, ...options }, this.options);
        this.s.activeSessions.add(session);
        session.once("ended", () => {
          this.s.activeSessions.delete(session);
        });
        return session;
      }
      async withSession(optionsOrExecutor, executor) {
        const options = {
          // Always define an owner
          owner: /* @__PURE__ */ Symbol(),
          // If it's an object inherit the options
          ...typeof optionsOrExecutor === "object" ? optionsOrExecutor : {}
        };
        const withSessionCallback = typeof optionsOrExecutor === "function" ? optionsOrExecutor : executor;
        if (withSessionCallback == null) {
          throw new error_1.MongoInvalidArgumentError("Missing required callback parameter");
        }
        const session = this.startSession(options);
        try {
          return await withSessionCallback(session);
        } finally {
          try {
            await session.endSession();
          } catch (error51) {
            (0, utils_1.squashError)(error51);
          }
        }
      }
      /**
       * Create a new Change Stream, watching for new changes (insertions, updates,
       * replacements, deletions, and invalidations) in this cluster. Will ignore all
       * changes to system collections, as well as the local, admin, and config databases.
       *
       * @remarks
       * watch() accepts two generic arguments for distinct use cases:
       * - The first is to provide the schema that may be defined for all the data within the current cluster
       * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument
       *
       * @remarks
       * When `timeoutMS` is configured for a change stream, it will have different behaviour depending
       * on whether the change stream is in iterator mode or emitter mode. In both cases, a change
       * stream will time out if it does not receive a change event within `timeoutMS` of the last change
       * event.
       *
       * Note that if a change stream is consistently timing out when watching a collection, database or
       * client that is being changed, then this may be due to the server timing out before it can finish
       * processing the existing oplog. To address this, restart the change stream with a higher
       * `timeoutMS`.
       *
       * If the change stream times out the initial aggregate operation to establish the change stream on
       * the server, then the client will close the change stream. If the getMore calls to the server
       * time out, then the change stream will be left open, but will throw a MongoOperationTimeoutError
       * when in iterator mode and emit an error event that returns a MongoOperationTimeoutError in
       * emitter mode.
       *
       * To determine whether or not the change stream is still open following a timeout, check the
       * {@link ChangeStream.closed} getter.
       *
       * @example
       * In iterator mode, if a next() call throws a timeout error, it will attempt to resume the change stream.
       * The next call can just be retried after this succeeds.
       * ```ts
       * const changeStream = collection.watch([], { timeoutMS: 100 });
       * try {
       *     await changeStream.next();
       * } catch (e) {
       *     if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
       *       await changeStream.next();
       *     }
       *     throw e;
       * }
       * ```
       *
       * @example
       * In emitter mode, if the change stream goes `timeoutMS` without emitting a change event, it will
       * emit an error event that returns a MongoOperationTimeoutError, but will not close the change
       * stream unless the resume attempt fails. There is no need to re-establish change listeners as
       * this will automatically continue emitting change events once the resume attempt completes.
       *
       * ```ts
       * const changeStream = collection.watch([], { timeoutMS: 100 });
       * changeStream.on('change', console.log);
       * changeStream.on('error', e => {
       *     if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
       *         // do nothing
       *     } else {
       *         changeStream.close();
       *     }
       * });
       * ```
       * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
       * @param options - Optional settings for the command
       * @typeParam TSchema - Type of the data being detected by the change stream
       * @typeParam TChange - Type of the whole change stream document emitted
       */
      watch(pipeline2 = [], options = {}) {
        if (!Array.isArray(pipeline2)) {
          options = pipeline2;
          pipeline2 = [];
        }
        return new change_stream_1.ChangeStream(this, pipeline2, (0, utils_1.resolveOptions)(this, options));
      }
    };
    exports2.MongoClient = MongoClient2;
  }
});

// node_modules/mongodb/lib/change_stream.js
var require_change_stream = __commonJS({
  "node_modules/mongodb/lib/change_stream.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ChangeStream = void 0;
    exports2.filterOutOptions = filterOutOptions;
    var collection_1 = require_collection();
    var constants_1 = require_constants2();
    var abstract_cursor_1 = require_abstract_cursor();
    var change_stream_cursor_1 = require_change_stream_cursor();
    var db_1 = require_db();
    var error_1 = require_error();
    var mongo_client_1 = require_mongo_client();
    var mongo_types_1 = require_mongo_types();
    var server_selection_1 = require_server_selection();
    var timeout_1 = require_timeout();
    var utils_1 = require_utils();
    var CHANGE_DOMAIN_TYPES = {
      COLLECTION: /* @__PURE__ */ Symbol("Collection"),
      DATABASE: /* @__PURE__ */ Symbol("Database"),
      CLUSTER: /* @__PURE__ */ Symbol("Cluster")
    };
    var CHANGE_STREAM_EVENTS = [constants_1.RESUME_TOKEN_CHANGED, constants_1.END, constants_1.CLOSE];
    var NO_RESUME_TOKEN_ERROR = "A change stream document has been received that lacks a resume token (_id).";
    var CHANGESTREAM_CLOSED_ERROR = "ChangeStream is closed";
    var INVALID_STAGE_OPTIONS = buildDisallowedChangeStreamOptions();
    function filterOutOptions(options) {
      return Object.fromEntries(Object.entries(options).filter(([k, _]) => !INVALID_STAGE_OPTIONS.has(k)));
    }
    var ChangeStream = class _ChangeStream extends mongo_types_1.TypedEventEmitter {
      /**
       * An alias for {@link ChangeStream.close|ChangeStream.close()}.
       */
      async [Symbol.asyncDispose]() {
        await this.close();
      }
      static {
        this.RESPONSE = constants_1.RESPONSE;
      }
      static {
        this.MORE = constants_1.MORE;
      }
      static {
        this.INIT = constants_1.INIT;
      }
      static {
        this.CLOSE = constants_1.CLOSE;
      }
      static {
        this.CHANGE = constants_1.CHANGE;
      }
      static {
        this.END = constants_1.END;
      }
      static {
        this.ERROR = constants_1.ERROR;
      }
      static {
        this.RESUME_TOKEN_CHANGED = constants_1.RESUME_TOKEN_CHANGED;
      }
      /**
       * @internal
       *
       * @param parent - The parent object that created this change stream
       * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents
       */
      constructor(parent, pipeline2 = [], options = {}) {
        super();
        this.pipeline = pipeline2;
        this.options = { ...options };
        let serverSelectionTimeoutMS;
        delete this.options.writeConcern;
        if (parent instanceof collection_1.Collection) {
          this.type = CHANGE_DOMAIN_TYPES.COLLECTION;
          serverSelectionTimeoutMS = parent.s.db.client.options.serverSelectionTimeoutMS;
        } else if (parent instanceof db_1.Db) {
          this.type = CHANGE_DOMAIN_TYPES.DATABASE;
          serverSelectionTimeoutMS = parent.client.options.serverSelectionTimeoutMS;
        } else if (parent instanceof mongo_client_1.MongoClient) {
          this.type = CHANGE_DOMAIN_TYPES.CLUSTER;
          serverSelectionTimeoutMS = parent.options.serverSelectionTimeoutMS;
        } else {
          throw new error_1.MongoChangeStreamError("Parent provided to ChangeStream constructor must be an instance of Collection, Db, or MongoClient");
        }
        this.contextOwner = /* @__PURE__ */ Symbol();
        this.parent = parent;
        this.namespace = parent.s.namespace;
        if (!this.options.readPreference && parent.readPreference) {
          this.options.readPreference = parent.readPreference;
        }
        this.cursor = this._createChangeStreamCursor(options);
        this.isClosed = false;
        this.mode = false;
        this.on("newListener", (eventName) => {
          if (eventName === "change" && this.cursor && this.listenerCount("change") === 0) {
            this._streamEvents(this.cursor);
          }
        });
        this.on("removeListener", (eventName) => {
          if (eventName === "change" && this.listenerCount("change") === 0 && this.cursor) {
            this.cursorStream?.removeAllListeners("data");
          }
        });
        if (this.options.timeoutMS != null) {
          this.timeoutContext = new timeout_1.CSOTTimeoutContext({
            timeoutMS: this.options.timeoutMS,
            serverSelectionTimeoutMS
          });
        }
      }
      /** The cached resume token that is used to resume after the most recently returned change. */
      get resumeToken() {
        return this.cursor?.resumeToken;
      }
      /** Returns the currently buffered documents length of the underlying cursor. */
      bufferedCount() {
        return this.cursor?.bufferedCount() ?? 0;
      }
      /** Check if there is any document still available in the Change Stream */
      async hasNext() {
        this._setIsIterator();
        this.timeoutContext?.refresh();
        try {
          while (true) {
            try {
              const hasNext = await this.cursor.hasNext();
              return hasNext;
            } catch (error51) {
              try {
                await this._processErrorIteratorMode(error51, this.cursor.id != null);
              } catch (error52) {
                if (error52 instanceof error_1.MongoOperationTimeoutError && this.cursor.id == null) {
                  throw error52;
                }
                try {
                  await this.close();
                } catch (error53) {
                  (0, utils_1.squashError)(error53);
                }
                throw error52;
              }
            }
          }
        } finally {
          this.timeoutContext?.clear();
        }
      }
      /** Get the next available document from the Change Stream. */
      async next() {
        this._setIsIterator();
        this.timeoutContext?.refresh();
        try {
          while (true) {
            try {
              const change = await this.cursor.next();
              const processedChange = this._processChange(change ?? null);
              return processedChange;
            } catch (error51) {
              try {
                await this._processErrorIteratorMode(error51, this.cursor.id != null);
              } catch (error52) {
                if (error52 instanceof error_1.MongoOperationTimeoutError && this.cursor.id == null) {
                  throw error52;
                }
                try {
                  await this.close();
                } catch (error53) {
                  (0, utils_1.squashError)(error53);
                }
                throw error52;
              }
            }
          }
        } finally {
          this.timeoutContext?.clear();
        }
      }
      /**
       * Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned
       */
      async tryNext() {
        this._setIsIterator();
        this.timeoutContext?.refresh();
        try {
          while (true) {
            try {
              const change = await this.cursor.tryNext();
              if (!change) {
                return null;
              }
              const processedChange = this._processChange(change);
              return processedChange;
            } catch (error51) {
              try {
                await this._processErrorIteratorMode(error51, this.cursor.id != null);
              } catch (error52) {
                if (error52 instanceof error_1.MongoOperationTimeoutError && this.cursor.id == null)
                  throw error52;
                try {
                  await this.close();
                } catch (error53) {
                  (0, utils_1.squashError)(error53);
                }
                throw error52;
              }
            }
          }
        } finally {
          this.timeoutContext?.clear();
        }
      }
      async *[Symbol.asyncIterator]() {
        if (this.closed) {
          return;
        }
        try {
          while (true) {
            yield await this.next();
          }
        } finally {
          try {
            await this.close();
          } catch (error51) {
            (0, utils_1.squashError)(error51);
          }
        }
      }
      /** Is the cursor closed */
      get closed() {
        return this.isClosed || this.cursor.closed;
      }
      /**
       * Frees the internal resources used by the change stream.
       */
      async close() {
        this.timeoutContext?.clear();
        this.timeoutContext = void 0;
        this.isClosed = true;
        const cursor = this.cursor;
        try {
          await cursor.close();
        } finally {
          this._endStream();
        }
      }
      /**
       * Return a modified Readable stream including a possible transform method.
       *
       * NOTE: When using a Stream to process change stream events, the stream will
       * NOT automatically resume in the case a resumable error is encountered.
       *
       * @throws MongoChangeStreamError if the underlying cursor or the change stream is closed
       */
      stream() {
        if (this.closed) {
          throw new error_1.MongoChangeStreamError(CHANGESTREAM_CLOSED_ERROR);
        }
        return this.cursor.stream();
      }
      /** @internal */
      _setIsEmitter() {
        if (this.mode === "iterator") {
          throw new error_1.MongoAPIError("ChangeStream cannot be used as an EventEmitter after being used as an iterator");
        }
        this.mode = "emitter";
      }
      /** @internal */
      _setIsIterator() {
        if (this.mode === "emitter") {
          throw new error_1.MongoAPIError("ChangeStream cannot be used as an iterator after being used as an EventEmitter");
        }
        this.mode = "iterator";
      }
      /**
       * Create a new change stream cursor based on self's configuration
       * @internal
       */
      _createChangeStreamCursor(options) {
        const changeStreamStageOptions = filterOutOptions(options);
        if (this.type === CHANGE_DOMAIN_TYPES.CLUSTER) {
          changeStreamStageOptions.allChangesForCluster = true;
        }
        const pipeline2 = [{ $changeStream: changeStreamStageOptions }, ...this.pipeline];
        const client = this.type === CHANGE_DOMAIN_TYPES.CLUSTER ? this.parent : this.type === CHANGE_DOMAIN_TYPES.DATABASE ? this.parent.client : this.type === CHANGE_DOMAIN_TYPES.COLLECTION ? this.parent.client : null;
        if (client == null) {
          throw new error_1.MongoRuntimeError(`Changestream type should only be one of cluster, database, collection. Found ${this.type.toString()}`);
        }
        const changeStreamCursor = new change_stream_cursor_1.ChangeStreamCursor(client, this.namespace, pipeline2, {
          ...options,
          timeoutContext: this.timeoutContext ? new abstract_cursor_1.CursorTimeoutContext(this.timeoutContext, this.contextOwner) : void 0
        });
        for (const event of CHANGE_STREAM_EVENTS) {
          changeStreamCursor.on(event, (e2) => this.emit(event, e2));
        }
        if (this.listenerCount(_ChangeStream.CHANGE) > 0) {
          this._streamEvents(changeStreamCursor);
        }
        return changeStreamCursor;
      }
      /** @internal */
      _closeEmitterModeWithError(error51) {
        this.emit(_ChangeStream.ERROR, error51);
        this.close().then(void 0, utils_1.squashError);
      }
      /** @internal */
      _streamEvents(cursor) {
        this._setIsEmitter();
        const stream = this.cursorStream ?? cursor.stream();
        this.cursorStream = stream;
        stream.on("data", (change) => {
          try {
            const processedChange = this._processChange(change);
            this.emit(_ChangeStream.CHANGE, processedChange);
          } catch (error51) {
            this.emit(_ChangeStream.ERROR, error51);
          }
          this.timeoutContext?.refresh();
        });
        stream.on("error", (error51) => this._processErrorStreamMode(error51, this.cursor.id != null));
      }
      /** @internal */
      _endStream() {
        this.cursorStream?.removeAllListeners("data");
        this.cursorStream?.removeAllListeners("close");
        this.cursorStream?.removeAllListeners("end");
        this.cursorStream?.destroy();
        this.cursorStream = void 0;
      }
      /** @internal */
      _processChange(change) {
        if (this.isClosed) {
          throw new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR);
        }
        if (change == null) {
          throw new error_1.MongoRuntimeError(CHANGESTREAM_CLOSED_ERROR);
        }
        if (change && !change._id) {
          throw new error_1.MongoChangeStreamError(NO_RESUME_TOKEN_ERROR);
        }
        this.cursor.cacheResumeToken(change._id);
        this.options.startAtOperationTime = void 0;
        return change;
      }
      /** @internal */
      _processErrorStreamMode(changeStreamError, cursorInitialized) {
        if (this.isClosed)
          return;
        if (cursorInitialized && ((0, error_1.isResumableError)(changeStreamError, this.cursor.maxWireVersion) || changeStreamError instanceof error_1.MongoOperationTimeoutError)) {
          this._endStream();
          this.cursor.close().then(() => this._resume(changeStreamError), (e2) => {
            (0, utils_1.squashError)(e2);
            return this._resume(changeStreamError);
          }).then(() => {
            if (changeStreamError instanceof error_1.MongoOperationTimeoutError)
              this.emit(_ChangeStream.ERROR, changeStreamError);
          }, () => this._closeEmitterModeWithError(changeStreamError));
        } else {
          this._closeEmitterModeWithError(changeStreamError);
        }
      }
      /** @internal */
      async _processErrorIteratorMode(changeStreamError, cursorInitialized) {
        if (this.isClosed) {
          throw new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR);
        }
        if (cursorInitialized && ((0, error_1.isResumableError)(changeStreamError, this.cursor.maxWireVersion) || changeStreamError instanceof error_1.MongoOperationTimeoutError)) {
          try {
            await this.cursor.close();
          } catch (error51) {
            (0, utils_1.squashError)(error51);
          }
          await this._resume(changeStreamError);
          if (changeStreamError instanceof error_1.MongoOperationTimeoutError)
            throw changeStreamError;
        } else {
          try {
            await this.close();
          } catch (error51) {
            (0, utils_1.squashError)(error51);
          }
          throw changeStreamError;
        }
      }
      async _resume(changeStreamError) {
        this.timeoutContext?.refresh();
        const topology = (0, utils_1.getTopology)(this.parent);
        try {
          await topology.selectServer(this.cursor.readPreference, {
            operationName: "reconnect topology in change stream",
            timeoutContext: this.timeoutContext,
            deprioritizedServers: new server_selection_1.DeprioritizedServers()
          });
          this.cursor = this._createChangeStreamCursor(this.cursor.resumeOptions);
        } catch {
          await this.close();
          throw changeStreamError;
        }
      }
    };
    exports2.ChangeStream = ChangeStream;
    function buildDisallowedChangeStreamOptions() {
      const denyList = {
        allowDiskUse: "",
        authdb: "",
        batchSize: "",
        bsonRegExp: "",
        bypassDocumentValidation: "",
        bypassPinningCheck: "",
        checkKeys: "",
        collation: "",
        comment: "",
        cursor: "",
        dbName: "",
        enableUtf8Validation: "",
        explain: "",
        fieldsAsRaw: "",
        hint: "",
        ignoreUndefined: "",
        let: "",
        maxAwaitTimeMS: "",
        maxTimeMS: "",
        omitMaxTimeMS: "",
        out: "",
        promoteBuffers: "",
        promoteLongs: "",
        promoteValues: "",
        raw: "",
        rawData: "",
        readConcern: "",
        readPreference: "",
        serializeFunctions: "",
        session: "",
        timeoutContext: "",
        timeoutMS: "",
        timeoutMode: "",
        useBigInt64: "",
        willRetryWrite: "",
        writeConcern: ""
      };
      return new Set(Object.keys(denyList));
    }
  }
});

// node_modules/mongodb/lib/gridfs/download.js
var require_download = __commonJS({
  "node_modules/mongodb/lib/gridfs/download.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.GridFSBucketReadStream = void 0;
    var stream_1 = require("stream");
    var bson_1 = require_bson2();
    var abstract_cursor_1 = require_abstract_cursor();
    var error_1 = require_error();
    var timeout_1 = require_timeout();
    var GridFSBucketReadStream = class extends stream_1.Readable {
      static {
        this.FILE = "file";
      }
      /**
       * @param chunks - Handle for chunks collection
       * @param files - Handle for files collection
       * @param readPreference - The read preference to use
       * @param filter - The filter to use to find the file document
       * @internal
       */
      constructor(chunks, files, readPreference, filter, options) {
        super({ emitClose: true });
        this.s = {
          bytesToTrim: 0,
          bytesToSkip: 0,
          bytesRead: 0,
          chunks,
          expected: 0,
          files,
          filter,
          init: false,
          expectedEnd: 0,
          options: {
            start: 0,
            end: 0,
            ...options
          },
          readPreference,
          timeoutContext: options?.timeoutMS != null ? new timeout_1.CSOTTimeoutContext({ timeoutMS: options.timeoutMS, serverSelectionTimeoutMS: 0 }) : void 0
        };
      }
      /**
       * Reads from the cursor and pushes to the stream.
       * Private Impl, do not call directly
       * @internal
       */
      _read() {
        if (this.destroyed)
          return;
        waitForFile(this, () => doRead(this));
      }
      /**
       * Sets the 0-based offset in bytes to start streaming from. Throws
       * an error if this stream has entered flowing mode
       * (e.g. if you've already called `on('data')`)
       *
       * @param start - 0-based offset in bytes to start streaming from
       */
      start(start = 0) {
        throwIfInitialized(this);
        this.s.options.start = start;
        return this;
      }
      /**
       * Sets the 0-based offset in bytes to start streaming from. Throws
       * an error if this stream has entered flowing mode
       * (e.g. if you've already called `on('data')`)
       *
       * @param end - Offset in bytes to stop reading at
       */
      end(end = 0) {
        throwIfInitialized(this);
        this.s.options.end = end;
        return this;
      }
      /**
       * Marks this stream as aborted (will never push another `data` event)
       * and kills the underlying cursor. Will emit the 'end' event, and then
       * the 'close' event once the cursor is successfully killed.
       */
      async abort() {
        this.push(null);
        this.destroy();
        const remainingTimeMS = this.s.timeoutContext?.getRemainingTimeMSOrThrow();
        await this.s.cursor?.close({ timeoutMS: remainingTimeMS });
      }
    };
    exports2.GridFSBucketReadStream = GridFSBucketReadStream;
    function throwIfInitialized(stream) {
      if (stream.s.init) {
        throw new error_1.MongoGridFSStreamError("Options cannot be changed after the stream is initialized");
      }
    }
    function doRead(stream) {
      if (stream.destroyed)
        return;
      if (!stream.s.cursor)
        return;
      if (!stream.s.file)
        return;
      const handleReadResult = (doc) => {
        if (stream.destroyed)
          return;
        if (!doc) {
          stream.push(null);
          stream.s.cursor?.close().then(void 0, (error51) => stream.destroy(error51));
          return;
        }
        if (!stream.s.file)
          return;
        const bytesRemaining = stream.s.file.length - stream.s.bytesRead;
        const expectedN = stream.s.expected++;
        const expectedLength = Math.min(stream.s.file.chunkSize, bytesRemaining);
        if (doc.n > expectedN) {
          return stream.destroy(new error_1.MongoGridFSChunkError(`ChunkIsMissing: Got unexpected n: ${doc.n}, expected: ${expectedN}`));
        }
        if (doc.n < expectedN) {
          return stream.destroy(new error_1.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}, expected: ${expectedN}`));
        }
        let buf = bson_1.ByteUtils.isUint8Array(doc.data) ? doc.data : doc.data.buffer;
        if (buf.byteLength !== expectedLength) {
          if (bytesRemaining <= 0) {
            return stream.destroy(new error_1.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}, expected file length ${stream.s.file.length} bytes but already read ${stream.s.bytesRead} bytes`));
          }
          return stream.destroy(new error_1.MongoGridFSChunkError(`ChunkIsWrongSize: Got unexpected length: ${buf.byteLength}, expected: ${expectedLength}`));
        }
        stream.s.bytesRead += buf.byteLength;
        if (buf.byteLength === 0) {
          return stream.push(null);
        }
        let sliceStart = null;
        let sliceEnd = null;
        if (stream.s.bytesToSkip != null) {
          sliceStart = stream.s.bytesToSkip;
          stream.s.bytesToSkip = 0;
        }
        const atEndOfStream = expectedN === stream.s.expectedEnd - 1;
        const bytesLeftToRead = stream.s.options.end - stream.s.bytesToSkip;
        if (atEndOfStream && stream.s.bytesToTrim != null) {
          sliceEnd = stream.s.file.chunkSize - stream.s.bytesToTrim;
        } else if (stream.s.options.end && bytesLeftToRead < doc.data.byteLength) {
          sliceEnd = bytesLeftToRead;
        }
        if (sliceStart != null || sliceEnd != null) {
          buf = buf.slice(sliceStart || 0, sliceEnd || buf.byteLength);
        }
        stream.push(buf);
        return;
      };
      stream.s.cursor.next().then(handleReadResult, (error51) => {
        if (stream.destroyed)
          return;
        stream.destroy(error51);
      });
    }
    function init(stream) {
      const findOneOptions = {};
      if (stream.s.readPreference) {
        findOneOptions.readPreference = stream.s.readPreference;
      }
      if (stream.s.options && stream.s.options.sort) {
        findOneOptions.sort = stream.s.options.sort;
      }
      if (stream.s.options && stream.s.options.skip) {
        findOneOptions.skip = stream.s.options.skip;
      }
      const handleReadResult = (doc) => {
        if (stream.destroyed)
          return;
        if (!doc) {
          const identifier = stream.s.filter._id ? stream.s.filter._id.toString() : stream.s.filter.filename;
          const errmsg = `FileNotFound: file ${identifier} was not found`;
          const err = new error_1.MongoRuntimeError(errmsg);
          err.code = "ENOENT";
          return stream.destroy(err);
        }
        if (doc.length <= 0) {
          stream.push(null);
          return;
        }
        if (stream.destroyed) {
          stream.destroy();
          return;
        }
        try {
          stream.s.bytesToSkip = handleStartOption(stream, doc, stream.s.options);
        } catch (error51) {
          return stream.destroy(error51);
        }
        const filter = { files_id: doc._id };
        if (stream.s.options && stream.s.options.start != null) {
          const skip = Math.floor(stream.s.options.start / doc.chunkSize);
          if (skip > 0) {
            filter["n"] = { $gte: skip };
          }
        }
        let remainingTimeMS2;
        try {
          remainingTimeMS2 = stream.s.timeoutContext?.getRemainingTimeMSOrThrow(`Download timed out after ${stream.s.timeoutContext?.timeoutMS}ms`);
        } catch (error51) {
          return stream.destroy(error51);
        }
        stream.s.cursor = stream.s.chunks.find(filter, {
          timeoutMode: stream.s.options.timeoutMS != null ? abstract_cursor_1.CursorTimeoutMode.LIFETIME : void 0,
          timeoutMS: remainingTimeMS2
        }).sort({ n: 1 });
        if (stream.s.readPreference) {
          stream.s.cursor.withReadPreference(stream.s.readPreference);
        }
        stream.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize);
        stream.s.file = doc;
        try {
          stream.s.bytesToTrim = handleEndOption(stream, doc, stream.s.cursor, stream.s.options);
        } catch (error51) {
          return stream.destroy(error51);
        }
        stream.emit(GridFSBucketReadStream.FILE, doc);
        return;
      };
      let remainingTimeMS;
      try {
        remainingTimeMS = stream.s.timeoutContext?.getRemainingTimeMSOrThrow(`Download timed out after ${stream.s.timeoutContext?.timeoutMS}ms`);
      } catch (error51) {
        if (!stream.destroyed)
          stream.destroy(error51);
        return;
      }
      findOneOptions.timeoutMS = remainingTimeMS;
      stream.s.files.findOne(stream.s.filter, findOneOptions).then(handleReadResult, (error51) => {
        if (stream.destroyed)
          return;
        stream.destroy(error51);
      });
    }
    function waitForFile(stream, callback) {
      if (stream.s.file) {
        return callback();
      }
      if (!stream.s.init) {
        init(stream);
        stream.s.init = true;
      }
      stream.once("file", () => {
        callback();
      });
    }
    function handleStartOption(stream, doc, options) {
      if (options && options.start != null) {
        if (options.start > doc.length) {
          throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be more than the length of the file (${doc.length})`);
        }
        if (options.start < 0) {
          throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be negative`);
        }
        if (options.end != null && options.end < options.start) {
          throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be greater than stream end (${options.end})`);
        }
        stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize;
        stream.s.expected = Math.floor(options.start / doc.chunkSize);
        return options.start - stream.s.bytesRead;
      }
      throw new error_1.MongoInvalidArgumentError("Start option must be defined");
    }
    function handleEndOption(stream, doc, cursor, options) {
      if (options && options.end != null) {
        if (options.end > doc.length) {
          throw new error_1.MongoInvalidArgumentError(`Stream end (${options.end}) must not be more than the length of the file (${doc.length})`);
        }
        if (options.start == null || options.start < 0) {
          throw new error_1.MongoInvalidArgumentError(`Stream end (${options.end}) must not be negative`);
        }
        const start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0;
        cursor.limit(Math.ceil(options.end / doc.chunkSize) - start);
        stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize);
        return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end;
      }
      throw new error_1.MongoInvalidArgumentError("End option must be defined");
    }
  }
});

// node_modules/mongodb/lib/gridfs/upload.js
var require_upload = __commonJS({
  "node_modules/mongodb/lib/gridfs/upload.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.GridFSBucketWriteStream = void 0;
    var stream_1 = require("stream");
    var bson_1 = require_bson2();
    var abstract_cursor_1 = require_abstract_cursor();
    var error_1 = require_error();
    var timeout_1 = require_timeout();
    var utils_1 = require_utils();
    var write_concern_1 = require_write_concern();
    var GridFSBucketWriteStream = class extends stream_1.Writable {
      /**
       * @param bucket - Handle for this stream's corresponding bucket
       * @param filename - The value of the 'filename' key in the files doc
       * @param options - Optional settings.
       * @internal
       */
      constructor(bucket, filename, options) {
        super();
        this.gridFSFile = null;
        options = options ?? {};
        this.bucket = bucket;
        this.chunks = bucket.s._chunksCollection;
        this.filename = filename;
        this.files = bucket.s._filesCollection;
        this.options = options;
        this.writeConcern = write_concern_1.WriteConcern.fromOptions(options) || bucket.s.options.writeConcern;
        this.done = false;
        this.id = options.id ? options.id : new bson_1.ObjectId();
        this.chunkSizeBytes = options.chunkSizeBytes || this.bucket.s.options.chunkSizeBytes;
        this.bufToStore = bson_1.ByteUtils.allocate(this.chunkSizeBytes);
        this.length = 0;
        this.n = 0;
        this.pos = 0;
        this.state = {
          streamEnd: false,
          outstandingRequests: 0,
          errored: false,
          aborted: false
        };
        if (options.timeoutMS != null)
          this.timeoutContext = new timeout_1.CSOTTimeoutContext({
            timeoutMS: options.timeoutMS,
            serverSelectionTimeoutMS: (0, utils_1.resolveTimeoutOptions)(this.bucket.s.db.client, {}).serverSelectionTimeoutMS
          });
      }
      /**
       * @internal
       *
       * The stream is considered constructed when the indexes are done being created
       */
      _construct(callback) {
        if (!this.bucket.s.calledOpenUploadStream) {
          this.bucket.s.calledOpenUploadStream = true;
          checkIndexes(this).then(() => {
            this.bucket.s.checkedIndexes = true;
            this.bucket.emit("index");
            callback();
          }, (error51) => {
            if (error51 instanceof error_1.MongoOperationTimeoutError) {
              return handleError(this, error51, callback);
            }
            (0, utils_1.squashError)(error51);
            callback();
          });
        } else {
          return queueMicrotask(callback);
        }
      }
      /**
       * @internal
       * Write a buffer to the stream.
       *
       * @param chunk - Buffer to write
       * @param encoding - Optional encoding for the buffer
       * @param callback - Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush.
       */
      _write(chunk, encoding, callback) {
        doWrite(this, chunk, encoding, callback);
      }
      /** @internal */
      _final(callback) {
        if (this.state.streamEnd) {
          return queueMicrotask(callback);
        }
        this.state.streamEnd = true;
        writeRemnant(this, callback);
      }
      /**
       * Places this write stream into an aborted state (all future writes fail)
       * and deletes all chunks that have already been written.
       */
      async abort() {
        if (this.state.streamEnd) {
          throw new error_1.MongoAPIError("Cannot abort a stream that has already completed");
        }
        if (this.state.aborted) {
          throw new error_1.MongoAPIError("Cannot call abort() on a stream twice");
        }
        this.state.aborted = true;
        const remainingTimeMS = this.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${this.timeoutContext?.timeoutMS}ms`);
        await this.chunks.deleteMany({ files_id: this.id }, { timeoutMS: remainingTimeMS });
      }
    };
    exports2.GridFSBucketWriteStream = GridFSBucketWriteStream;
    function handleError(stream, error51, callback) {
      if (stream.state.errored) {
        queueMicrotask(callback);
        return;
      }
      stream.state.errored = true;
      queueMicrotask(() => callback(error51));
    }
    function createChunkDoc(filesId, n, data) {
      return {
        _id: new bson_1.ObjectId(),
        files_id: filesId,
        n,
        data
      };
    }
    async function checkChunksIndex(stream) {
      const index = { files_id: 1, n: 1 };
      let remainingTimeMS;
      remainingTimeMS = stream.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`);
      let indexes;
      try {
        indexes = await stream.chunks.listIndexes({
          timeoutMode: remainingTimeMS != null ? abstract_cursor_1.CursorTimeoutMode.LIFETIME : void 0,
          timeoutMS: remainingTimeMS
        }).toArray();
      } catch (error51) {
        if (error51 instanceof error_1.MongoError && error51.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) {
          indexes = [];
        } else {
          throw error51;
        }
      }
      const hasChunksIndex = !!indexes.find((index2) => {
        const keys = Object.keys(index2.key);
        if (keys.length === 2 && index2.key.files_id === 1 && index2.key.n === 1) {
          return true;
        }
        return false;
      });
      if (!hasChunksIndex) {
        remainingTimeMS = stream.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`);
        await stream.chunks.createIndex(index, {
          ...stream.writeConcern,
          background: true,
          unique: true,
          timeoutMS: remainingTimeMS
        });
      }
    }
    function checkDone(stream, callback) {
      if (stream.done) {
        return queueMicrotask(callback);
      }
      if (stream.state.streamEnd && stream.state.outstandingRequests === 0 && !stream.state.errored) {
        stream.done = true;
        const gridFSFile = createFilesDoc(stream.id, stream.length, stream.chunkSizeBytes, stream.filename, stream.options.metadata);
        if (isAborted2(stream, callback)) {
          return;
        }
        const remainingTimeMS = stream.timeoutContext?.remainingTimeMS;
        if (remainingTimeMS != null && remainingTimeMS <= 0) {
          return handleError(stream, new error_1.MongoOperationTimeoutError(`Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`), callback);
        }
        stream.files.insertOne(gridFSFile, { writeConcern: stream.writeConcern, timeoutMS: remainingTimeMS }).then(() => {
          stream.gridFSFile = gridFSFile;
          callback();
        }, (error51) => {
          return handleError(stream, error51, callback);
        });
        return;
      }
      queueMicrotask(callback);
    }
    async function checkIndexes(stream) {
      let remainingTimeMS = stream.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`);
      const doc = await stream.files.findOne({}, {
        projection: { _id: 1 },
        timeoutMS: remainingTimeMS
      });
      if (doc != null) {
        return;
      }
      const index = { filename: 1, uploadDate: 1 };
      let indexes;
      remainingTimeMS = stream.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`);
      const listIndexesOptions = {
        timeoutMode: remainingTimeMS != null ? abstract_cursor_1.CursorTimeoutMode.LIFETIME : void 0,
        timeoutMS: remainingTimeMS
      };
      try {
        indexes = await stream.files.listIndexes(listIndexesOptions).toArray();
      } catch (error51) {
        if (error51 instanceof error_1.MongoError && error51.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) {
          indexes = [];
        } else {
          throw error51;
        }
      }
      const hasFileIndex = !!indexes.find((index2) => {
        const keys = Object.keys(index2.key);
        if (keys.length === 2 && index2.key.filename === 1 && index2.key.uploadDate === 1) {
          return true;
        }
        return false;
      });
      if (!hasFileIndex) {
        remainingTimeMS = stream.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`);
        await stream.files.createIndex(index, { background: false, timeoutMS: remainingTimeMS });
      }
      await checkChunksIndex(stream);
    }
    function createFilesDoc(_id, length, chunkSize, filename, metadata) {
      const ret = {
        _id,
        length,
        chunkSize,
        uploadDate: /* @__PURE__ */ new Date(),
        filename
      };
      if (metadata) {
        ret.metadata = metadata;
      }
      return ret;
    }
    function doWrite(stream, chunk, encoding, callback) {
      if (isAborted2(stream, callback)) {
        return;
      }
      const inputBuf = typeof chunk === "string" ? bson_1.ByteUtils.fromUTF8(chunk) : bson_1.ByteUtils.toLocalBufferType(chunk);
      stream.length += inputBuf.length;
      if (stream.pos + inputBuf.length < stream.chunkSizeBytes) {
        bson_1.ByteUtils.copy(inputBuf, stream.bufToStore, stream.pos);
        stream.pos += inputBuf.length;
        queueMicrotask(callback);
        return;
      }
      let inputBufRemaining = inputBuf.length;
      let spaceRemaining = stream.chunkSizeBytes - stream.pos;
      let numToCopy = Math.min(spaceRemaining, inputBuf.length);
      let outstandingRequests = 0;
      while (inputBufRemaining > 0) {
        const inputBufPos = inputBuf.length - inputBufRemaining;
        bson_1.ByteUtils.copy(inputBuf, stream.bufToStore, stream.pos, inputBufPos, inputBufPos + numToCopy);
        stream.pos += numToCopy;
        spaceRemaining -= numToCopy;
        let doc;
        if (spaceRemaining === 0) {
          doc = createChunkDoc(stream.id, stream.n, new Uint8Array(stream.bufToStore));
          const remainingTimeMS = stream.timeoutContext?.remainingTimeMS;
          if (remainingTimeMS != null && remainingTimeMS <= 0) {
            return handleError(stream, new error_1.MongoOperationTimeoutError(`Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`), callback);
          }
          ++stream.state.outstandingRequests;
          ++outstandingRequests;
          if (isAborted2(stream, callback)) {
            return;
          }
          stream.chunks.insertOne(doc, { writeConcern: stream.writeConcern, timeoutMS: remainingTimeMS }).then(() => {
            --stream.state.outstandingRequests;
            --outstandingRequests;
            if (!outstandingRequests) {
              checkDone(stream, callback);
            }
          }, (error51) => {
            return handleError(stream, error51, callback);
          });
          spaceRemaining = stream.chunkSizeBytes;
          stream.pos = 0;
          ++stream.n;
        }
        inputBufRemaining -= numToCopy;
        numToCopy = Math.min(spaceRemaining, inputBufRemaining);
      }
    }
    function writeRemnant(stream, callback) {
      if (stream.pos === 0) {
        return checkDone(stream, callback);
      }
      const remnant = bson_1.ByteUtils.allocate(stream.pos);
      bson_1.ByteUtils.copy(stream.bufToStore, remnant, 0, 0, stream.pos);
      const doc = createChunkDoc(stream.id, stream.n, remnant);
      if (isAborted2(stream, callback)) {
        return;
      }
      const remainingTimeMS = stream.timeoutContext?.remainingTimeMS;
      if (remainingTimeMS != null && remainingTimeMS <= 0) {
        return handleError(stream, new error_1.MongoOperationTimeoutError(`Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`), callback);
      }
      ++stream.state.outstandingRequests;
      stream.chunks.insertOne(doc, { writeConcern: stream.writeConcern, timeoutMS: remainingTimeMS }).then(() => {
        --stream.state.outstandingRequests;
        checkDone(stream, callback);
      }, (error51) => {
        return handleError(stream, error51, callback);
      });
    }
    function isAborted2(stream, callback) {
      if (stream.state.aborted) {
        queueMicrotask(() => callback(new error_1.MongoAPIError("Stream has been aborted")));
        return true;
      }
      return false;
    }
  }
});

// node_modules/mongodb/lib/gridfs/index.js
var require_gridfs = __commonJS({
  "node_modules/mongodb/lib/gridfs/index.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.GridFSBucket = void 0;
    var error_1 = require_error();
    var mongo_types_1 = require_mongo_types();
    var timeout_1 = require_timeout();
    var utils_1 = require_utils();
    var write_concern_1 = require_write_concern();
    var download_1 = require_download();
    var upload_1 = require_upload();
    var DEFAULT_GRIDFS_BUCKET_OPTIONS = {
      bucketName: "fs",
      chunkSizeBytes: 255 * 1024
    };
    var GridFSBucket = class extends mongo_types_1.TypedEventEmitter {
      static {
        this.INDEX = "index";
      }
      constructor(db, options) {
        super();
        this.on("error", utils_1.noop);
        this.setMaxListeners(0);
        const privateOptions = (0, utils_1.resolveOptions)(db, {
          ...DEFAULT_GRIDFS_BUCKET_OPTIONS,
          ...options,
          writeConcern: write_concern_1.WriteConcern.fromOptions(options)
        });
        this.s = {
          db,
          options: privateOptions,
          _chunksCollection: db.collection(privateOptions.bucketName + ".chunks"),
          _filesCollection: db.collection(privateOptions.bucketName + ".files"),
          checkedIndexes: false,
          calledOpenUploadStream: false
        };
      }
      /**
       * Returns a writable stream (GridFSBucketWriteStream) for writing
       * buffers to GridFS. The stream's 'id' property contains the resulting
       * file's id.
       *
       * @param filename - The value of the 'filename' key in the files doc
       * @param options - Optional settings.
       */
      openUploadStream(filename, options) {
        return new upload_1.GridFSBucketWriteStream(this, filename, {
          timeoutMS: this.s.options.timeoutMS,
          ...options
        });
      }
      /**
       * Returns a writable stream (GridFSBucketWriteStream) for writing
       * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting
       * file's id.
       */
      openUploadStreamWithId(id, filename, options) {
        return new upload_1.GridFSBucketWriteStream(this, filename, {
          timeoutMS: this.s.options.timeoutMS,
          ...options,
          id
        });
      }
      /** Returns a readable stream (GridFSBucketReadStream) for streaming file data from GridFS. */
      openDownloadStream(id, options) {
        return new download_1.GridFSBucketReadStream(this.s._chunksCollection, this.s._filesCollection, this.s.options.readPreference, { _id: id }, { timeoutMS: this.s.options.timeoutMS, ...options });
      }
      /**
       * Deletes a file with the given id
       *
       * @param id - The id of the file doc
       */
      async delete(id, options) {
        const { timeoutMS } = (0, utils_1.resolveOptions)(this.s.db, options);
        let timeoutContext = void 0;
        if (timeoutMS) {
          timeoutContext = new timeout_1.CSOTTimeoutContext({
            timeoutMS,
            serverSelectionTimeoutMS: this.s.db.client.s.options.serverSelectionTimeoutMS
          });
        }
        const { deletedCount } = await this.s._filesCollection.deleteOne({ _id: id }, { timeoutMS: timeoutContext?.remainingTimeMS });
        const remainingTimeMS = timeoutContext?.remainingTimeMS;
        if (remainingTimeMS != null && remainingTimeMS <= 0)
          throw new error_1.MongoOperationTimeoutError(`Timed out after ${timeoutMS}ms`);
        await this.s._chunksCollection.deleteMany({ files_id: id }, { timeoutMS: remainingTimeMS });
        if (deletedCount === 0) {
          throw new error_1.MongoRuntimeError(`File not found for id ${id}`);
        }
      }
      /** Convenience wrapper around find on the files collection */
      find(filter = {}, options = {}) {
        return this.s._filesCollection.find(filter, options);
      }
      /**
       * Returns a readable stream (GridFSBucketReadStream) for streaming the
       * file with the given name from GridFS. If there are multiple files with
       * the same name, this will stream the most recent file with the given name
       * (as determined by the `uploadDate` field). You can set the `revision`
       * option to change this behavior.
       */
      openDownloadStreamByName(filename, options) {
        let sort = { uploadDate: -1 };
        let skip = void 0;
        if (options && options.revision != null) {
          if (options.revision >= 0) {
            sort = { uploadDate: 1 };
            skip = options.revision;
          } else {
            skip = -options.revision - 1;
          }
        }
        return new download_1.GridFSBucketReadStream(this.s._chunksCollection, this.s._filesCollection, this.s.options.readPreference, { filename }, { timeoutMS: this.s.options.timeoutMS, ...options, sort, skip });
      }
      /**
       * Renames the file with the given _id to the given string
       *
       * @param id - the id of the file to rename
       * @param filename - new name for the file
       */
      async rename(id, filename, options) {
        const filter = { _id: id };
        const update = { $set: { filename } };
        const { matchedCount } = await this.s._filesCollection.updateOne(filter, update, options);
        if (matchedCount === 0) {
          throw new error_1.MongoRuntimeError(`File with id ${id} not found`);
        }
      }
      /** Removes this bucket's files collection, followed by its chunks collection. */
      async drop(options) {
        const { timeoutMS } = (0, utils_1.resolveOptions)(this.s.db, options);
        let timeoutContext = void 0;
        if (timeoutMS) {
          timeoutContext = new timeout_1.CSOTTimeoutContext({
            timeoutMS,
            serverSelectionTimeoutMS: this.s.db.client.s.options.serverSelectionTimeoutMS
          });
        }
        if (timeoutContext) {
          await this.s._filesCollection.drop({ timeoutMS: timeoutContext.remainingTimeMS });
          const remainingTimeMS = timeoutContext.getRemainingTimeMSOrThrow(`Timed out after ${timeoutMS}ms`);
          await this.s._chunksCollection.drop({ timeoutMS: remainingTimeMS });
        } else {
          await this.s._filesCollection.drop();
          await this.s._chunksCollection.drop();
        }
      }
    };
    exports2.GridFSBucket = GridFSBucket;
  }
});

// node_modules/mongodb/lib/index.js
var require_lib3 = __commonJS({
  "node_modules/mongodb/lib/index.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MongoRuntimeError = exports2.MongoParseError = exports2.MongoOperationTimeoutError = exports2.MongoOIDCError = exports2.MongoNotConnectedError = exports2.MongoNetworkTimeoutError = exports2.MongoNetworkError = exports2.MongoMissingDependencyError = exports2.MongoMissingCredentialsError = exports2.MongoKerberosError = exports2.MongoInvalidArgumentError = exports2.MongoGridFSStreamError = exports2.MongoGridFSChunkError = exports2.MongoGCPError = exports2.MongoExpiredSessionError = exports2.MongoError = exports2.MongoDriverError = exports2.MongoDecompressionError = exports2.MongoCursorInUseError = exports2.MongoCursorExhaustedError = exports2.MongoCompatibilityError = exports2.MongoClientClosedError = exports2.MongoClientBulkWriteExecutionError = exports2.MongoClientBulkWriteError = exports2.MongoClientBulkWriteCursorError = exports2.MongoChangeStreamError = exports2.MongoBatchReExecutionError = exports2.MongoAzureError = exports2.MongoAWSError = exports2.MongoAPIError = exports2.ExplainableCursor = exports2.ChangeStreamCursor = exports2.ClientEncryption = exports2.MongoBulkWriteError = exports2.UUID = exports2.Timestamp = exports2.ObjectId = exports2.MinKey = exports2.MaxKey = exports2.Long = exports2.Int32 = exports2.Double = exports2.Decimal128 = exports2.DBRef = exports2.Code = exports2.BSONType = exports2.BSONSymbol = exports2.BSONRegExp = exports2.Binary = exports2.BSON = void 0;
    exports2.CommandStartedEvent = exports2.CommandFailedEvent = exports2.WriteConcern = exports2.ReadPreference = exports2.ReadConcern = exports2.TopologyType = exports2.ServerType = exports2.ReadPreferenceMode = exports2.ReadConcernLevel = exports2.ProfilingLevel = exports2.ReturnDocument = exports2.SeverityLevel = exports2.MongoLoggableComponent = exports2.ServerApiVersion = exports2.ExplainVerbosity = exports2.MongoErrorLabel = exports2.CursorTimeoutMode = exports2.CURSOR_FLAGS = exports2.Compressor = exports2.AuthMechanism = exports2.GSSAPICanonicalizationValue = exports2.AutoEncryptionLoggerLevel = exports2.BatchType = exports2.UnorderedBulkOperation = exports2.OrderedBulkOperation = exports2.MongoClient = exports2.ListIndexesCursor = exports2.ListCollectionsCursor = exports2.GridFSBucketWriteStream = exports2.GridFSBucketReadStream = exports2.GridFSBucket = exports2.FindCursor = exports2.Db = exports2.Collection = exports2.ClientSession = exports2.ChangeStream = exports2.CancellationToken = exports2.AggregationCursor = exports2.Admin = exports2.AbstractCursor = exports2.MongoWriteConcernError = exports2.MongoUnexpectedServerResponseError = exports2.MongoTransactionError = exports2.MongoTopologyClosedError = exports2.MongoTailableCursorError = exports2.MongoSystemError = exports2.MongoStalePrimaryError = exports2.MongoServerSelectionError = exports2.MongoServerError = exports2.MongoServerClosedError = void 0;
    exports2.MongoClientAuthProviders = exports2.MongoCryptKMSRequestNetworkTimeoutError = exports2.MongoCryptInvalidArgumentError = exports2.MongoCryptError = exports2.MongoCryptCreateEncryptedCollectionError = exports2.MongoCryptCreateDataKeyError = exports2.MongoCryptAzureKMSRequestError = exports2.SrvPollingEvent = exports2.WaitingForSuitableServerEvent = exports2.ServerSelectionSucceededEvent = exports2.ServerSelectionStartedEvent = exports2.ServerSelectionFailedEvent = exports2.ServerSelectionEvent = exports2.TopologyOpeningEvent = exports2.TopologyDescriptionChangedEvent = exports2.TopologyClosedEvent = exports2.ServerOpeningEvent = exports2.ServerHeartbeatSucceededEvent = exports2.ServerHeartbeatStartedEvent = exports2.ServerHeartbeatFailedEvent = exports2.ServerDescriptionChangedEvent = exports2.ServerClosedEvent = exports2.ConnectionReadyEvent = exports2.ConnectionPoolReadyEvent = exports2.ConnectionPoolMonitoringEvent = exports2.ConnectionPoolCreatedEvent = exports2.ConnectionPoolClosedEvent = exports2.ConnectionPoolClearedEvent = exports2.ConnectionCreatedEvent = exports2.ConnectionClosedEvent = exports2.ConnectionCheckOutStartedEvent = exports2.ConnectionCheckOutFailedEvent = exports2.ConnectionCheckedOutEvent = exports2.ConnectionCheckedInEvent = exports2.CommandSucceededEvent = void 0;
    var admin_1 = require_admin();
    Object.defineProperty(exports2, "Admin", { enumerable: true, get: function() {
      return admin_1.Admin;
    } });
    var ordered_1 = require_ordered();
    Object.defineProperty(exports2, "OrderedBulkOperation", { enumerable: true, get: function() {
      return ordered_1.OrderedBulkOperation;
    } });
    var unordered_1 = require_unordered();
    Object.defineProperty(exports2, "UnorderedBulkOperation", { enumerable: true, get: function() {
      return unordered_1.UnorderedBulkOperation;
    } });
    var change_stream_1 = require_change_stream();
    Object.defineProperty(exports2, "ChangeStream", { enumerable: true, get: function() {
      return change_stream_1.ChangeStream;
    } });
    var collection_1 = require_collection();
    Object.defineProperty(exports2, "Collection", { enumerable: true, get: function() {
      return collection_1.Collection;
    } });
    var abstract_cursor_1 = require_abstract_cursor();
    Object.defineProperty(exports2, "AbstractCursor", { enumerable: true, get: function() {
      return abstract_cursor_1.AbstractCursor;
    } });
    var aggregation_cursor_1 = require_aggregation_cursor();
    Object.defineProperty(exports2, "AggregationCursor", { enumerable: true, get: function() {
      return aggregation_cursor_1.AggregationCursor;
    } });
    var find_cursor_1 = require_find_cursor();
    Object.defineProperty(exports2, "FindCursor", { enumerable: true, get: function() {
      return find_cursor_1.FindCursor;
    } });
    var list_collections_cursor_1 = require_list_collections_cursor();
    Object.defineProperty(exports2, "ListCollectionsCursor", { enumerable: true, get: function() {
      return list_collections_cursor_1.ListCollectionsCursor;
    } });
    var list_indexes_cursor_1 = require_list_indexes_cursor();
    Object.defineProperty(exports2, "ListIndexesCursor", { enumerable: true, get: function() {
      return list_indexes_cursor_1.ListIndexesCursor;
    } });
    var db_1 = require_db();
    Object.defineProperty(exports2, "Db", { enumerable: true, get: function() {
      return db_1.Db;
    } });
    var gridfs_1 = require_gridfs();
    Object.defineProperty(exports2, "GridFSBucket", { enumerable: true, get: function() {
      return gridfs_1.GridFSBucket;
    } });
    var download_1 = require_download();
    Object.defineProperty(exports2, "GridFSBucketReadStream", { enumerable: true, get: function() {
      return download_1.GridFSBucketReadStream;
    } });
    var upload_1 = require_upload();
    Object.defineProperty(exports2, "GridFSBucketWriteStream", { enumerable: true, get: function() {
      return upload_1.GridFSBucketWriteStream;
    } });
    var mongo_client_1 = require_mongo_client();
    Object.defineProperty(exports2, "MongoClient", { enumerable: true, get: function() {
      return mongo_client_1.MongoClient;
    } });
    var mongo_types_1 = require_mongo_types();
    Object.defineProperty(exports2, "CancellationToken", { enumerable: true, get: function() {
      return mongo_types_1.CancellationToken;
    } });
    var sessions_1 = require_sessions();
    Object.defineProperty(exports2, "ClientSession", { enumerable: true, get: function() {
      return sessions_1.ClientSession;
    } });
    var bson_1 = require_bson2();
    Object.defineProperty(exports2, "BSON", { enumerable: true, get: function() {
      return bson_1.BSON;
    } });
    var bson_2 = require_bson2();
    Object.defineProperty(exports2, "Binary", { enumerable: true, get: function() {
      return bson_2.Binary;
    } });
    Object.defineProperty(exports2, "BSONRegExp", { enumerable: true, get: function() {
      return bson_2.BSONRegExp;
    } });
    Object.defineProperty(exports2, "BSONSymbol", { enumerable: true, get: function() {
      return bson_2.BSONSymbol;
    } });
    Object.defineProperty(exports2, "BSONType", { enumerable: true, get: function() {
      return bson_2.BSONType;
    } });
    Object.defineProperty(exports2, "Code", { enumerable: true, get: function() {
      return bson_2.Code;
    } });
    Object.defineProperty(exports2, "DBRef", { enumerable: true, get: function() {
      return bson_2.DBRef;
    } });
    Object.defineProperty(exports2, "Decimal128", { enumerable: true, get: function() {
      return bson_2.Decimal128;
    } });
    Object.defineProperty(exports2, "Double", { enumerable: true, get: function() {
      return bson_2.Double;
    } });
    Object.defineProperty(exports2, "Int32", { enumerable: true, get: function() {
      return bson_2.Int32;
    } });
    Object.defineProperty(exports2, "Long", { enumerable: true, get: function() {
      return bson_2.Long;
    } });
    Object.defineProperty(exports2, "MaxKey", { enumerable: true, get: function() {
      return bson_2.MaxKey;
    } });
    Object.defineProperty(exports2, "MinKey", { enumerable: true, get: function() {
      return bson_2.MinKey;
    } });
    Object.defineProperty(exports2, "ObjectId", { enumerable: true, get: function() {
      return bson_2.ObjectId;
    } });
    Object.defineProperty(exports2, "Timestamp", { enumerable: true, get: function() {
      return bson_2.Timestamp;
    } });
    Object.defineProperty(exports2, "UUID", { enumerable: true, get: function() {
      return bson_2.UUID;
    } });
    var common_1 = require_common2();
    Object.defineProperty(exports2, "MongoBulkWriteError", { enumerable: true, get: function() {
      return common_1.MongoBulkWriteError;
    } });
    var client_encryption_1 = require_client_encryption();
    Object.defineProperty(exports2, "ClientEncryption", { enumerable: true, get: function() {
      return client_encryption_1.ClientEncryption;
    } });
    var change_stream_cursor_1 = require_change_stream_cursor();
    Object.defineProperty(exports2, "ChangeStreamCursor", { enumerable: true, get: function() {
      return change_stream_cursor_1.ChangeStreamCursor;
    } });
    var explainable_cursor_1 = require_explainable_cursor();
    Object.defineProperty(exports2, "ExplainableCursor", { enumerable: true, get: function() {
      return explainable_cursor_1.ExplainableCursor;
    } });
    var error_1 = require_error();
    Object.defineProperty(exports2, "MongoAPIError", { enumerable: true, get: function() {
      return error_1.MongoAPIError;
    } });
    Object.defineProperty(exports2, "MongoAWSError", { enumerable: true, get: function() {
      return error_1.MongoAWSError;
    } });
    Object.defineProperty(exports2, "MongoAzureError", { enumerable: true, get: function() {
      return error_1.MongoAzureError;
    } });
    Object.defineProperty(exports2, "MongoBatchReExecutionError", { enumerable: true, get: function() {
      return error_1.MongoBatchReExecutionError;
    } });
    Object.defineProperty(exports2, "MongoChangeStreamError", { enumerable: true, get: function() {
      return error_1.MongoChangeStreamError;
    } });
    Object.defineProperty(exports2, "MongoClientBulkWriteCursorError", { enumerable: true, get: function() {
      return error_1.MongoClientBulkWriteCursorError;
    } });
    Object.defineProperty(exports2, "MongoClientBulkWriteError", { enumerable: true, get: function() {
      return error_1.MongoClientBulkWriteError;
    } });
    Object.defineProperty(exports2, "MongoClientBulkWriteExecutionError", { enumerable: true, get: function() {
      return error_1.MongoClientBulkWriteExecutionError;
    } });
    Object.defineProperty(exports2, "MongoClientClosedError", { enumerable: true, get: function() {
      return error_1.MongoClientClosedError;
    } });
    Object.defineProperty(exports2, "MongoCompatibilityError", { enumerable: true, get: function() {
      return error_1.MongoCompatibilityError;
    } });
    Object.defineProperty(exports2, "MongoCursorExhaustedError", { enumerable: true, get: function() {
      return error_1.MongoCursorExhaustedError;
    } });
    Object.defineProperty(exports2, "MongoCursorInUseError", { enumerable: true, get: function() {
      return error_1.MongoCursorInUseError;
    } });
    Object.defineProperty(exports2, "MongoDecompressionError", { enumerable: true, get: function() {
      return error_1.MongoDecompressionError;
    } });
    Object.defineProperty(exports2, "MongoDriverError", { enumerable: true, get: function() {
      return error_1.MongoDriverError;
    } });
    Object.defineProperty(exports2, "MongoError", { enumerable: true, get: function() {
      return error_1.MongoError;
    } });
    Object.defineProperty(exports2, "MongoExpiredSessionError", { enumerable: true, get: function() {
      return error_1.MongoExpiredSessionError;
    } });
    Object.defineProperty(exports2, "MongoGCPError", { enumerable: true, get: function() {
      return error_1.MongoGCPError;
    } });
    Object.defineProperty(exports2, "MongoGridFSChunkError", { enumerable: true, get: function() {
      return error_1.MongoGridFSChunkError;
    } });
    Object.defineProperty(exports2, "MongoGridFSStreamError", { enumerable: true, get: function() {
      return error_1.MongoGridFSStreamError;
    } });
    Object.defineProperty(exports2, "MongoInvalidArgumentError", { enumerable: true, get: function() {
      return error_1.MongoInvalidArgumentError;
    } });
    Object.defineProperty(exports2, "MongoKerberosError", { enumerable: true, get: function() {
      return error_1.MongoKerberosError;
    } });
    Object.defineProperty(exports2, "MongoMissingCredentialsError", { enumerable: true, get: function() {
      return error_1.MongoMissingCredentialsError;
    } });
    Object.defineProperty(exports2, "MongoMissingDependencyError", { enumerable: true, get: function() {
      return error_1.MongoMissingDependencyError;
    } });
    Object.defineProperty(exports2, "MongoNetworkError", { enumerable: true, get: function() {
      return error_1.MongoNetworkError;
    } });
    Object.defineProperty(exports2, "MongoNetworkTimeoutError", { enumerable: true, get: function() {
      return error_1.MongoNetworkTimeoutError;
    } });
    Object.defineProperty(exports2, "MongoNotConnectedError", { enumerable: true, get: function() {
      return error_1.MongoNotConnectedError;
    } });
    Object.defineProperty(exports2, "MongoOIDCError", { enumerable: true, get: function() {
      return error_1.MongoOIDCError;
    } });
    Object.defineProperty(exports2, "MongoOperationTimeoutError", { enumerable: true, get: function() {
      return error_1.MongoOperationTimeoutError;
    } });
    Object.defineProperty(exports2, "MongoParseError", { enumerable: true, get: function() {
      return error_1.MongoParseError;
    } });
    Object.defineProperty(exports2, "MongoRuntimeError", { enumerable: true, get: function() {
      return error_1.MongoRuntimeError;
    } });
    Object.defineProperty(exports2, "MongoServerClosedError", { enumerable: true, get: function() {
      return error_1.MongoServerClosedError;
    } });
    Object.defineProperty(exports2, "MongoServerError", { enumerable: true, get: function() {
      return error_1.MongoServerError;
    } });
    Object.defineProperty(exports2, "MongoServerSelectionError", { enumerable: true, get: function() {
      return error_1.MongoServerSelectionError;
    } });
    Object.defineProperty(exports2, "MongoStalePrimaryError", { enumerable: true, get: function() {
      return error_1.MongoStalePrimaryError;
    } });
    Object.defineProperty(exports2, "MongoSystemError", { enumerable: true, get: function() {
      return error_1.MongoSystemError;
    } });
    Object.defineProperty(exports2, "MongoTailableCursorError", { enumerable: true, get: function() {
      return error_1.MongoTailableCursorError;
    } });
    Object.defineProperty(exports2, "MongoTopologyClosedError", { enumerable: true, get: function() {
      return error_1.MongoTopologyClosedError;
    } });
    Object.defineProperty(exports2, "MongoTransactionError", { enumerable: true, get: function() {
      return error_1.MongoTransactionError;
    } });
    Object.defineProperty(exports2, "MongoUnexpectedServerResponseError", { enumerable: true, get: function() {
      return error_1.MongoUnexpectedServerResponseError;
    } });
    Object.defineProperty(exports2, "MongoWriteConcernError", { enumerable: true, get: function() {
      return error_1.MongoWriteConcernError;
    } });
    var common_2 = require_common2();
    Object.defineProperty(exports2, "BatchType", { enumerable: true, get: function() {
      return common_2.BatchType;
    } });
    var auto_encrypter_1 = require_auto_encrypter();
    Object.defineProperty(exports2, "AutoEncryptionLoggerLevel", { enumerable: true, get: function() {
      return auto_encrypter_1.AutoEncryptionLoggerLevel;
    } });
    var gssapi_1 = require_gssapi();
    Object.defineProperty(exports2, "GSSAPICanonicalizationValue", { enumerable: true, get: function() {
      return gssapi_1.GSSAPICanonicalizationValue;
    } });
    var providers_1 = require_providers();
    Object.defineProperty(exports2, "AuthMechanism", { enumerable: true, get: function() {
      return providers_1.AuthMechanism;
    } });
    var compression_1 = require_compression();
    Object.defineProperty(exports2, "Compressor", { enumerable: true, get: function() {
      return compression_1.Compressor;
    } });
    var abstract_cursor_2 = require_abstract_cursor();
    Object.defineProperty(exports2, "CURSOR_FLAGS", { enumerable: true, get: function() {
      return abstract_cursor_2.CURSOR_FLAGS;
    } });
    Object.defineProperty(exports2, "CursorTimeoutMode", { enumerable: true, get: function() {
      return abstract_cursor_2.CursorTimeoutMode;
    } });
    var error_2 = require_error();
    Object.defineProperty(exports2, "MongoErrorLabel", { enumerable: true, get: function() {
      return error_2.MongoErrorLabel;
    } });
    var explain_1 = require_explain();
    Object.defineProperty(exports2, "ExplainVerbosity", { enumerable: true, get: function() {
      return explain_1.ExplainVerbosity;
    } });
    var mongo_client_2 = require_mongo_client();
    Object.defineProperty(exports2, "ServerApiVersion", { enumerable: true, get: function() {
      return mongo_client_2.ServerApiVersion;
    } });
    var mongo_logger_1 = require_mongo_logger();
    Object.defineProperty(exports2, "MongoLoggableComponent", { enumerable: true, get: function() {
      return mongo_logger_1.MongoLoggableComponent;
    } });
    Object.defineProperty(exports2, "SeverityLevel", { enumerable: true, get: function() {
      return mongo_logger_1.SeverityLevel;
    } });
    var find_and_modify_1 = require_find_and_modify();
    Object.defineProperty(exports2, "ReturnDocument", { enumerable: true, get: function() {
      return find_and_modify_1.ReturnDocument;
    } });
    var set_profiling_level_1 = require_set_profiling_level();
    Object.defineProperty(exports2, "ProfilingLevel", { enumerable: true, get: function() {
      return set_profiling_level_1.ProfilingLevel;
    } });
    var read_concern_1 = require_read_concern();
    Object.defineProperty(exports2, "ReadConcernLevel", { enumerable: true, get: function() {
      return read_concern_1.ReadConcernLevel;
    } });
    var read_preference_1 = require_read_preference();
    Object.defineProperty(exports2, "ReadPreferenceMode", { enumerable: true, get: function() {
      return read_preference_1.ReadPreferenceMode;
    } });
    var common_3 = require_common();
    Object.defineProperty(exports2, "ServerType", { enumerable: true, get: function() {
      return common_3.ServerType;
    } });
    Object.defineProperty(exports2, "TopologyType", { enumerable: true, get: function() {
      return common_3.TopologyType;
    } });
    var read_concern_2 = require_read_concern();
    Object.defineProperty(exports2, "ReadConcern", { enumerable: true, get: function() {
      return read_concern_2.ReadConcern;
    } });
    var read_preference_2 = require_read_preference();
    Object.defineProperty(exports2, "ReadPreference", { enumerable: true, get: function() {
      return read_preference_2.ReadPreference;
    } });
    var write_concern_1 = require_write_concern();
    Object.defineProperty(exports2, "WriteConcern", { enumerable: true, get: function() {
      return write_concern_1.WriteConcern;
    } });
    var command_monitoring_events_1 = require_command_monitoring_events();
    Object.defineProperty(exports2, "CommandFailedEvent", { enumerable: true, get: function() {
      return command_monitoring_events_1.CommandFailedEvent;
    } });
    Object.defineProperty(exports2, "CommandStartedEvent", { enumerable: true, get: function() {
      return command_monitoring_events_1.CommandStartedEvent;
    } });
    Object.defineProperty(exports2, "CommandSucceededEvent", { enumerable: true, get: function() {
      return command_monitoring_events_1.CommandSucceededEvent;
    } });
    var connection_pool_events_1 = require_connection_pool_events();
    Object.defineProperty(exports2, "ConnectionCheckedInEvent", { enumerable: true, get: function() {
      return connection_pool_events_1.ConnectionCheckedInEvent;
    } });
    Object.defineProperty(exports2, "ConnectionCheckedOutEvent", { enumerable: true, get: function() {
      return connection_pool_events_1.ConnectionCheckedOutEvent;
    } });
    Object.defineProperty(exports2, "ConnectionCheckOutFailedEvent", { enumerable: true, get: function() {
      return connection_pool_events_1.ConnectionCheckOutFailedEvent;
    } });
    Object.defineProperty(exports2, "ConnectionCheckOutStartedEvent", { enumerable: true, get: function() {
      return connection_pool_events_1.ConnectionCheckOutStartedEvent;
    } });
    Object.defineProperty(exports2, "ConnectionClosedEvent", { enumerable: true, get: function() {
      return connection_pool_events_1.ConnectionClosedEvent;
    } });
    Object.defineProperty(exports2, "ConnectionCreatedEvent", { enumerable: true, get: function() {
      return connection_pool_events_1.ConnectionCreatedEvent;
    } });
    Object.defineProperty(exports2, "ConnectionPoolClearedEvent", { enumerable: true, get: function() {
      return connection_pool_events_1.ConnectionPoolClearedEvent;
    } });
    Object.defineProperty(exports2, "ConnectionPoolClosedEvent", { enumerable: true, get: function() {
      return connection_pool_events_1.ConnectionPoolClosedEvent;
    } });
    Object.defineProperty(exports2, "ConnectionPoolCreatedEvent", { enumerable: true, get: function() {
      return connection_pool_events_1.ConnectionPoolCreatedEvent;
    } });
    Object.defineProperty(exports2, "ConnectionPoolMonitoringEvent", { enumerable: true, get: function() {
      return connection_pool_events_1.ConnectionPoolMonitoringEvent;
    } });
    Object.defineProperty(exports2, "ConnectionPoolReadyEvent", { enumerable: true, get: function() {
      return connection_pool_events_1.ConnectionPoolReadyEvent;
    } });
    Object.defineProperty(exports2, "ConnectionReadyEvent", { enumerable: true, get: function() {
      return connection_pool_events_1.ConnectionReadyEvent;
    } });
    var events_1 = require_events();
    Object.defineProperty(exports2, "ServerClosedEvent", { enumerable: true, get: function() {
      return events_1.ServerClosedEvent;
    } });
    Object.defineProperty(exports2, "ServerDescriptionChangedEvent", { enumerable: true, get: function() {
      return events_1.ServerDescriptionChangedEvent;
    } });
    Object.defineProperty(exports2, "ServerHeartbeatFailedEvent", { enumerable: true, get: function() {
      return events_1.ServerHeartbeatFailedEvent;
    } });
    Object.defineProperty(exports2, "ServerHeartbeatStartedEvent", { enumerable: true, get: function() {
      return events_1.ServerHeartbeatStartedEvent;
    } });
    Object.defineProperty(exports2, "ServerHeartbeatSucceededEvent", { enumerable: true, get: function() {
      return events_1.ServerHeartbeatSucceededEvent;
    } });
    Object.defineProperty(exports2, "ServerOpeningEvent", { enumerable: true, get: function() {
      return events_1.ServerOpeningEvent;
    } });
    Object.defineProperty(exports2, "TopologyClosedEvent", { enumerable: true, get: function() {
      return events_1.TopologyClosedEvent;
    } });
    Object.defineProperty(exports2, "TopologyDescriptionChangedEvent", { enumerable: true, get: function() {
      return events_1.TopologyDescriptionChangedEvent;
    } });
    Object.defineProperty(exports2, "TopologyOpeningEvent", { enumerable: true, get: function() {
      return events_1.TopologyOpeningEvent;
    } });
    var server_selection_events_1 = require_server_selection_events();
    Object.defineProperty(exports2, "ServerSelectionEvent", { enumerable: true, get: function() {
      return server_selection_events_1.ServerSelectionEvent;
    } });
    Object.defineProperty(exports2, "ServerSelectionFailedEvent", { enumerable: true, get: function() {
      return server_selection_events_1.ServerSelectionFailedEvent;
    } });
    Object.defineProperty(exports2, "ServerSelectionStartedEvent", { enumerable: true, get: function() {
      return server_selection_events_1.ServerSelectionStartedEvent;
    } });
    Object.defineProperty(exports2, "ServerSelectionSucceededEvent", { enumerable: true, get: function() {
      return server_selection_events_1.ServerSelectionSucceededEvent;
    } });
    Object.defineProperty(exports2, "WaitingForSuitableServerEvent", { enumerable: true, get: function() {
      return server_selection_events_1.WaitingForSuitableServerEvent;
    } });
    var srv_polling_1 = require_srv_polling();
    Object.defineProperty(exports2, "SrvPollingEvent", { enumerable: true, get: function() {
      return srv_polling_1.SrvPollingEvent;
    } });
    var errors_1 = require_errors();
    Object.defineProperty(exports2, "MongoCryptAzureKMSRequestError", { enumerable: true, get: function() {
      return errors_1.MongoCryptAzureKMSRequestError;
    } });
    Object.defineProperty(exports2, "MongoCryptCreateDataKeyError", { enumerable: true, get: function() {
      return errors_1.MongoCryptCreateDataKeyError;
    } });
    Object.defineProperty(exports2, "MongoCryptCreateEncryptedCollectionError", { enumerable: true, get: function() {
      return errors_1.MongoCryptCreateEncryptedCollectionError;
    } });
    Object.defineProperty(exports2, "MongoCryptError", { enumerable: true, get: function() {
      return errors_1.MongoCryptError;
    } });
    Object.defineProperty(exports2, "MongoCryptInvalidArgumentError", { enumerable: true, get: function() {
      return errors_1.MongoCryptInvalidArgumentError;
    } });
    Object.defineProperty(exports2, "MongoCryptKMSRequestNetworkTimeoutError", { enumerable: true, get: function() {
      return errors_1.MongoCryptKMSRequestNetworkTimeoutError;
    } });
    var mongo_client_auth_providers_1 = require_mongo_client_auth_providers();
    Object.defineProperty(exports2, "MongoClientAuthProviders", { enumerable: true, get: function() {
      return mongo_client_auth_providers_1.MongoClientAuthProviders;
    } });
  }
});

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

// node_modules/googleapis-common/node_modules/gaxios/build/cjs/src/util.cjs
var require_util2 = __commonJS({
  "node_modules/googleapis-common/node_modules/gaxios/build/cjs/src/util.cjs"(exports2, module2) {
    "use strict";
    var pkg = require_package3();
    module2.exports = { pkg };
  }
});

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

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

// node_modules/googleapis-common/node_modules/gaxios/build/cjs/src/interceptor.js
var require_interceptor2 = __commonJS({
  "node_modules/googleapis-common/node_modules/gaxios/build/cjs/src/interceptor.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.GaxiosInterceptorManager = void 0;
    var GaxiosInterceptorManager = class extends Set {
    };
    exports2.GaxiosInterceptorManager = GaxiosInterceptorManager;
  }
});

// node_modules/googleapis-common/node_modules/gaxios/build/cjs/src/gaxios.js
var require_gaxios2 = __commonJS({
  "node_modules/googleapis-common/node_modules/gaxios/build/cjs/src/gaxios.js"(exports2) {
    "use strict";
    var __importDefault = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    var _a3;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Gaxios = void 0;
    var extend_1 = __importDefault(require_extend());
    var https_1 = require("https");
    var common_js_1 = require_common5();
    var retry_js_1 = require_retry2();
    var stream_1 = require("stream");
    var interceptor_js_1 = require_interceptor2();
    var randomUUID = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
    var HTTP_STATUS_NO_CONTENT = 204;
    var Gaxios = class {
      agentCache = /* @__PURE__ */ new Map();
      /**
       * Default HTTP options that will be used for every HTTP request.
       */
      defaults;
      /**
       * Interceptors
       */
      interceptors;
      /**
       * The Gaxios class is responsible for making HTTP requests.
       * @param defaults The default set of options to be used for this instance.
       */
      constructor(defaults) {
        this.defaults = defaults || {};
        this.interceptors = {
          request: new interceptor_js_1.GaxiosInterceptorManager(),
          response: new interceptor_js_1.GaxiosInterceptorManager()
        };
      }
      /**
       * A {@link fetch `fetch`} compliant API for {@link Gaxios}.
       *
       * @remarks
       *
       * This is useful as a drop-in replacement for `fetch` API usage.
       *
       * @example
       *
       * ```ts
       * const gaxios = new Gaxios();
       * const myFetch: typeof fetch = (...args) => gaxios.fetch(...args);
       * await myFetch('https://example.com');
       * ```
       *
       * @param args `fetch` API or `Gaxios#request` parameters
       * @returns the {@link Response} with Gaxios-added properties
       */
      fetch(...args) {
        const input = args[0];
        const init = args[1];
        let url2 = void 0;
        const headers = new Headers();
        if (typeof input === "string") {
          url2 = new URL(input);
        } else if (input instanceof URL) {
          url2 = input;
        } else if (input && input.url) {
          url2 = new URL(input.url);
        }
        if (input && typeof input === "object" && "headers" in input) {
          _a3.mergeHeaders(headers, input.headers);
        }
        if (init) {
          _a3.mergeHeaders(headers, new Headers(init.headers));
        }
        if (typeof input === "object" && !(input instanceof URL)) {
          return this.request({ ...init, ...input, headers, url: url2 });
        } else {
          return this.request({ ...init, headers, url: url2 });
        }
      }
      /**
       * Perform an HTTP request with the given options.
       * @param opts Set of HTTP options that will be used for this HTTP request.
       */
      async request(opts = {}) {
        let prepared = await this.#prepareRequest(opts);
        prepared = await this.#applyRequestInterceptors(prepared);
        return this.#applyResponseInterceptors(this._request(prepared));
      }
      async _defaultAdapter(config2) {
        const fetchImpl = config2.fetchImplementation || this.defaults.fetchImplementation || await _a3.#getFetch();
        const preparedOpts = { ...config2 };
        delete preparedOpts.data;
        const res = await fetchImpl(config2.url, preparedOpts);
        const data = await this.getResponseData(config2, res);
        if (!Object.getOwnPropertyDescriptor(res, "data")?.configurable) {
          Object.defineProperties(res, {
            data: {
              configurable: true,
              writable: true,
              enumerable: true,
              value: data
            }
          });
        }
        return Object.assign(res, { config: config2, data });
      }
      /**
       * Internal, retryable version of the `request` method.
       * @param opts Set of HTTP options that will be used for this HTTP request.
       */
      async _request(opts) {
        try {
          let translatedResponse;
          if (opts.adapter) {
            translatedResponse = await opts.adapter(opts, this._defaultAdapter.bind(this));
          } else {
            translatedResponse = await this._defaultAdapter(opts);
          }
          if (!opts.validateStatus(translatedResponse.status)) {
            if (opts.responseType === "stream") {
              const response = [];
              for await (const chunk of translatedResponse.data) {
                response.push(chunk);
              }
              translatedResponse.data = response.toString();
            }
            const errorInfo = common_js_1.GaxiosError.extractAPIErrorFromResponse(translatedResponse, `Request failed with status code ${translatedResponse.status}`);
            throw new common_js_1.GaxiosError(errorInfo?.message, opts, translatedResponse, errorInfo);
          }
          return translatedResponse;
        } catch (e2) {
          let err;
          if (e2 instanceof common_js_1.GaxiosError) {
            err = e2;
          } else if (e2 instanceof Error) {
            err = new common_js_1.GaxiosError(e2.message, opts, void 0, e2);
          } else {
            err = new common_js_1.GaxiosError("Unexpected Gaxios Error", opts, void 0, e2);
          }
          const { shouldRetry, config: config2 } = await (0, retry_js_1.getRetryConfig)(err);
          if (shouldRetry && config2) {
            err.config.retryConfig.currentRetryAttempt = config2.retryConfig.currentRetryAttempt;
            opts.retryConfig = err.config?.retryConfig;
            this.#appendTimeoutToSignal(opts);
            return this._request(opts);
          }
          if (opts.errorRedactor) {
            opts.errorRedactor(err);
          }
          throw err;
        }
      }
      async getResponseData(opts, res) {
        if (res.status === HTTP_STATUS_NO_CONTENT) {
          return "";
        }
        if (opts.maxContentLength && res.headers.has("content-length") && opts.maxContentLength < Number.parseInt(res.headers?.get("content-length") || "")) {
          throw new common_js_1.GaxiosError("Response's `Content-Length` is over the limit.", opts, Object.assign(res, { config: opts }));
        }
        switch (opts.responseType) {
          case "stream":
            return res.body;
          case "json": {
            const data = await res.text();
            try {
              return JSON.parse(data);
            } catch {
              return data;
            }
          }
          case "arraybuffer":
            return res.arrayBuffer();
          case "blob":
            return res.blob();
          case "text":
            return res.text();
          default:
            return this.getResponseDataFromContentType(res);
        }
      }
      #urlMayUseProxy(url2, noProxy = []) {
        const candidate = new URL(url2);
        const noProxyList = [...noProxy];
        const noProxyEnvList = (process.env.NO_PROXY ?? process.env.no_proxy)?.split(",") || [];
        for (const rule of noProxyEnvList) {
          noProxyList.push(rule.trim());
        }
        for (const rule of noProxyList) {
          if (rule instanceof RegExp) {
            if (rule.test(candidate.toString())) {
              return false;
            }
          } else if (rule instanceof URL) {
            if (rule.origin === candidate.origin) {
              return false;
            }
          } else if (rule.startsWith("*.") || rule.startsWith(".")) {
            const cleanedRule = rule.replace(/^\*\./, ".");
            if (candidate.hostname.endsWith(cleanedRule)) {
              return false;
            }
          } else if (rule === candidate.origin || rule === candidate.hostname || rule === candidate.href) {
            return false;
          }
        }
        return true;
      }
      /**
       * Applies the request interceptors. The request interceptors are applied after the
       * call to prepareRequest is completed.
       *
       * @param {GaxiosOptionsPrepared} options The current set of options.
       *
       * @returns {Promise<GaxiosOptionsPrepared>} Promise that resolves to the set of options or response after interceptors are applied.
       */
      async #applyRequestInterceptors(options) {
        let promiseChain = Promise.resolve(options);
        for (const interceptor of this.interceptors.request.values()) {
          if (interceptor) {
            promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected);
          }
        }
        return promiseChain;
      }
      /**
       * Applies the response interceptors. The response interceptors are applied after the
       * call to request is made.
       *
       * @param {GaxiosOptionsPrepared} options The current set of options.
       *
       * @returns {Promise<GaxiosOptionsPrepared>} Promise that resolves to the set of options or response after interceptors are applied.
       */
      async #applyResponseInterceptors(response) {
        let promiseChain = Promise.resolve(response);
        for (const interceptor of this.interceptors.response.values()) {
          if (interceptor) {
            promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected);
          }
        }
        return promiseChain;
      }
      /**
       * Validates the options, merges them with defaults, and prepare request.
       *
       * @param options The original options passed from the client.
       * @returns Prepared options, ready to make a request
       */
      async #prepareRequest(options) {
        const preparedHeaders = new Headers(this.defaults.headers);
        _a3.mergeHeaders(preparedHeaders, options.headers);
        const opts = (0, extend_1.default)(true, {}, this.defaults, options);
        if (!opts.url) {
          throw new Error("URL is required.");
        }
        if (opts.baseURL) {
          opts.url = new URL(opts.url, opts.baseURL);
        }
        opts.url = new URL(opts.url);
        if (opts.params) {
          if (opts.paramsSerializer) {
            let additionalQueryParams = opts.paramsSerializer(opts.params);
            if (additionalQueryParams.startsWith("?")) {
              additionalQueryParams = additionalQueryParams.slice(1);
            }
            const prefix = opts.url.toString().includes("?") ? "&" : "?";
            opts.url = opts.url + prefix + additionalQueryParams;
          } else {
            const url2 = opts.url instanceof URL ? opts.url : new URL(opts.url);
            for (const [key, value] of new URLSearchParams(opts.params)) {
              url2.searchParams.append(key, value);
            }
            opts.url = url2;
          }
        }
        if (typeof options.maxContentLength === "number") {
          opts.size = options.maxContentLength;
        }
        if (typeof options.maxRedirects === "number") {
          opts.follow = options.maxRedirects;
        }
        const shouldDirectlyPassData = typeof opts.data === "string" || opts.data instanceof ArrayBuffer || opts.data instanceof Blob || // Node 18 does not have a global `File` object
        globalThis.File && opts.data instanceof File || opts.data instanceof FormData || opts.data instanceof stream_1.Readable || opts.data instanceof ReadableStream || opts.data instanceof String || opts.data instanceof URLSearchParams || ArrayBuffer.isView(opts.data) || // `Buffer` (Node.js), `DataView`, `TypedArray`
        /**
         * @deprecated `node-fetch` or another third-party's request types
         */
        ["Blob", "File", "FormData"].includes(opts.data?.constructor?.name || "");
        if (opts.multipart?.length) {
          const boundary = await randomUUID();
          preparedHeaders.set("content-type", `multipart/related; boundary=${boundary}`);
          opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary));
        } else if (shouldDirectlyPassData) {
          opts.body = opts.data;
        } else if (typeof opts.data === "object") {
          if (preparedHeaders.get("Content-Type") === "application/x-www-form-urlencoded") {
            opts.body = opts.paramsSerializer ? opts.paramsSerializer(opts.data) : new URLSearchParams(opts.data);
          } else {
            if (!preparedHeaders.has("content-type")) {
              preparedHeaders.set("content-type", "application/json");
            }
            opts.body = JSON.stringify(opts.data);
          }
        } else if (opts.data) {
          opts.body = opts.data;
        }
        opts.validateStatus = opts.validateStatus || this.validateStatus;
        opts.responseType = opts.responseType || "unknown";
        if (!preparedHeaders.has("accept") && opts.responseType === "json") {
          preparedHeaders.set("accept", "application/json");
        }
        const proxy = opts.proxy || process?.env?.HTTPS_PROXY || process?.env?.https_proxy || process?.env?.HTTP_PROXY || process?.env?.http_proxy;
        if (opts.agent) {
        } else if (proxy && this.#urlMayUseProxy(opts.url, opts.noProxy)) {
          const HttpsProxyAgent = await _a3.#getProxyAgent();
          if (this.agentCache.has(proxy)) {
            opts.agent = this.agentCache.get(proxy);
          } else {
            opts.agent = new HttpsProxyAgent(proxy, {
              cert: opts.cert,
              key: opts.key
            });
            this.agentCache.set(proxy, opts.agent);
          }
        } else if (opts.cert && opts.key) {
          if (this.agentCache.has(opts.key)) {
            opts.agent = this.agentCache.get(opts.key);
          } else {
            opts.agent = new https_1.Agent({
              cert: opts.cert,
              key: opts.key
            });
            this.agentCache.set(opts.key, opts.agent);
          }
        }
        if (typeof opts.errorRedactor !== "function" && opts.errorRedactor !== false) {
          opts.errorRedactor = common_js_1.defaultErrorRedactor;
        }
        if (opts.body && !("duplex" in opts)) {
          opts.duplex = "half";
        }
        this.#appendTimeoutToSignal(opts);
        return Object.assign(opts, {
          headers: preparedHeaders,
          url: opts.url instanceof URL ? opts.url : new URL(opts.url)
        });
      }
      #appendTimeoutToSignal(opts) {
        if (opts.timeout) {
          const timeoutSignal = AbortSignal.timeout(opts.timeout);
          if (opts.signal && !opts.signal.aborted) {
            opts.signal = AbortSignal.any([opts.signal, timeoutSignal]);
          } else {
            opts.signal = timeoutSignal;
          }
        }
      }
      /**
       * By default, throw for any non-2xx status code
       * @param status status code from the HTTP response
       */
      validateStatus(status) {
        return status >= 200 && status < 300;
      }
      /**
       * Attempts to parse a response by looking at the Content-Type header.
       * @param {Response} response the HTTP response.
       * @returns a promise that resolves to the response data.
       */
      async getResponseDataFromContentType(response) {
        let contentType = response.headers.get("Content-Type");
        if (contentType === null) {
          return response.text();
        }
        contentType = contentType.toLowerCase();
        if (contentType.includes("application/json")) {
          let data = await response.text();
          try {
            data = JSON.parse(data);
          } catch {
          }
          return data;
        } else if (contentType.match(/^text\//)) {
          return response.text();
        } else {
          return response.blob();
        }
      }
      /**
       * Creates an async generator that yields the pieces of a multipart/related request body.
       * This implementation follows the spec: https://www.ietf.org/rfc/rfc2387.txt. However, recursive
       * multipart/related requests are not currently supported.
       *
       * @param {GaxiosMultipartOptions[]} multipartOptions the pieces to turn into a multipart/related body.
       * @param {string} boundary the boundary string to be placed between each part.
       */
      async *getMultipartRequest(multipartOptions, boundary) {
        const finale = `--${boundary}--`;
        for (const currentPart of multipartOptions) {
          const partContentType = currentPart.headers.get("Content-Type") || "application/octet-stream";
          const preamble = `--${boundary}\r
Content-Type: ${partContentType}\r
\r
`;
          yield preamble;
          if (typeof currentPart.content === "string") {
            yield currentPart.content;
          } else {
            yield* currentPart.content;
          }
          yield "\r\n";
        }
        yield finale;
      }
      /**
       * A cache for the lazily-loaded proxy agent.
       *
       * Should use {@link Gaxios[#getProxyAgent]} to retrieve.
       */
      // using `import` to dynamically import the types here
      static #proxyAgent;
      /**
       * A cache for the lazily-loaded fetch library.
       *
       * Should use {@link Gaxios[#getFetch]} to retrieve.
       */
      //
      static #fetch;
      /**
       * Imports, caches, and returns a proxy agent - if not already imported
       *
       * @returns A proxy agent
       */
      static async #getProxyAgent() {
        this.#proxyAgent ||= (await Promise.resolve().then(() => __toESM(require_dist2()))).HttpsProxyAgent;
        return this.#proxyAgent;
      }
      static async #getFetch() {
        const hasWindow = typeof window !== "undefined" && !!window;
        this.#fetch ||= hasWindow ? window.fetch : (await Promise.resolve().then(() => (init_src(), src_exports))).default;
        return this.#fetch;
      }
      /**
       * Merges headers.
       * If the base headers do not exist a new `Headers` object will be returned.
       *
       * @remarks
       *
       * Using this utility can be helpful when the headers are not known to exist:
       * - if they exist as `Headers`, that instance will be used
       *   - it improves performance and allows users to use their existing references to their `Headers`
       * - if they exist in another form (`HeadersInit`), they will be used to create a new `Headers` object
       * - if the base headers do not exist a new `Headers` object will be created
       *
       * @param base headers to append/overwrite to
       * @param append headers to append/overwrite with
       * @returns the base headers instance with merged `Headers`
       */
      static mergeHeaders(base, ...append) {
        base = base instanceof Headers ? base : new Headers(base);
        for (const headers of append) {
          const add = headers instanceof Headers ? headers : new Headers(headers);
          add.forEach((value, key) => {
            key === "set-cookie" ? base.append(key, value) : base.set(key, value);
          });
        }
        return base;
      }
    };
    exports2.Gaxios = Gaxios;
    _a3 = Gaxios;
  }
});

// node_modules/googleapis-common/node_modules/gaxios/build/cjs/src/index.js
var require_src5 = __commonJS({
  "node_modules/googleapis-common/node_modules/gaxios/build/cjs/src/index.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __exportStar = exports2 && exports2.__exportStar || function(m2, exports3) {
      for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m2, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.instance = exports2.Gaxios = exports2.GaxiosError = void 0;
    exports2.request = request;
    var gaxios_js_1 = require_gaxios2();
    Object.defineProperty(exports2, "Gaxios", { enumerable: true, get: function() {
      return gaxios_js_1.Gaxios;
    } });
    var common_js_1 = require_common5();
    Object.defineProperty(exports2, "GaxiosError", { enumerable: true, get: function() {
      return common_js_1.GaxiosError;
    } });
    __exportStar(require_interceptor2(), exports2);
    exports2.instance = new gaxios_js_1.Gaxios();
    async function request(opts) {
      return exports2.instance.request(opts);
    }
  }
});

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

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

// node_modules/base64-js/index.js
var require_base64_js = __commonJS({
  "node_modules/base64-js/index.js"(exports2) {
    "use strict";
    exports2.byteLength = byteLength;
    exports2.toByteArray = toByteArray;
    exports2.fromByteArray = fromByteArray;
    var lookup = [];
    var revLookup = [];
    var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
    var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    for (i2 = 0, len = code.length; i2 < len; ++i2) {
      lookup[i2] = code[i2];
      revLookup[code.charCodeAt(i2)] = i2;
    }
    var i2;
    var len;
    revLookup["-".charCodeAt(0)] = 62;
    revLookup["_".charCodeAt(0)] = 63;
    function getLens(b64) {
      var len2 = b64.length;
      if (len2 % 4 > 0) {
        throw new Error("Invalid string. Length must be a multiple of 4");
      }
      var validLen = b64.indexOf("=");
      if (validLen === -1) validLen = len2;
      var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
      return [validLen, placeHoldersLen];
    }
    function byteLength(b64) {
      var lens = getLens(b64);
      var validLen = lens[0];
      var placeHoldersLen = lens[1];
      return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
    }
    function _byteLength(b64, validLen, placeHoldersLen) {
      return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
    }
    function toByteArray(b64) {
      var tmp;
      var lens = getLens(b64);
      var validLen = lens[0];
      var placeHoldersLen = lens[1];
      var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
      var curByte = 0;
      var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
      var i3;
      for (i3 = 0; i3 < len2; i3 += 4) {
        tmp = revLookup[b64.charCodeAt(i3)] << 18 | revLookup[b64.charCodeAt(i3 + 1)] << 12 | revLookup[b64.charCodeAt(i3 + 2)] << 6 | revLookup[b64.charCodeAt(i3 + 3)];
        arr[curByte++] = tmp >> 16 & 255;
        arr[curByte++] = tmp >> 8 & 255;
        arr[curByte++] = tmp & 255;
      }
      if (placeHoldersLen === 2) {
        tmp = revLookup[b64.charCodeAt(i3)] << 2 | revLookup[b64.charCodeAt(i3 + 1)] >> 4;
        arr[curByte++] = tmp & 255;
      }
      if (placeHoldersLen === 1) {
        tmp = revLookup[b64.charCodeAt(i3)] << 10 | revLookup[b64.charCodeAt(i3 + 1)] << 4 | revLookup[b64.charCodeAt(i3 + 2)] >> 2;
        arr[curByte++] = tmp >> 8 & 255;
        arr[curByte++] = tmp & 255;
      }
      return arr;
    }
    function tripletToBase64(num) {
      return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
    }
    function encodeChunk(uint8, start, end) {
      var tmp;
      var output = [];
      for (var i3 = start; i3 < end; i3 += 3) {
        tmp = (uint8[i3] << 16 & 16711680) + (uint8[i3 + 1] << 8 & 65280) + (uint8[i3 + 2] & 255);
        output.push(tripletToBase64(tmp));
      }
      return output.join("");
    }
    function fromByteArray(uint8) {
      var tmp;
      var len2 = uint8.length;
      var extraBytes = len2 % 3;
      var parts = [];
      var maxChunkLength = 16383;
      for (var i3 = 0, len22 = len2 - extraBytes; i3 < len22; i3 += maxChunkLength) {
        parts.push(encodeChunk(uint8, i3, i3 + maxChunkLength > len22 ? len22 : i3 + maxChunkLength));
      }
      if (extraBytes === 1) {
        tmp = uint8[len2 - 1];
        parts.push(
          lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="
        );
      } else if (extraBytes === 2) {
        tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
        parts.push(
          lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="
        );
      }
      return parts.join("");
    }
  }
});

// node_modules/googleapis-common/node_modules/google-auth-library/build/src/crypto/shared.js
var require_shared2 = __commonJS({
  "node_modules/googleapis-common/node_modules/google-auth-library/build/src/crypto/shared.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.fromArrayBufferToHex = fromArrayBufferToHex;
    function fromArrayBufferToHex(arrayBuffer) {
      const byteArray = Array.from(new Uint8Array(arrayBuffer));
      return byteArray.map((byte) => {
        return byte.toString(16).padStart(2, "0");
      }).join("");
    }
  }
});

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

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

// node_modules/googleapis-common/node_modules/google-auth-library/build/src/crypto/crypto.js
var require_crypto3 = __commonJS({
  "node_modules/googleapis-common/node_modules/google-auth-library/build/src/crypto/crypto.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __exportStar = exports2 && exports2.__exportStar || function(m2, exports3) {
      for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m2, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createCrypto = createCrypto;
    exports2.hasBrowserCrypto = hasBrowserCrypto;
    var crypto_1 = require_crypto();
    var crypto_2 = require_crypto2();
    __exportStar(require_shared2(), exports2);
    function createCrypto() {
      if (hasBrowserCrypto()) {
        return new crypto_1.BrowserCrypto();
      }
      return new crypto_2.NodeCrypto();
    }
    function hasBrowserCrypto() {
      return typeof window !== "undefined" && typeof window.crypto !== "undefined" && typeof window.crypto.subtle !== "undefined";
    }
  }
});

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

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

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

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

// node_modules/googleapis-common/node_modules/google-auth-library/package.json
var require_package4 = __commonJS({
  "node_modules/googleapis-common/node_modules/google-auth-library/package.json"(exports2, module2) {
    module2.exports = {
      name: "google-auth-library",
      version: "10.5.0",
      author: "Google Inc.",
      description: "Google APIs Authentication Client Library for Node.js",
      engines: {
        node: ">=18"
      },
      main: "./build/src/index.js",
      types: "./build/src/index.d.ts",
      repository: "googleapis/google-auth-library-nodejs.git",
      keywords: [
        "google",
        "api",
        "google apis",
        "client",
        "client library"
      ],
      dependencies: {
        "base64-js": "^1.3.0",
        "ecdsa-sig-formatter": "^1.0.11",
        gaxios: "^7.0.0",
        "gcp-metadata": "^8.0.0",
        "google-logging-utils": "^1.0.0",
        gtoken: "^8.0.0",
        jws: "^4.0.0"
      },
      devDependencies: {
        "@types/base64-js": "^1.2.5",
        "@types/jws": "^3.1.0",
        "@types/mocha": "^10.0.10",
        "@types/mv": "^2.1.0",
        "@types/ncp": "^2.0.1",
        "@types/node": "^22.0.0",
        "@types/sinon": "^17.0.0",
        "assert-rejects": "^1.0.0",
        c8: "^10.0.0",
        codecov: "^3.0.2",
        gts: "^6.0.0",
        "is-docker": "^3.0.0",
        jsdoc: "^4.0.0",
        "jsdoc-fresh": "^5.0.0",
        "jsdoc-region-tag": "^4.0.0",
        karma: "^6.0.0",
        "karma-chrome-launcher": "^3.0.0",
        "karma-coverage": "^2.0.0",
        "karma-firefox-launcher": "^2.0.0",
        "karma-mocha": "^2.0.0",
        "karma-sourcemap-loader": "^0.4.0",
        "karma-webpack": "^5.0.1",
        keypair: "^1.0.4",
        mocha: "^11.1.0",
        mv: "^2.1.1",
        ncp: "^2.0.0",
        nock: "^14.0.5",
        "null-loader": "^4.0.0",
        puppeteer: "^24.0.0",
        sinon: "^21.0.0",
        "ts-loader": "^8.0.0",
        typescript: "5.8.2",
        webpack: "^5.21.2",
        "webpack-cli": "^4.0.0"
      },
      files: [
        "build/src",
        "!build/src/**/*.map"
      ],
      scripts: {
        test: "c8 mocha build/test",
        clean: "gts clean",
        prepare: "npm run compile",
        lint: "gts check --no-inline-config",
        compile: "tsc -p .",
        fix: "gts fix",
        pretest: "npm run compile -- --sourceMap",
        docs: "jsdoc -c .jsdoc.js",
        "samples-setup": "cd samples/ && npm link ../ && npm run setup && cd ../",
        "samples-test": "cd samples/ && npm link ../ && npm test && cd ../",
        "system-test": "mocha build/system-test --timeout 60000",
        "presystem-test": "npm run compile -- --sourceMap",
        webpack: "webpack",
        "browser-test": "karma start",
        "docs-test": "echo 'disabled until linkinator is fixed'",
        "predocs-test": "npm run docs",
        prelint: "cd samples; npm link ../; npm install"
      },
      license: "Apache-2.0"
    };
  }
});

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

// node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/authclient.js
var require_authclient = __commonJS({
  "node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/authclient.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AuthClient = exports2.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = exports2.DEFAULT_UNIVERSE = void 0;
    var events_1 = require("events");
    var gaxios_1 = require_src5();
    var util_1 = require_util3();
    var google_logging_utils_1 = require_src3();
    var shared_cjs_1 = require_shared3();
    exports2.DEFAULT_UNIVERSE = "googleapis.com";
    exports2.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = 5 * 60 * 1e3;
    var AuthClient = class _AuthClient extends events_1.EventEmitter {
      apiKey;
      projectId;
      /**
       * The quota project ID. The quota project can be used by client libraries for the billing purpose.
       * See {@link https://cloud.google.com/docs/quota Working with quotas}
       */
      quotaProjectId;
      /**
       * The {@link Gaxios `Gaxios`} instance used for making requests.
       */
      transporter;
      credentials = {};
      eagerRefreshThresholdMillis = exports2.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;
      forceRefreshOnFailure = false;
      universeDomain = exports2.DEFAULT_UNIVERSE;
      /**
       * Symbols that can be added to GaxiosOptions to specify the method name that is
       * making an RPC call, for logging purposes, as well as a string ID that can be
       * used to correlate calls and responses.
       */
      static RequestMethodNameSymbol = /* @__PURE__ */ Symbol("request method name");
      static RequestLogIdSymbol = /* @__PURE__ */ Symbol("request log id");
      constructor(opts = {}) {
        super();
        const options = (0, util_1.originalOrCamelOptions)(opts);
        this.apiKey = opts.apiKey;
        this.projectId = options.get("project_id") ?? null;
        this.quotaProjectId = options.get("quota_project_id");
        this.credentials = options.get("credentials") ?? {};
        this.universeDomain = options.get("universe_domain") ?? exports2.DEFAULT_UNIVERSE;
        this.transporter = opts.transporter ?? new gaxios_1.Gaxios(opts.transporterOptions);
        if (options.get("useAuthRequestParameters") !== false) {
          this.transporter.interceptors.request.add(_AuthClient.DEFAULT_REQUEST_INTERCEPTOR);
          this.transporter.interceptors.response.add(_AuthClient.DEFAULT_RESPONSE_INTERCEPTOR);
        }
        if (opts.eagerRefreshThresholdMillis) {
          this.eagerRefreshThresholdMillis = opts.eagerRefreshThresholdMillis;
        }
        this.forceRefreshOnFailure = opts.forceRefreshOnFailure ?? false;
      }
      /**
       * A {@link fetch `fetch`} compliant API for {@link AuthClient}.
       *
       * @see {@link AuthClient.request} for the classic method.
       *
       * @remarks
       *
       * This is useful as a drop-in replacement for `fetch` API usage.
       *
       * @example
       *
       * ```ts
       * const authClient = new AuthClient();
       * const fetchWithAuthClient: typeof fetch = (...args) => authClient.fetch(...args);
       * await fetchWithAuthClient('https://example.com');
       * ```
       *
       * @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters
       * @returns the {@link GaxiosResponse} with Gaxios-added properties
       */
      fetch(...args) {
        const input = args[0];
        const init = args[1];
        let url2 = void 0;
        const headers = new Headers();
        if (typeof input === "string") {
          url2 = new URL(input);
        } else if (input instanceof URL) {
          url2 = input;
        } else if (input && input.url) {
          url2 = new URL(input.url);
        }
        if (input && typeof input === "object" && "headers" in input) {
          gaxios_1.Gaxios.mergeHeaders(headers, input.headers);
        }
        if (init) {
          gaxios_1.Gaxios.mergeHeaders(headers, new Headers(init.headers));
        }
        if (typeof input === "object" && !(input instanceof URL)) {
          return this.request({ ...init, ...input, headers, url: url2 });
        } else {
          return this.request({ ...init, headers, url: url2 });
        }
      }
      /**
       * Sets the auth credentials.
       */
      setCredentials(credentials) {
        this.credentials = credentials;
      }
      /**
       * Append additional headers, e.g., x-goog-user-project, shared across the
       * classes inheriting AuthClient. This method should be used by any method
       * that overrides getRequestMetadataAsync(), which is a shared helper for
       * setting request information in both gRPC and HTTP API calls.
       *
       * @param headers object to append additional headers to.
       */
      addSharedMetadataHeaders(headers) {
        if (!headers.has("x-goog-user-project") && // don't override a value the user sets.
        this.quotaProjectId) {
          headers.set("x-goog-user-project", this.quotaProjectId);
        }
        return headers;
      }
      /**
       * Adds the `x-goog-user-project` and `authorization` headers to the target Headers
       * object, if they exist on the source.
       *
       * @param target the headers to target
       * @param source the headers to source from
       * @returns the target headers
       */
      addUserProjectAndAuthHeaders(target, source) {
        const xGoogUserProject = source.get("x-goog-user-project");
        const authorizationHeader = source.get("authorization");
        if (xGoogUserProject) {
          target.set("x-goog-user-project", xGoogUserProject);
        }
        if (authorizationHeader) {
          target.set("authorization", authorizationHeader);
        }
        return target;
      }
      static log = (0, google_logging_utils_1.log)("auth");
      static DEFAULT_REQUEST_INTERCEPTOR = {
        resolved: async (config2) => {
          if (!config2.headers.has("x-goog-api-client")) {
            const nodeVersion = process.version.replace(/^v/, "");
            config2.headers.set("x-goog-api-client", `gl-node/${nodeVersion}`);
          }
          const userAgent = config2.headers.get("User-Agent");
          if (!userAgent) {
            config2.headers.set("User-Agent", shared_cjs_1.USER_AGENT);
          } else if (!userAgent.includes(`${shared_cjs_1.PRODUCT_NAME}/`)) {
            config2.headers.set("User-Agent", `${userAgent} ${shared_cjs_1.USER_AGENT}`);
          }
          try {
            const symbols = config2;
            const methodName = symbols[_AuthClient.RequestMethodNameSymbol];
            const logId = `${Math.floor(Math.random() * 1e3)}`;
            symbols[_AuthClient.RequestLogIdSymbol] = logId;
            const logObject = {
              url: config2.url,
              headers: config2.headers
            };
            if (methodName) {
              _AuthClient.log.info("%s [%s] request %j", methodName, logId, logObject);
            } else {
              _AuthClient.log.info("[%s] request %j", logId, logObject);
            }
          } catch (e2) {
          }
          return config2;
        }
      };
      static DEFAULT_RESPONSE_INTERCEPTOR = {
        resolved: async (response) => {
          try {
            const symbols = response.config;
            const methodName = symbols[_AuthClient.RequestMethodNameSymbol];
            const logId = symbols[_AuthClient.RequestLogIdSymbol];
            if (methodName) {
              _AuthClient.log.info("%s [%s] response %j", methodName, logId, response.data);
            } else {
              _AuthClient.log.info("[%s] response %j", logId, response.data);
            }
          } catch (e2) {
          }
          return response;
        },
        rejected: async (error51) => {
          try {
            const symbols = error51.config;
            const methodName = symbols[_AuthClient.RequestMethodNameSymbol];
            const logId = symbols[_AuthClient.RequestLogIdSymbol];
            if (methodName) {
              _AuthClient.log.info("%s [%s] error %j", methodName, logId, error51.response?.data);
            } else {
              _AuthClient.log.error("[%s] error %j", logId, error51.response?.data);
            }
          } catch (e2) {
          }
          throw error51;
        }
      };
      /**
       * Sets the method name that is making a Gaxios request, so that logging may tag
       * log lines with the operation.
       * @param config A Gaxios request config
       * @param methodName The method name making the call
       */
      static setMethodName(config2, methodName) {
        try {
          const symbols = config2;
          symbols[_AuthClient.RequestMethodNameSymbol] = methodName;
        } catch (e2) {
        }
      }
      /**
       * Retry config for Auth-related requests.
       *
       * @remarks
       *
       * This is not a part of the default {@link AuthClient.transporter transporter/gaxios}
       * config as some downstream APIs would prefer if customers explicitly enable retries,
       * such as GCS.
       */
      static get RETRY_CONFIG() {
        return {
          retry: true,
          retryConfig: {
            httpMethodsToRetry: ["GET", "PUT", "POST", "HEAD", "OPTIONS", "DELETE"]
          }
        };
      }
    };
    exports2.AuthClient = AuthClient;
  }
});

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

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

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

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

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

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

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

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

// node_modules/jws/lib/tostring.js
var require_tostring = __commonJS({
  "node_modules/jws/lib/tostring.js"(exports2, module2) {
    var Buffer4 = require("buffer").Buffer;
    module2.exports = function toString(obj) {
      if (typeof obj === "string")
        return obj;
      if (typeof obj === "number" || Buffer4.isBuffer(obj))
        return obj.toString();
      return JSON.stringify(obj);
    };
  }
});

// node_modules/jws/lib/sign-stream.js
var require_sign_stream = __commonJS({
  "node_modules/jws/lib/sign-stream.js"(exports2, module2) {
    var Buffer4 = require_safe_buffer().Buffer;
    var DataStream = require_data_stream();
    var jwa = require_jwa();
    var Stream3 = require("stream");
    var toString = require_tostring();
    var util2 = require("util");
    function base64url3(string4, encoding) {
      return Buffer4.from(string4, encoding).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
    }
    function jwsSecuredInput(header, payload, encoding) {
      encoding = encoding || "utf8";
      var encodedHeader = base64url3(toString(header), "binary");
      var encodedPayload = base64url3(toString(payload), encoding);
      return util2.format("%s.%s", encodedHeader, encodedPayload);
    }
    function jwsSign(opts) {
      var header = opts.header;
      var payload = opts.payload;
      var secretOrKey = opts.secret || opts.privateKey;
      var encoding = opts.encoding;
      var algo = jwa(header.alg);
      var securedInput = jwsSecuredInput(header, payload, encoding);
      var signature = algo.sign(securedInput, secretOrKey);
      return util2.format("%s.%s", securedInput, signature);
    }
    function SignStream(opts) {
      var secret = opts.secret;
      secret = secret == null ? opts.privateKey : secret;
      secret = secret == null ? opts.key : secret;
      if (/^hs/i.test(opts.header.alg) === true && secret == null) {
        throw new TypeError("secret must be a string or buffer or a KeyObject");
      }
      var secretStream = new DataStream(secret);
      this.readable = true;
      this.header = opts.header;
      this.encoding = opts.encoding;
      this.secret = this.privateKey = this.key = secretStream;
      this.payload = new DataStream(opts.payload);
      this.secret.once("close", function() {
        if (!this.payload.writable && this.readable)
          this.sign();
      }.bind(this));
      this.payload.once("close", function() {
        if (!this.secret.writable && this.readable)
          this.sign();
      }.bind(this));
    }
    util2.inherits(SignStream, Stream3);
    SignStream.prototype.sign = function sign() {
      try {
        var signature = jwsSign({
          header: this.header,
          payload: this.payload.buffer,
          secret: this.secret.buffer,
          encoding: this.encoding
        });
        this.emit("done", signature);
        this.emit("data", signature);
        this.emit("end");
        this.readable = false;
        return signature;
      } catch (e2) {
        this.readable = false;
        this.emit("error", e2);
        this.emit("close");
      }
    };
    SignStream.sign = jwsSign;
    module2.exports = SignStream;
  }
});

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

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

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

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

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

// node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/refreshclient.js
var require_refreshclient = __commonJS({
  "node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/refreshclient.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.UserRefreshClient = exports2.USER_REFRESH_ACCOUNT_TYPE = void 0;
    var oauth2client_1 = require_oauth2client();
    var authclient_1 = require_authclient();
    exports2.USER_REFRESH_ACCOUNT_TYPE = "authorized_user";
    var UserRefreshClient = class _UserRefreshClient extends oauth2client_1.OAuth2Client {
      // TODO: refactor tests to make this private
      // In a future gts release, the _propertyName rule will be lifted.
      // This is also a hard one because `this.refreshToken` is a function.
      _refreshToken;
      /**
       * The User Refresh Token client.
       *
       * @param optionsOrClientId The User Refresh Token client options. Passing an `clientId` directly is **@DEPRECATED**.
       * @param clientSecret **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
       * @param refreshToken **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
       * @param eagerRefreshThresholdMillis **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
       * @param forceRefreshOnFailure **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
       */
      constructor(optionsOrClientId, clientSecret, refreshToken, eagerRefreshThresholdMillis, forceRefreshOnFailure) {
        const opts = optionsOrClientId && typeof optionsOrClientId === "object" ? optionsOrClientId : {
          clientId: optionsOrClientId,
          clientSecret,
          refreshToken,
          eagerRefreshThresholdMillis,
          forceRefreshOnFailure
        };
        super(opts);
        this._refreshToken = opts.refreshToken;
        this.credentials.refresh_token = opts.refreshToken;
      }
      /**
       * Refreshes the access token.
       * @param refreshToken An ignored refreshToken..
       * @param callback Optional callback.
       */
      async refreshTokenNoCache() {
        return super.refreshTokenNoCache(this._refreshToken);
      }
      async fetchIdToken(targetAudience) {
        const opts = {
          ..._UserRefreshClient.RETRY_CONFIG,
          url: this.endpoints.oauth2TokenUrl,
          method: "POST",
          data: new URLSearchParams({
            client_id: this._clientId,
            client_secret: this._clientSecret,
            grant_type: "refresh_token",
            refresh_token: this._refreshToken,
            target_audience: targetAudience
          })
        };
        authclient_1.AuthClient.setMethodName(opts, "fetchIdToken");
        const res = await this.transporter.request(opts);
        return res.data.id_token;
      }
      /**
       * Create a UserRefreshClient credentials instance using the given input
       * options.
       * @param json The input object.
       */
      fromJSON(json2) {
        if (!json2) {
          throw new Error("Must pass in a JSON object containing the user refresh token");
        }
        if (json2.type !== "authorized_user") {
          throw new Error('The incoming JSON object does not have the "authorized_user" type');
        }
        if (!json2.client_id) {
          throw new Error("The incoming JSON object does not contain a client_id field");
        }
        if (!json2.client_secret) {
          throw new Error("The incoming JSON object does not contain a client_secret field");
        }
        if (!json2.refresh_token) {
          throw new Error("The incoming JSON object does not contain a refresh_token field");
        }
        this._clientId = json2.client_id;
        this._clientSecret = json2.client_secret;
        this._refreshToken = json2.refresh_token;
        this.credentials.refresh_token = json2.refresh_token;
        this.quotaProjectId = json2.quota_project_id;
        this.universeDomain = json2.universe_domain || this.universeDomain;
      }
      fromStream(inputStream, callback) {
        if (callback) {
          this.fromStreamAsync(inputStream).then(() => callback(), callback);
        } else {
          return this.fromStreamAsync(inputStream);
        }
      }
      async fromStreamAsync(inputStream) {
        return new Promise((resolve2, reject) => {
          if (!inputStream) {
            return reject(new Error("Must pass in a stream containing the user refresh token."));
          }
          let s2 = "";
          inputStream.setEncoding("utf8").on("error", reject).on("data", (chunk) => s2 += chunk).on("end", () => {
            try {
              const data = JSON.parse(s2);
              this.fromJSON(data);
              return resolve2();
            } catch (err) {
              return reject(err);
            }
          });
        });
      }
      /**
       * Create a UserRefreshClient credentials instance using the given input
       * options.
       * @param json The input object.
       */
      static fromJSON(json2) {
        const client = new _UserRefreshClient();
        client.fromJSON(json2);
        return client;
      }
    };
    exports2.UserRefreshClient = UserRefreshClient;
  }
});

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

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

// node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/stscredentials.js
var require_stscredentials = __commonJS({
  "node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/stscredentials.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.StsCredentials = void 0;
    var gaxios_1 = require_src5();
    var authclient_1 = require_authclient();
    var oauth2common_1 = require_oauth2common();
    var util_1 = require_util3();
    var StsCredentials = class _StsCredentials extends oauth2common_1.OAuthClientAuthHandler {
      #tokenExchangeEndpoint;
      /**
       * Initializes an STS credentials instance.
       *
       * @param options The STS credentials instance options. Passing an `tokenExchangeEndpoint` directly is **@DEPRECATED**.
       * @param clientAuthentication **@DEPRECATED**. Provide a {@link StsCredentialsConstructionOptions `StsCredentialsConstructionOptions`} object in the first parameter instead.
       */
      constructor(options = {
        tokenExchangeEndpoint: ""
      }, clientAuthentication) {
        if (typeof options !== "object" || options instanceof URL) {
          options = {
            tokenExchangeEndpoint: options,
            clientAuthentication
          };
        }
        super(options);
        this.#tokenExchangeEndpoint = options.tokenExchangeEndpoint;
      }
      /**
       * Exchanges the provided token for another type of token based on the
       * rfc8693 spec.
       * @param stsCredentialsOptions The token exchange options used to populate
       *   the token exchange request.
       * @param additionalHeaders Optional additional headers to pass along the
       *   request.
       * @param options Optional additional GCP-specific non-spec defined options
       *   to send with the request.
       *   Example: `&options=${encodeUriComponent(JSON.stringified(options))}`
       * @return A promise that resolves with the token exchange response containing
       *   the requested token and its expiration time.
       */
      async exchangeToken(stsCredentialsOptions, headers, options) {
        const values = {
          grant_type: stsCredentialsOptions.grantType,
          resource: stsCredentialsOptions.resource,
          audience: stsCredentialsOptions.audience,
          scope: stsCredentialsOptions.scope?.join(" "),
          requested_token_type: stsCredentialsOptions.requestedTokenType,
          subject_token: stsCredentialsOptions.subjectToken,
          subject_token_type: stsCredentialsOptions.subjectTokenType,
          actor_token: stsCredentialsOptions.actingParty?.actorToken,
          actor_token_type: stsCredentialsOptions.actingParty?.actorTokenType,
          // Non-standard GCP-specific options.
          options: options && JSON.stringify(options)
        };
        const opts = {
          ..._StsCredentials.RETRY_CONFIG,
          url: this.#tokenExchangeEndpoint.toString(),
          method: "POST",
          headers,
          data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values))
        };
        authclient_1.AuthClient.setMethodName(opts, "exchangeToken");
        this.applyClientAuthenticationOptions(opts);
        try {
          const response = await this.transporter.request(opts);
          const stsSuccessfulResponse = response.data;
          stsSuccessfulResponse.res = response;
          return stsSuccessfulResponse;
        } catch (error51) {
          if (error51 instanceof gaxios_1.GaxiosError && error51.response) {
            throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(
              error51.response.data,
              // Preserve other fields from the original error.
              error51
            );
          }
          throw error51;
        }
      }
    };
    exports2.StsCredentials = StsCredentials;
  }
});

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

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

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

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

// node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/identitypoolclient.js
var require_identitypoolclient = __commonJS({
  "node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/identitypoolclient.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.IdentityPoolClient = void 0;
    var baseexternalclient_1 = require_baseexternalclient();
    var util_1 = require_util3();
    var filesubjecttokensupplier_1 = require_filesubjecttokensupplier();
    var urlsubjecttokensupplier_1 = require_urlsubjecttokensupplier();
    var certificatesubjecttokensupplier_1 = require_certificatesubjecttokensupplier();
    var stscredentials_1 = require_stscredentials();
    var gaxios_1 = require_src5();
    var IdentityPoolClient = class _IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient {
      subjectTokenSupplier;
      /**
       * Instantiate an IdentityPoolClient instance using the provided JSON
       * object loaded from an external account credentials file.
       * An error is thrown if the credential is not a valid file-sourced or
       * url-sourced credential or a workforce pool user project is provided
       * with a non workforce audience.
       * @param options The external account options object typically loaded
       *   from the external account JSON credential file. The camelCased options
       *   are aliases for the snake_cased options.
       */
      constructor(options) {
        super(options);
        const opts = (0, util_1.originalOrCamelOptions)(options);
        const credentialSource = opts.get("credential_source");
        const subjectTokenSupplier = opts.get("subject_token_supplier");
        if (!credentialSource && !subjectTokenSupplier) {
          throw new Error("A credential source or subject token supplier must be specified.");
        }
        if (credentialSource && subjectTokenSupplier) {
          throw new Error("Only one of credential source or subject token supplier can be specified.");
        }
        if (subjectTokenSupplier) {
          this.subjectTokenSupplier = subjectTokenSupplier;
          this.credentialSourceType = "programmatic";
        } else {
          const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource);
          const formatOpts = (0, util_1.originalOrCamelOptions)(credentialSourceOpts.get("format"));
          const formatType = formatOpts.get("type") || "text";
          const formatSubjectTokenFieldName = formatOpts.get("subject_token_field_name");
          if (formatType !== "json" && formatType !== "text") {
            throw new Error(`Invalid credential_source format "${formatType}"`);
          }
          if (formatType === "json" && !formatSubjectTokenFieldName) {
            throw new Error("Missing subject_token_field_name for JSON credential_source format");
          }
          const file2 = credentialSourceOpts.get("file");
          const url2 = credentialSourceOpts.get("url");
          const certificate = credentialSourceOpts.get("certificate");
          const headers = credentialSourceOpts.get("headers");
          if (file2 && url2 || url2 && certificate || file2 && certificate) {
            throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');
          } else if (file2) {
            this.credentialSourceType = "file";
            this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({
              filePath: file2,
              formatType,
              subjectTokenFieldName: formatSubjectTokenFieldName
            });
          } else if (url2) {
            this.credentialSourceType = "url";
            this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({
              url: url2,
              formatType,
              subjectTokenFieldName: formatSubjectTokenFieldName,
              headers,
              additionalGaxiosOptions: _IdentityPoolClient.RETRY_CONFIG
            });
          } else if (certificate) {
            this.credentialSourceType = "certificate";
            const certificateSubjecttokensupplier = new certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier({
              useDefaultCertificateConfig: certificate.use_default_certificate_config,
              certificateConfigLocation: certificate.certificate_config_location,
              trustChainPath: certificate.trust_chain_path
            });
            this.subjectTokenSupplier = certificateSubjecttokensupplier;
          } else {
            throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');
          }
        }
      }
      /**
       * Triggered when a external subject token is needed to be exchanged for a GCP
       * access token via GCP STS endpoint. Gets a subject token by calling
       * the configured {@link SubjectTokenSupplier}
       * @return A promise that resolves with the external subject token.
       */
      async retrieveSubjectToken() {
        const subjectToken = await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);
        if (this.subjectTokenSupplier instanceof certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier) {
          const mtlsAgent = await this.subjectTokenSupplier.createMtlsHttpsAgent();
          this.stsCredential = new stscredentials_1.StsCredentials({
            tokenExchangeEndpoint: this.getTokenUrl(),
            clientAuthentication: this.clientAuth,
            transporter: new gaxios_1.Gaxios({ agent: mtlsAgent })
          });
          this.transporter = new gaxios_1.Gaxios({
            ...this.transporter.defaults || {},
            agent: mtlsAgent
          });
        }
        return subjectToken;
      }
    };
    exports2.IdentityPoolClient = IdentityPoolClient;
  }
});

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

// node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js
var require_defaultawssecuritycredentialssupplier = __commonJS({
  "node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DefaultAwsSecurityCredentialsSupplier = void 0;
    var authclient_1 = require_authclient();
    var DefaultAwsSecurityCredentialsSupplier = class {
      regionUrl;
      securityCredentialsUrl;
      imdsV2SessionTokenUrl;
      additionalGaxiosOptions;
      /**
       * Instantiates a new DefaultAwsSecurityCredentialsSupplier using information
       * from the credential_source stored in the ADC file.
       * @param opts The default aws security credentials supplier options object to
       *   build the supplier with.
       */
      constructor(opts) {
        this.regionUrl = opts.regionUrl;
        this.securityCredentialsUrl = opts.securityCredentialsUrl;
        this.imdsV2SessionTokenUrl = opts.imdsV2SessionTokenUrl;
        this.additionalGaxiosOptions = opts.additionalGaxiosOptions;
      }
      /**
       * Returns the active AWS region. This first checks to see if the region
       * is available as an environment variable. If it is not, then the supplier
       * will call the region URL.
       * @param context {@link ExternalAccountSupplierContext} from the calling
       *   {@link AwsClient}, contains the requested audience and subject token type
       *   for the external account identity.
       * @return A promise that resolves with the AWS region string.
       */
      async getAwsRegion(context) {
        if (this.#regionFromEnv) {
          return this.#regionFromEnv;
        }
        const metadataHeaders = new Headers();
        if (!this.#regionFromEnv && this.imdsV2SessionTokenUrl) {
          metadataHeaders.set("x-aws-ec2-metadata-token", await this.#getImdsV2SessionToken(context.transporter));
        }
        if (!this.regionUrl) {
          throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');
        }
        const opts = {
          ...this.additionalGaxiosOptions,
          url: this.regionUrl,
          method: "GET",
          headers: metadataHeaders
        };
        authclient_1.AuthClient.setMethodName(opts, "getAwsRegion");
        const response = await context.transporter.request(opts);
        return response.data.substr(0, response.data.length - 1);
      }
      /**
       * Returns AWS security credentials. This first checks to see if the credentials
       * is available as environment variables. If it is not, then the supplier
       * will call the security credentials URL.
       * @param context {@link ExternalAccountSupplierContext} from the calling
       *   {@link AwsClient}, contains the requested audience and subject token type
       *   for the external account identity.
       * @return A promise that resolves with the AWS security credentials.
       */
      async getAwsSecurityCredentials(context) {
        if (this.#securityCredentialsFromEnv) {
          return this.#securityCredentialsFromEnv;
        }
        const metadataHeaders = new Headers();
        if (this.imdsV2SessionTokenUrl) {
          metadataHeaders.set("x-aws-ec2-metadata-token", await this.#getImdsV2SessionToken(context.transporter));
        }
        const roleName = await this.#getAwsRoleName(metadataHeaders, context.transporter);
        const awsCreds = await this.#retrieveAwsSecurityCredentials(roleName, metadataHeaders, context.transporter);
        return {
          accessKeyId: awsCreds.AccessKeyId,
          secretAccessKey: awsCreds.SecretAccessKey,
          token: awsCreds.Token
        };
      }
      /**
       * @param transporter The transporter to use for requests.
       * @return A promise that resolves with the IMDSv2 Session Token.
       */
      async #getImdsV2SessionToken(transporter) {
        const opts = {
          ...this.additionalGaxiosOptions,
          url: this.imdsV2SessionTokenUrl,
          method: "PUT",
          headers: { "x-aws-ec2-metadata-token-ttl-seconds": "300" }
        };
        authclient_1.AuthClient.setMethodName(opts, "#getImdsV2SessionToken");
        const response = await transporter.request(opts);
        return response.data;
      }
      /**
       * @param headers The headers to be used in the metadata request.
       * @param transporter The transporter to use for requests.
       * @return A promise that resolves with the assigned role to the current
       *   AWS VM. This is needed for calling the security-credentials endpoint.
       */
      async #getAwsRoleName(headers, transporter) {
        if (!this.securityCredentialsUrl) {
          throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');
        }
        const opts = {
          ...this.additionalGaxiosOptions,
          url: this.securityCredentialsUrl,
          method: "GET",
          headers
        };
        authclient_1.AuthClient.setMethodName(opts, "#getAwsRoleName");
        const response = await transporter.request(opts);
        return response.data;
      }
      /**
       * Retrieves the temporary AWS credentials by calling the security-credentials
       * endpoint as specified in the `credential_source` object.
       * @param roleName The role attached to the current VM.
       * @param headers The headers to be used in the metadata request.
       * @param transporter The transporter to use for requests.
       * @return A promise that resolves with the temporary AWS credentials
       *   needed for creating the GetCallerIdentity signed request.
       */
      async #retrieveAwsSecurityCredentials(roleName, headers, transporter) {
        const opts = {
          ...this.additionalGaxiosOptions,
          url: `${this.securityCredentialsUrl}/${roleName}`,
          headers
        };
        authclient_1.AuthClient.setMethodName(opts, "#retrieveAwsSecurityCredentials");
        const response = await transporter.request(opts);
        return response.data;
      }
      get #regionFromEnv() {
        return process.env["AWS_REGION"] || process.env["AWS_DEFAULT_REGION"] || null;
      }
      get #securityCredentialsFromEnv() {
        if (process.env["AWS_ACCESS_KEY_ID"] && process.env["AWS_SECRET_ACCESS_KEY"]) {
          return {
            accessKeyId: process.env["AWS_ACCESS_KEY_ID"],
            secretAccessKey: process.env["AWS_SECRET_ACCESS_KEY"],
            token: process.env["AWS_SESSION_TOKEN"]
          };
        }
        return null;
      }
    };
    exports2.DefaultAwsSecurityCredentialsSupplier = DefaultAwsSecurityCredentialsSupplier;
  }
});

// node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/awsclient.js
var require_awsclient = __commonJS({
  "node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/awsclient.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AwsClient = void 0;
    var awsrequestsigner_1 = require_awsrequestsigner();
    var baseexternalclient_1 = require_baseexternalclient();
    var defaultawssecuritycredentialssupplier_1 = require_defaultawssecuritycredentialssupplier();
    var util_1 = require_util3();
    var gaxios_1 = require_src5();
    var AwsClient = class _AwsClient extends baseexternalclient_1.BaseExternalAccountClient {
      environmentId;
      awsSecurityCredentialsSupplier;
      regionalCredVerificationUrl;
      awsRequestSigner;
      region;
      static #DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL = "https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";
      /**
       * @deprecated AWS client no validates the EC2 metadata address.
       **/
      static AWS_EC2_METADATA_IPV4_ADDRESS = "169.254.169.254";
      /**
       * @deprecated AWS client no validates the EC2 metadata address.
       **/
      static AWS_EC2_METADATA_IPV6_ADDRESS = "fd00:ec2::254";
      /**
       * Instantiates an AwsClient instance using the provided JSON
       * object loaded from an external account credentials file.
       * An error is thrown if the credential is not a valid AWS credential.
       * @param options The external account options object typically loaded
       *   from the external account JSON credential file.
       */
      constructor(options) {
        super(options);
        const opts = (0, util_1.originalOrCamelOptions)(options);
        const credentialSource = opts.get("credential_source");
        const awsSecurityCredentialsSupplier = opts.get("aws_security_credentials_supplier");
        if (!credentialSource && !awsSecurityCredentialsSupplier) {
          throw new Error("A credential source or AWS security credentials supplier must be specified.");
        }
        if (credentialSource && awsSecurityCredentialsSupplier) {
          throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");
        }
        if (awsSecurityCredentialsSupplier) {
          this.awsSecurityCredentialsSupplier = awsSecurityCredentialsSupplier;
          this.regionalCredVerificationUrl = _AwsClient.#DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL;
          this.credentialSourceType = "programmatic";
        } else {
          const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource);
          this.environmentId = credentialSourceOpts.get("environment_id");
          const regionUrl = credentialSourceOpts.get("region_url");
          const securityCredentialsUrl = credentialSourceOpts.get("url");
          const imdsV2SessionTokenUrl = credentialSourceOpts.get("imdsv2_session_token_url");
          this.awsSecurityCredentialsSupplier = new defaultawssecuritycredentialssupplier_1.DefaultAwsSecurityCredentialsSupplier({
            regionUrl,
            securityCredentialsUrl,
            imdsV2SessionTokenUrl
          });
          this.regionalCredVerificationUrl = credentialSourceOpts.get("regional_cred_verification_url");
          this.credentialSourceType = "aws";
          this.validateEnvironmentId();
        }
        this.awsRequestSigner = null;
        this.region = "";
      }
      validateEnvironmentId() {
        const match = this.environmentId?.match(/^(aws)(\d+)$/);
        if (!match || !this.regionalCredVerificationUrl) {
          throw new Error('No valid AWS "credential_source" provided');
        } else if (parseInt(match[2], 10) !== 1) {
          throw new Error(`aws version "${match[2]}" is not supported in the current build.`);
        }
      }
      /**
       * Triggered when an external subject token is needed to be exchanged for a
       * GCP access token via GCP STS endpoint. This will call the
       * {@link AwsSecurityCredentialsSupplier} to retrieve an AWS region and AWS
       * Security Credentials, then use them to create a signed AWS STS request that
       * can be exchanged for a GCP access token.
       * @return A promise that resolves with the external subject token.
       */
      async retrieveSubjectToken() {
        if (!this.awsRequestSigner) {
          this.region = await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext);
          this.awsRequestSigner = new awsrequestsigner_1.AwsRequestSigner(async () => {
            return this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext);
          }, this.region);
        }
        const options = await this.awsRequestSigner.getRequestOptions({
          ..._AwsClient.RETRY_CONFIG,
          url: this.regionalCredVerificationUrl.replace("{region}", this.region),
          method: "POST"
        });
        const reformattedHeader = [];
        const extendedHeaders = gaxios_1.Gaxios.mergeHeaders({
          // The full, canonical resource name of the workload identity pool
          // provider, with or without the HTTPS prefix.
          // Including this header as part of the signature is recommended to
          // ensure data integrity.
          "x-goog-cloud-target-resource": this.audience
        }, options.headers);
        extendedHeaders.forEach((value, key) => reformattedHeader.push({ key, value }));
        return encodeURIComponent(JSON.stringify({
          url: options.url,
          method: options.method,
          headers: reformattedHeader
        }));
      }
    };
    exports2.AwsClient = AwsClient;
  }
});

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

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

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

// node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/externalclient.js
var require_externalclient = __commonJS({
  "node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/externalclient.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ExternalAccountClient = void 0;
    var baseexternalclient_1 = require_baseexternalclient();
    var identitypoolclient_1 = require_identitypoolclient();
    var awsclient_1 = require_awsclient();
    var pluggable_auth_client_1 = require_pluggable_auth_client();
    var ExternalAccountClient = class {
      constructor() {
        throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()");
      }
      /**
       * This static method will instantiate the
       * corresponding type of external account credential depending on the
       * underlying credential source.
       *
       * **IMPORTANT**: This method does not validate the credential configuration.
       * A security risk occurs when a credential configuration configured with
       * malicious URLs is used. When the credential configuration is accepted from
       * an untrusted source, you should validate it before using it with this
       * method. For more details, see
       * https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.
       *
       * @param options The external account options object typically loaded
       *   from the external account JSON credential file.
       * @return A BaseExternalAccountClient instance or null if the options
       *   provided do not correspond to an external account credential.
       */
      static fromJSON(options) {
        if (options && options.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {
          if (options.credential_source?.environment_id) {
            return new awsclient_1.AwsClient(options);
          } else if (options.credential_source?.executable) {
            return new pluggable_auth_client_1.PluggableAuthClient(options);
          } else {
            return new identitypoolclient_1.IdentityPoolClient(options);
          }
        } else {
          return null;
        }
      }
    };
    exports2.ExternalAccountClient = ExternalAccountClient;
  }
});

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

// node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/googleauth.js
var require_googleauth = __commonJS({
  "node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/googleauth.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.GoogleAuth = exports2.GoogleAuthExceptionMessages = void 0;
    var child_process_1 = require("child_process");
    var fs2 = require("fs");
    var gaxios_1 = require_src5();
    var gcpMetadata = require_src6();
    var os = require("os");
    var path = require("path");
    var crypto_1 = require_crypto3();
    var computeclient_1 = require_computeclient();
    var idtokenclient_1 = require_idtokenclient();
    var envDetect_1 = require_envDetect();
    var jwtclient_1 = require_jwtclient();
    var refreshclient_1 = require_refreshclient();
    var impersonated_1 = require_impersonated();
    var externalclient_1 = require_externalclient();
    var baseexternalclient_1 = require_baseexternalclient();
    var authclient_1 = require_authclient();
    var externalAccountAuthorizedUserClient_1 = require_externalAccountAuthorizedUserClient();
    var util_1 = require_util3();
    exports2.GoogleAuthExceptionMessages = {
      API_KEY_WITH_CREDENTIALS: "API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",
      NO_PROJECT_ID_FOUND: "Unable to detect a Project Id in the current environment. \nTo learn more about authentication and Google APIs, visit: \nhttps://cloud.google.com/docs/authentication/getting-started",
      NO_CREDENTIALS_FOUND: "Unable to find credentials in current environment. \nTo learn more about authentication and Google APIs, visit: \nhttps://cloud.google.com/docs/authentication/getting-started",
      NO_ADC_FOUND: "Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",
      NO_UNIVERSE_DOMAIN_FOUND: "Unable to detect a Universe Domain in the current environment.\nTo learn more about Universe Domain retrieval, visit: \nhttps://cloud.google.com/compute/docs/metadata/predefined-metadata-keys"
    };
    var GoogleAuth = class {
      /**
       * Caches a value indicating whether the auth layer is running on Google
       * Compute Engine.
       * @private
       */
      checkIsGCE = void 0;
      useJWTAccessWithScope;
      defaultServicePath;
      // Note:  this properly is only public to satisfy unit tests.
      // https://github.com/Microsoft/TypeScript/issues/5228
      get isGCE() {
        return this.checkIsGCE;
      }
      _findProjectIdPromise;
      _cachedProjectId;
      // To save the contents of the JSON credential file
      jsonContent = null;
      apiKey;
      cachedCredential = null;
      /**
       * A pending {@link AuthClient}. Used for concurrent {@link GoogleAuth.getClient} calls.
       */
      #pendingAuthClient = null;
      /**
       * Scopes populated by the client library by default. We differentiate between
       * these and user defined scopes when deciding whether to use a self-signed JWT.
       */
      defaultScopes;
      keyFilename;
      scopes;
      clientOptions = {};
      /**
       * Configuration is resolved in the following order of precedence:
       * - {@link GoogleAuthOptions.credentials `credentials`}
       * - {@link GoogleAuthOptions.keyFilename `keyFilename`}
       * - {@link GoogleAuthOptions.keyFile `keyFile`}
       *
       * {@link GoogleAuthOptions.clientOptions `clientOptions`} are passed to the
       * {@link AuthClient `AuthClient`s}.
       *
       * @param opts
       */
      constructor(opts = {}) {
        this._cachedProjectId = opts.projectId || null;
        this.cachedCredential = opts.authClient || null;
        this.keyFilename = opts.keyFilename || opts.keyFile;
        this.scopes = opts.scopes;
        this.clientOptions = opts.clientOptions || {};
        this.jsonContent = opts.credentials || null;
        this.apiKey = opts.apiKey || this.clientOptions.apiKey || null;
        if (this.apiKey && (this.jsonContent || this.clientOptions.credentials)) {
          throw new RangeError(exports2.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);
        }
        if (opts.universeDomain) {
          this.clientOptions.universeDomain = opts.universeDomain;
        }
      }
      // GAPIC client libraries should always use self-signed JWTs. The following
      // variables are set on the JWT client in order to indicate the type of library,
      // and sign the JWT with the correct audience and scopes (if not supplied).
      setGapicJWTValues(client) {
        client.defaultServicePath = this.defaultServicePath;
        client.useJWTAccessWithScope = this.useJWTAccessWithScope;
        client.defaultScopes = this.defaultScopes;
      }
      getProjectId(callback) {
        if (callback) {
          this.getProjectIdAsync().then((r2) => callback(null, r2), callback);
        } else {
          return this.getProjectIdAsync();
        }
      }
      /**
       * A temporary method for internal `getProjectId` usages where `null` is
       * acceptable. In a future major release, `getProjectId` should return `null`
       * (as the `Promise<string | null>` base signature describes) and this private
       * method should be removed.
       *
       * @returns Promise that resolves with project id (or `null`)
       */
      async getProjectIdOptional() {
        try {
          return await this.getProjectId();
        } catch (e2) {
          if (e2 instanceof Error && e2.message === exports2.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND) {
            return null;
          } else {
            throw e2;
          }
        }
      }
      /**
       * A private method for finding and caching a projectId.
       *
       * Supports environments in order of precedence:
       * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable
       * - GOOGLE_APPLICATION_CREDENTIALS JSON file
       * - Cloud SDK: `gcloud config config-helper --format json`
       * - GCE project ID from metadata server
       *
       * @returns projectId
       */
      async findAndCacheProjectId() {
        let projectId = null;
        projectId ||= await this.getProductionProjectId();
        projectId ||= await this.getFileProjectId();
        projectId ||= await this.getDefaultServiceProjectId();
        projectId ||= await this.getGCEProjectId();
        projectId ||= await this.getExternalAccountClientProjectId();
        if (projectId) {
          this._cachedProjectId = projectId;
          return projectId;
        } else {
          throw new Error(exports2.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND);
        }
      }
      async getProjectIdAsync() {
        if (this._cachedProjectId) {
          return this._cachedProjectId;
        }
        if (!this._findProjectIdPromise) {
          this._findProjectIdPromise = this.findAndCacheProjectId();
        }
        return this._findProjectIdPromise;
      }
      /**
       * Retrieves a universe domain from the metadata server via
       * {@link gcpMetadata.universe}.
       *
       * @returns a universe domain
       */
      async getUniverseDomainFromMetadataServer() {
        let universeDomain;
        try {
          universeDomain = await gcpMetadata.universe("universe-domain");
          universeDomain ||= authclient_1.DEFAULT_UNIVERSE;
        } catch (e2) {
          if (e2 && e2?.response?.status === 404) {
            universeDomain = authclient_1.DEFAULT_UNIVERSE;
          } else {
            throw e2;
          }
        }
        return universeDomain;
      }
      /**
       * Retrieves, caches, and returns the universe domain in the following order
       * of precedence:
       * - The universe domain in {@link GoogleAuth.clientOptions}
       * - An existing or ADC {@link AuthClient}'s universe domain
       * - {@link gcpMetadata.universe}, if {@link Compute} client
       *
       * @returns The universe domain
       */
      async getUniverseDomain() {
        let universeDomain = (0, util_1.originalOrCamelOptions)(this.clientOptions).get("universe_domain");
        try {
          universeDomain ??= (await this.getClient()).universeDomain;
        } catch {
          universeDomain ??= authclient_1.DEFAULT_UNIVERSE;
        }
        return universeDomain;
      }
      /**
       * @returns Any scopes (user-specified or default scopes specified by the
       *   client library) that need to be set on the current Auth client.
       */
      getAnyScopes() {
        return this.scopes || this.defaultScopes;
      }
      getApplicationDefault(optionsOrCallback = {}, callback) {
        let options;
        if (typeof optionsOrCallback === "function") {
          callback = optionsOrCallback;
        } else {
          options = optionsOrCallback;
        }
        if (callback) {
          this.getApplicationDefaultAsync(options).then((r2) => callback(null, r2.credential, r2.projectId), callback);
        } else {
          return this.getApplicationDefaultAsync(options);
        }
      }
      async getApplicationDefaultAsync(options = {}) {
        if (this.cachedCredential) {
          return await this.#prepareAndCacheClient(this.cachedCredential, null);
        }
        let credential;
        credential = await this._tryGetApplicationCredentialsFromEnvironmentVariable(options);
        if (credential) {
          if (credential instanceof jwtclient_1.JWT) {
            credential.scopes = this.scopes;
          } else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) {
            credential.scopes = this.getAnyScopes();
          }
          return await this.#prepareAndCacheClient(credential);
        }
        credential = await this._tryGetApplicationCredentialsFromWellKnownFile(options);
        if (credential) {
          if (credential instanceof jwtclient_1.JWT) {
            credential.scopes = this.scopes;
          } else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) {
            credential.scopes = this.getAnyScopes();
          }
          return await this.#prepareAndCacheClient(credential);
        }
        if (await this._checkIsGCE()) {
          options.scopes = this.getAnyScopes();
          return await this.#prepareAndCacheClient(new computeclient_1.Compute(options));
        }
        throw new Error(exports2.GoogleAuthExceptionMessages.NO_ADC_FOUND);
      }
      async #prepareAndCacheClient(credential, quotaProjectIdOverride = process.env["GOOGLE_CLOUD_QUOTA_PROJECT"] || null) {
        const projectId = await this.getProjectIdOptional();
        if (quotaProjectIdOverride) {
          credential.quotaProjectId = quotaProjectIdOverride;
        }
        this.cachedCredential = credential;
        return { credential, projectId };
      }
      /**
       * Determines whether the auth layer is running on Google Compute Engine.
       * Checks for GCP Residency, then fallback to checking if metadata server
       * is available.
       *
       * @returns A promise that resolves with the boolean.
       * @api private
       */
      async _checkIsGCE() {
        if (this.checkIsGCE === void 0) {
          this.checkIsGCE = gcpMetadata.getGCPResidency() || await gcpMetadata.isAvailable();
        }
        return this.checkIsGCE;
      }
      /**
       * Attempts to load default credentials from the environment variable path..
       * @returns Promise that resolves with the OAuth2Client or null.
       * @api private
       */
      async _tryGetApplicationCredentialsFromEnvironmentVariable(options) {
        const credentialsPath = process.env["GOOGLE_APPLICATION_CREDENTIALS"] || process.env["google_application_credentials"];
        if (!credentialsPath || credentialsPath.length === 0) {
          return null;
        }
        try {
          return this._getApplicationCredentialsFromFilePath(credentialsPath, options);
        } catch (e2) {
          if (e2 instanceof Error) {
            e2.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e2.message}`;
          }
          throw e2;
        }
      }
      /**
       * Attempts to load default credentials from a well-known file location
       * @return Promise that resolves with the OAuth2Client or null.
       * @api private
       */
      async _tryGetApplicationCredentialsFromWellKnownFile(options) {
        let location = null;
        if (this._isWindows()) {
          location = process.env["APPDATA"];
        } else {
          const home = process.env["HOME"];
          if (home) {
            location = path.join(home, ".config");
          }
        }
        if (location) {
          location = path.join(location, "gcloud", "application_default_credentials.json");
          if (!fs2.existsSync(location)) {
            location = null;
          }
        }
        if (!location) {
          return null;
        }
        const client = await this._getApplicationCredentialsFromFilePath(location, options);
        return client;
      }
      /**
       * Attempts to load default credentials from a file at the given path..
       * @param filePath The path to the file to read.
       * @returns Promise that resolves with the OAuth2Client
       * @api private
       */
      async _getApplicationCredentialsFromFilePath(filePath, options = {}) {
        if (!filePath || filePath.length === 0) {
          throw new Error("The file path is invalid.");
        }
        try {
          filePath = fs2.realpathSync(filePath);
          if (!fs2.lstatSync(filePath).isFile()) {
            throw new Error();
          }
        } catch (err) {
          if (err instanceof Error) {
            err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`;
          }
          throw err;
        }
        const readStream = fs2.createReadStream(filePath);
        return this.fromStream(readStream, options);
      }
      /**
       * Create a credentials instance using a given impersonated input options.
       * @param json The impersonated input object.
       * @returns JWT or UserRefresh Client with data
       */
      fromImpersonatedJSON(json2) {
        if (!json2) {
          throw new Error("Must pass in a JSON object containing an  impersonated refresh token");
        }
        if (json2.type !== impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {
          throw new Error(`The incoming JSON object does not have the "${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}" type`);
        }
        if (!json2.source_credentials) {
          throw new Error("The incoming JSON object does not contain a source_credentials field");
        }
        if (!json2.service_account_impersonation_url) {
          throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");
        }
        const sourceClient = this.fromJSON(json2.source_credentials);
        if (json2.service_account_impersonation_url?.length > 256) {
          throw new RangeError(`Target principal is too long: ${json2.service_account_impersonation_url}`);
        }
        const targetPrincipal = /(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(json2.service_account_impersonation_url)?.groups?.target;
        if (!targetPrincipal) {
          throw new RangeError(`Cannot extract target principal from ${json2.service_account_impersonation_url}`);
        }
        const targetScopes = (this.scopes || json2.scopes || this.defaultScopes) ?? [];
        return new impersonated_1.Impersonated({
          ...json2,
          sourceClient,
          targetPrincipal,
          targetScopes: Array.isArray(targetScopes) ? targetScopes : [targetScopes]
        });
      }
      /**
       * Create a credentials instance using the given input options.
       * This client is not cached.
       *
       * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}.
       *
       * @deprecated This method is being deprecated because of a potential security risk.
       *
       * This method does not validate the credential configuration. The security
       * risk occurs when a credential configuration is accepted from a source that
       * is not under your control and used without validation on your side.
       *
       * If you know that you will be loading credential configurations of a
       * specific type, it is recommended to use a credential-type-specific
       * constructor. This will ensure that an unexpected credential type with
       * potential for malicious intent is not loaded unintentionally. You might
       * still have to do validation for certain credential types. Please follow
       * the recommendation for that method. For example, if you want to load only
       * service accounts, you can use the `JWT` constructor:
       * ```
       * const {JWT} = require('google-auth-library');
       * const keys = require('/path/to/key.json');
       * const client = new JWT({
       *   email: keys.client_email,
       *   key: keys.private_key,
       *   scopes: ['https://www.googleapis.com/auth/cloud-platform'],
       * });
       * ```
       *
       * If you are loading your credential configuration from an untrusted source and have
       * not mitigated the risks (e.g. by validating the configuration yourself), make
       * these changes as soon as possible to prevent security risks to your environment.
       *
       * Regardless of the method used, it is always your responsibility to validate
       * configurations received from external sources.
       *
       * For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.
       *
       * @param json The input object.
       * @param options The JWT or UserRefresh options for the client
       * @returns JWT or UserRefresh Client with data
       */
      fromJSON(json2, options = {}) {
        let client;
        const preferredUniverseDomain = (0, util_1.originalOrCamelOptions)(options).get("universe_domain");
        if (json2.type === refreshclient_1.USER_REFRESH_ACCOUNT_TYPE) {
          client = new refreshclient_1.UserRefreshClient(options);
          client.fromJSON(json2);
        } else if (json2.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {
          client = this.fromImpersonatedJSON(json2);
        } else if (json2.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {
          client = externalclient_1.ExternalAccountClient.fromJSON({
            ...json2,
            ...options
          });
          client.scopes = this.getAnyScopes();
        } else if (json2.type === externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE) {
          client = new externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient({
            ...json2,
            ...options
          });
        } else {
          options.scopes = this.scopes;
          client = new jwtclient_1.JWT(options);
          this.setGapicJWTValues(client);
          client.fromJSON(json2);
        }
        if (preferredUniverseDomain) {
          client.universeDomain = preferredUniverseDomain;
        }
        return client;
      }
      /**
       * Return a JWT or UserRefreshClient from JavaScript object, caching both the
       * object used to instantiate and the client.
       * @param json The input object.
       * @param options The JWT or UserRefresh options for the client
       * @returns JWT or UserRefresh Client with data
       */
      _cacheClientFromJSON(json2, options) {
        const client = this.fromJSON(json2, options);
        this.jsonContent = json2;
        this.cachedCredential = client;
        return client;
      }
      fromStream(inputStream, optionsOrCallback = {}, callback) {
        let options = {};
        if (typeof optionsOrCallback === "function") {
          callback = optionsOrCallback;
        } else {
          options = optionsOrCallback;
        }
        if (callback) {
          this.fromStreamAsync(inputStream, options).then((r2) => callback(null, r2), callback);
        } else {
          return this.fromStreamAsync(inputStream, options);
        }
      }
      fromStreamAsync(inputStream, options) {
        return new Promise((resolve2, reject) => {
          if (!inputStream) {
            throw new Error("Must pass in a stream containing the Google auth settings.");
          }
          const chunks = [];
          inputStream.setEncoding("utf8").on("error", reject).on("data", (chunk) => chunks.push(chunk)).on("end", () => {
            try {
              try {
                const data = JSON.parse(chunks.join(""));
                const r2 = this._cacheClientFromJSON(data, options);
                return resolve2(r2);
              } catch (err) {
                if (!this.keyFilename)
                  throw err;
                const client = new jwtclient_1.JWT({
                  ...this.clientOptions,
                  keyFile: this.keyFilename
                });
                this.cachedCredential = client;
                this.setGapicJWTValues(client);
                return resolve2(client);
              }
            } catch (err) {
              return reject(err);
            }
          });
        });
      }
      /**
       * Create a credentials instance using the given API key string.
       * The created client is not cached. In order to create and cache it use the {@link GoogleAuth.getClient `getClient`} method after first providing an {@link GoogleAuth.apiKey `apiKey`}.
       *
       * @param apiKey The API key string
       * @param options An optional options object.
       * @returns A JWT loaded from the key
       */
      fromAPIKey(apiKey, options = {}) {
        return new jwtclient_1.JWT({ ...options, apiKey });
      }
      /**
       * Determines whether the current operating system is Windows.
       * @api private
       */
      _isWindows() {
        const sys = os.platform();
        if (sys && sys.length >= 3) {
          if (sys.substring(0, 3).toLowerCase() === "win") {
            return true;
          }
        }
        return false;
      }
      /**
       * Run the Google Cloud SDK command that prints the default project ID
       */
      async getDefaultServiceProjectId() {
        return new Promise((resolve2) => {
          (0, child_process_1.exec)("gcloud config config-helper --format json", (err, stdout) => {
            if (!err && stdout) {
              try {
                const projectId = JSON.parse(stdout).configuration.properties.core.project;
                resolve2(projectId);
                return;
              } catch (e2) {
              }
            }
            resolve2(null);
          });
        });
      }
      /**
       * Loads the project id from environment variables.
       * @api private
       */
      getProductionProjectId() {
        return process.env["GCLOUD_PROJECT"] || process.env["GOOGLE_CLOUD_PROJECT"] || process.env["gcloud_project"] || process.env["google_cloud_project"];
      }
      /**
       * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file.
       * @api private
       */
      async getFileProjectId() {
        if (this.cachedCredential) {
          return this.cachedCredential.projectId;
        }
        if (this.keyFilename) {
          const creds = await this.getClient();
          if (creds && creds.projectId) {
            return creds.projectId;
          }
        }
        const r2 = await this._tryGetApplicationCredentialsFromEnvironmentVariable();
        if (r2) {
          return r2.projectId;
        } else {
          return null;
        }
      }
      /**
       * Gets the project ID from external account client if available.
       */
      async getExternalAccountClientProjectId() {
        if (!this.jsonContent || this.jsonContent.type !== baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {
          return null;
        }
        const creds = await this.getClient();
        return await creds.getProjectId();
      }
      /**
       * Gets the Compute Engine project ID if it can be inferred.
       */
      async getGCEProjectId() {
        try {
          const r2 = await gcpMetadata.project("project-id");
          return r2;
        } catch (e2) {
          return null;
        }
      }
      getCredentials(callback) {
        if (callback) {
          this.getCredentialsAsync().then((r2) => callback(null, r2), callback);
        } else {
          return this.getCredentialsAsync();
        }
      }
      async getCredentialsAsync() {
        const client = await this.getClient();
        if (client instanceof impersonated_1.Impersonated) {
          return { client_email: client.getTargetPrincipal() };
        }
        if (client instanceof baseexternalclient_1.BaseExternalAccountClient) {
          const serviceAccountEmail = client.getServiceAccountEmail();
          if (serviceAccountEmail) {
            return {
              client_email: serviceAccountEmail,
              universe_domain: client.universeDomain
            };
          }
        }
        if (this.jsonContent) {
          return {
            client_email: this.jsonContent.client_email,
            private_key: this.jsonContent.private_key,
            universe_domain: this.jsonContent.universe_domain
          };
        }
        if (await this._checkIsGCE()) {
          const [client_email, universe_domain] = await Promise.all([
            gcpMetadata.instance("service-accounts/default/email"),
            this.getUniverseDomain()
          ]);
          return { client_email, universe_domain };
        }
        throw new Error(exports2.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND);
      }
      /**
       * Automatically obtain an {@link AuthClient `AuthClient`} based on the
       * provided configuration. If no options were passed, use Application
       * Default Credentials.
       */
      async getClient() {
        if (this.cachedCredential) {
          return this.cachedCredential;
        }
        this.#pendingAuthClient = this.#pendingAuthClient || this.#determineClient();
        try {
          return await this.#pendingAuthClient;
        } finally {
          this.#pendingAuthClient = null;
        }
      }
      async #determineClient() {
        if (this.jsonContent) {
          return this._cacheClientFromJSON(this.jsonContent, this.clientOptions);
        } else if (this.keyFilename) {
          const filePath = path.resolve(this.keyFilename);
          const stream = fs2.createReadStream(filePath);
          return await this.fromStreamAsync(stream, this.clientOptions);
        } else if (this.apiKey) {
          const client = await this.fromAPIKey(this.apiKey, this.clientOptions);
          client.scopes = this.scopes;
          const { credential } = await this.#prepareAndCacheClient(client);
          return credential;
        } else {
          const { credential } = await this.getApplicationDefaultAsync(this.clientOptions);
          return credential;
        }
      }
      /**
       * Creates a client which will fetch an ID token for authorization.
       * @param targetAudience the audience for the fetched ID token.
       * @returns IdTokenClient for making HTTP calls authenticated with ID tokens.
       */
      async getIdTokenClient(targetAudience) {
        const client = await this.getClient();
        if (!("fetchIdToken" in client)) {
          throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");
        }
        return new idtokenclient_1.IdTokenClient({ targetAudience, idTokenProvider: client });
      }
      /**
       * Automatically obtain application default credentials, and return
       * an access token for making requests.
       */
      async getAccessToken() {
        const client = await this.getClient();
        return (await client.getAccessToken()).token;
      }
      /**
       * Obtain the HTTP headers that will provide authorization for a given
       * request.
       */
      async getRequestHeaders(url2) {
        const client = await this.getClient();
        return client.getRequestHeaders(url2);
      }
      /**
       * Obtain credentials for a request, then attach the appropriate headers to
       * the request options.
       * @param opts Axios or Request options on which to attach the headers
       */
      async authorizeRequest(opts = {}) {
        const url2 = opts.url;
        const client = await this.getClient();
        const headers = await client.getRequestHeaders(url2);
        opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, headers);
        return opts;
      }
      /**
       * A {@link fetch `fetch`} compliant API for {@link GoogleAuth}.
       *
       * @see {@link GoogleAuth.request} for the classic method.
       *
       * @remarks
       *
       * This is useful as a drop-in replacement for `fetch` API usage.
       *
       * @example
       *
       * ```ts
       * const auth = new GoogleAuth();
       * const fetchWithAuth: typeof fetch = (...args) => auth.fetch(...args);
       * await fetchWithAuth('https://example.com');
       * ```
       *
       * @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters
       * @returns the {@link GaxiosResponse} with Gaxios-added properties
       */
      async fetch(...args) {
        const client = await this.getClient();
        return client.fetch(...args);
      }
      /**
       * Automatically obtain application default credentials, and make an
       * HTTP request using the given options.
       *
       * @see {@link GoogleAuth.fetch} for the modern method.
       *
       * @param opts Axios request options for the HTTP request.
       */
      async request(opts) {
        const client = await this.getClient();
        return client.request(opts);
      }
      /**
       * Determine the compute environment in which the code is running.
       */
      getEnv() {
        return (0, envDetect_1.getEnv)();
      }
      /**
       * Sign the given data with the current private key, or go out
       * to the IAM API to sign it.
       * @param data The data to be signed.
       * @param endpoint A custom endpoint to use.
       *
       * @example
       * ```
       * sign('data', 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/');
       * ```
       */
      async sign(data, endpoint) {
        const client = await this.getClient();
        const universe = await this.getUniverseDomain();
        endpoint = endpoint || `https://iamcredentials.${universe}/v1/projects/-/serviceAccounts/`;
        if (client instanceof impersonated_1.Impersonated) {
          const signed = await client.sign(data);
          return signed.signedBlob;
        }
        const crypto2 = (0, crypto_1.createCrypto)();
        if (client instanceof jwtclient_1.JWT && client.key) {
          const sign = await crypto2.sign(client.key, data);
          return sign;
        }
        const creds = await this.getCredentials();
        if (!creds.client_email) {
          throw new Error("Cannot sign data without `client_email`.");
        }
        return this.signBlob(crypto2, creds.client_email, data, endpoint);
      }
      async signBlob(crypto2, emailOrUniqueId, data, endpoint) {
        const url2 = new URL(endpoint + `${emailOrUniqueId}:signBlob`);
        const res = await this.request({
          method: "POST",
          url: url2.href,
          data: {
            payload: crypto2.encodeBase64StringUtf8(data)
          },
          retry: true,
          retryConfig: {
            httpMethodsToRetry: ["POST"]
          }
        });
        return res.data.signedBlob;
      }
    };
    exports2.GoogleAuth = GoogleAuth;
  }
});

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

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

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

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

// node_modules/googleapis-common/build/src/apiIndex.js
var require_apiIndex = __commonJS({
  "node_modules/googleapis-common/build/src/apiIndex.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getAPI = getAPI;
    function getAPI(api, options, versions, context) {
      let version2;
      if (typeof options === "string") {
        version2 = options;
        options = {};
      } else if (typeof options === "object") {
        version2 = options.version;
        delete options.version;
      } else {
        throw new Error("Argument error: Accepts only string or object");
      }
      try {
        const ctr = versions[version2];
        const ep = new ctr(options, context);
        return Object.freeze(ep);
      } catch (e2) {
        throw new Error(`Unable to load endpoint ${api}("${version2}"): ${e2.message}`);
      }
    }
  }
});

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

// node_modules/object-inspect/util.inspect.js
var require_util_inspect = __commonJS({
  "node_modules/object-inspect/util.inspect.js"(exports2, module2) {
    module2.exports = require("util").inspect;
  }
});

// node_modules/object-inspect/index.js
var require_object_inspect = __commonJS({
  "node_modules/object-inspect/index.js"(exports2, module2) {
    var hasMap = typeof Map === "function" && Map.prototype;
    var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, "size") : null;
    var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === "function" ? mapSizeDescriptor.get : null;
    var mapForEach = hasMap && Map.prototype.forEach;
    var hasSet = typeof Set === "function" && Set.prototype;
    var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, "size") : null;
    var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === "function" ? setSizeDescriptor.get : null;
    var setForEach = hasSet && Set.prototype.forEach;
    var hasWeakMap = typeof WeakMap === "function" && WeakMap.prototype;
    var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
    var hasWeakSet = typeof WeakSet === "function" && WeakSet.prototype;
    var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
    var hasWeakRef = typeof WeakRef === "function" && WeakRef.prototype;
    var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;
    var booleanValueOf = Boolean.prototype.valueOf;
    var objectToString = Object.prototype.toString;
    var functionToString = Function.prototype.toString;
    var $match = String.prototype.match;
    var $slice = String.prototype.slice;
    var $replace = String.prototype.replace;
    var $toUpperCase = String.prototype.toUpperCase;
    var $toLowerCase = String.prototype.toLowerCase;
    var $test = RegExp.prototype.test;
    var $concat = Array.prototype.concat;
    var $join = Array.prototype.join;
    var $arrSlice = Array.prototype.slice;
    var $floor = Math.floor;
    var bigIntValueOf = typeof BigInt === "function" ? BigInt.prototype.valueOf : null;
    var gOPS = Object.getOwnPropertySymbols;
    var symToString = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol.prototype.toString : null;
    var hasShammedSymbols = typeof Symbol === "function" && typeof Symbol.iterator === "object";
    var toStringTag = typeof Symbol === "function" && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? "object" : "symbol") ? Symbol.toStringTag : null;
    var isEnumerable = Object.prototype.propertyIsEnumerable;
    var gPO = (typeof Reflect === "function" ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype ? function(O) {
      return O.__proto__;
    } : null);
    function addNumericSeparator(num, str) {
      if (num === Infinity || num === -Infinity || num !== num || num && num > -1e3 && num < 1e3 || $test.call(/e/, str)) {
        return str;
      }
      var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;
      if (typeof num === "number") {
        var int2 = num < 0 ? -$floor(-num) : $floor(num);
        if (int2 !== num) {
          var intStr = String(int2);
          var dec = $slice.call(str, intStr.length + 1);
          return $replace.call(intStr, sepRegex, "$&_") + "." + $replace.call($replace.call(dec, /([0-9]{3})/g, "$&_"), /_$/, "");
        }
      }
      return $replace.call(str, sepRegex, "$&_");
    }
    var utilInspect = require_util_inspect();
    var inspectCustom = utilInspect.custom;
    var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null;
    var quotes = {
      __proto__: null,
      "double": '"',
      single: "'"
    };
    var quoteREs = {
      __proto__: null,
      "double": /(["\\])/g,
      single: /(['\\])/g
    };
    module2.exports = function inspect_(obj, options, depth, seen) {
      var opts = options || {};
      if (has(opts, "quoteStyle") && !has(quotes, opts.quoteStyle)) {
        throw new TypeError('option "quoteStyle" must be "single" or "double"');
      }
      if (has(opts, "maxStringLength") && (typeof opts.maxStringLength === "number" ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null)) {
        throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');
      }
      var customInspect = has(opts, "customInspect") ? opts.customInspect : true;
      if (typeof customInspect !== "boolean" && customInspect !== "symbol") {
        throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");
      }
      if (has(opts, "indent") && opts.indent !== null && opts.indent !== "	" && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)) {
        throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');
      }
      if (has(opts, "numericSeparator") && typeof opts.numericSeparator !== "boolean") {
        throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');
      }
      var numericSeparator = opts.numericSeparator;
      if (typeof obj === "undefined") {
        return "undefined";
      }
      if (obj === null) {
        return "null";
      }
      if (typeof obj === "boolean") {
        return obj ? "true" : "false";
      }
      if (typeof obj === "string") {
        return inspectString(obj, opts);
      }
      if (typeof obj === "number") {
        if (obj === 0) {
          return Infinity / obj > 0 ? "0" : "-0";
        }
        var str = String(obj);
        return numericSeparator ? addNumericSeparator(obj, str) : str;
      }
      if (typeof obj === "bigint") {
        var bigIntStr = String(obj) + "n";
        return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr;
      }
      var maxDepth = typeof opts.depth === "undefined" ? 5 : opts.depth;
      if (typeof depth === "undefined") {
        depth = 0;
      }
      if (depth >= maxDepth && maxDepth > 0 && typeof obj === "object") {
        return isArray(obj) ? "[Array]" : "[Object]";
      }
      var indent = getIndent(opts, depth);
      if (typeof seen === "undefined") {
        seen = [];
      } else if (indexOf(seen, obj) >= 0) {
        return "[Circular]";
      }
      function inspect(value, from, noIndent) {
        if (from) {
          seen = $arrSlice.call(seen);
          seen.push(from);
        }
        if (noIndent) {
          var newOpts = {
            depth: opts.depth
          };
          if (has(opts, "quoteStyle")) {
            newOpts.quoteStyle = opts.quoteStyle;
          }
          return inspect_(value, newOpts, depth + 1, seen);
        }
        return inspect_(value, opts, depth + 1, seen);
      }
      if (typeof obj === "function" && !isRegExp(obj)) {
        var name = nameOf(obj);
        var keys = arrObjKeys(obj, inspect);
        return "[Function" + (name ? ": " + name : " (anonymous)") + "]" + (keys.length > 0 ? " { " + $join.call(keys, ", ") + " }" : "");
      }
      if (isSymbol(obj)) {
        var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, "$1") : symToString.call(obj);
        return typeof obj === "object" && !hasShammedSymbols ? markBoxed(symString) : symString;
      }
      if (isElement(obj)) {
        var s2 = "<" + $toLowerCase.call(String(obj.nodeName));
        var attrs = obj.attributes || [];
        for (var i2 = 0; i2 < attrs.length; i2++) {
          s2 += " " + attrs[i2].name + "=" + wrapQuotes(quote(attrs[i2].value), "double", opts);
        }
        s2 += ">";
        if (obj.childNodes && obj.childNodes.length) {
          s2 += "...";
        }
        s2 += "</" + $toLowerCase.call(String(obj.nodeName)) + ">";
        return s2;
      }
      if (isArray(obj)) {
        if (obj.length === 0) {
          return "[]";
        }
        var xs = arrObjKeys(obj, inspect);
        if (indent && !singleLineValues(xs)) {
          return "[" + indentedJoin(xs, indent) + "]";
        }
        return "[ " + $join.call(xs, ", ") + " ]";
      }
      if (isError(obj)) {
        var parts = arrObjKeys(obj, inspect);
        if (!("cause" in Error.prototype) && "cause" in obj && !isEnumerable.call(obj, "cause")) {
          return "{ [" + String(obj) + "] " + $join.call($concat.call("[cause]: " + inspect(obj.cause), parts), ", ") + " }";
        }
        if (parts.length === 0) {
          return "[" + String(obj) + "]";
        }
        return "{ [" + String(obj) + "] " + $join.call(parts, ", ") + " }";
      }
      if (typeof obj === "object" && customInspect) {
        if (inspectSymbol && typeof obj[inspectSymbol] === "function" && utilInspect) {
          return utilInspect(obj, { depth: maxDepth - depth });
        } else if (customInspect !== "symbol" && typeof obj.inspect === "function") {
          return obj.inspect();
        }
      }
      if (isMap(obj)) {
        var mapParts = [];
        if (mapForEach) {
          mapForEach.call(obj, function(value, key) {
            mapParts.push(inspect(key, obj, true) + " => " + inspect(value, obj));
          });
        }
        return collectionOf("Map", mapSize.call(obj), mapParts, indent);
      }
      if (isSet(obj)) {
        var setParts = [];
        if (setForEach) {
          setForEach.call(obj, function(value) {
            setParts.push(inspect(value, obj));
          });
        }
        return collectionOf("Set", setSize.call(obj), setParts, indent);
      }
      if (isWeakMap(obj)) {
        return weakCollectionOf("WeakMap");
      }
      if (isWeakSet(obj)) {
        return weakCollectionOf("WeakSet");
      }
      if (isWeakRef(obj)) {
        return weakCollectionOf("WeakRef");
      }
      if (isNumber(obj)) {
        return markBoxed(inspect(Number(obj)));
      }
      if (isBigInt(obj)) {
        return markBoxed(inspect(bigIntValueOf.call(obj)));
      }
      if (isBoolean(obj)) {
        return markBoxed(booleanValueOf.call(obj));
      }
      if (isString(obj)) {
        return markBoxed(inspect(String(obj)));
      }
      if (typeof window !== "undefined" && obj === window) {
        return "{ [object Window] }";
      }
      if (typeof globalThis !== "undefined" && obj === globalThis || typeof global !== "undefined" && obj === global) {
        return "{ [object globalThis] }";
      }
      if (!isDate(obj) && !isRegExp(obj)) {
        var ys = arrObjKeys(obj, inspect);
        var isPlainObject3 = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object;
        var protoTag = obj instanceof Object ? "" : "null prototype";
        var stringTag = !isPlainObject3 && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? "Object" : "";
        var constructorTag = isPlainObject3 || typeof obj.constructor !== "function" ? "" : obj.constructor.name ? obj.constructor.name + " " : "";
        var tag = constructorTag + (stringTag || protoTag ? "[" + $join.call($concat.call([], stringTag || [], protoTag || []), ": ") + "] " : "");
        if (ys.length === 0) {
          return tag + "{}";
        }
        if (indent) {
          return tag + "{" + indentedJoin(ys, indent) + "}";
        }
        return tag + "{ " + $join.call(ys, ", ") + " }";
      }
      return String(obj);
    };
    function wrapQuotes(s2, defaultStyle, opts) {
      var style = opts.quoteStyle || defaultStyle;
      var quoteChar = quotes[style];
      return quoteChar + s2 + quoteChar;
    }
    function quote(s2) {
      return $replace.call(String(s2), /"/g, "&quot;");
    }
    function canTrustToString(obj) {
      return !toStringTag || !(typeof obj === "object" && (toStringTag in obj || typeof obj[toStringTag] !== "undefined"));
    }
    function isArray(obj) {
      return toStr(obj) === "[object Array]" && canTrustToString(obj);
    }
    function isDate(obj) {
      return toStr(obj) === "[object Date]" && canTrustToString(obj);
    }
    function isRegExp(obj) {
      return toStr(obj) === "[object RegExp]" && canTrustToString(obj);
    }
    function isError(obj) {
      return toStr(obj) === "[object Error]" && canTrustToString(obj);
    }
    function isString(obj) {
      return toStr(obj) === "[object String]" && canTrustToString(obj);
    }
    function isNumber(obj) {
      return toStr(obj) === "[object Number]" && canTrustToString(obj);
    }
    function isBoolean(obj) {
      return toStr(obj) === "[object Boolean]" && canTrustToString(obj);
    }
    function isSymbol(obj) {
      if (hasShammedSymbols) {
        return obj && typeof obj === "object" && obj instanceof Symbol;
      }
      if (typeof obj === "symbol") {
        return true;
      }
      if (!obj || typeof obj !== "object" || !symToString) {
        return false;
      }
      try {
        symToString.call(obj);
        return true;
      } catch (e2) {
      }
      return false;
    }
    function isBigInt(obj) {
      if (!obj || typeof obj !== "object" || !bigIntValueOf) {
        return false;
      }
      try {
        bigIntValueOf.call(obj);
        return true;
      } catch (e2) {
      }
      return false;
    }
    var hasOwn = Object.prototype.hasOwnProperty || function(key) {
      return key in this;
    };
    function has(obj, key) {
      return hasOwn.call(obj, key);
    }
    function toStr(obj) {
      return objectToString.call(obj);
    }
    function nameOf(f3) {
      if (f3.name) {
        return f3.name;
      }
      var m2 = $match.call(functionToString.call(f3), /^function\s*([\w$]+)/);
      if (m2) {
        return m2[1];
      }
      return null;
    }
    function indexOf(xs, x2) {
      if (xs.indexOf) {
        return xs.indexOf(x2);
      }
      for (var i2 = 0, l = xs.length; i2 < l; i2++) {
        if (xs[i2] === x2) {
          return i2;
        }
      }
      return -1;
    }
    function isMap(x2) {
      if (!mapSize || !x2 || typeof x2 !== "object") {
        return false;
      }
      try {
        mapSize.call(x2);
        try {
          setSize.call(x2);
        } catch (s2) {
          return true;
        }
        return x2 instanceof Map;
      } catch (e2) {
      }
      return false;
    }
    function isWeakMap(x2) {
      if (!weakMapHas || !x2 || typeof x2 !== "object") {
        return false;
      }
      try {
        weakMapHas.call(x2, weakMapHas);
        try {
          weakSetHas.call(x2, weakSetHas);
        } catch (s2) {
          return true;
        }
        return x2 instanceof WeakMap;
      } catch (e2) {
      }
      return false;
    }
    function isWeakRef(x2) {
      if (!weakRefDeref || !x2 || typeof x2 !== "object") {
        return false;
      }
      try {
        weakRefDeref.call(x2);
        return true;
      } catch (e2) {
      }
      return false;
    }
    function isSet(x2) {
      if (!setSize || !x2 || typeof x2 !== "object") {
        return false;
      }
      try {
        setSize.call(x2);
        try {
          mapSize.call(x2);
        } catch (m2) {
          return true;
        }
        return x2 instanceof Set;
      } catch (e2) {
      }
      return false;
    }
    function isWeakSet(x2) {
      if (!weakSetHas || !x2 || typeof x2 !== "object") {
        return false;
      }
      try {
        weakSetHas.call(x2, weakSetHas);
        try {
          weakMapHas.call(x2, weakMapHas);
        } catch (s2) {
          return true;
        }
        return x2 instanceof WeakSet;
      } catch (e2) {
      }
      return false;
    }
    function isElement(x2) {
      if (!x2 || typeof x2 !== "object") {
        return false;
      }
      if (typeof HTMLElement !== "undefined" && x2 instanceof HTMLElement) {
        return true;
      }
      return typeof x2.nodeName === "string" && typeof x2.getAttribute === "function";
    }
    function inspectString(str, opts) {
      if (str.length > opts.maxStringLength) {
        var remaining = str.length - opts.maxStringLength;
        var trailer = "... " + remaining + " more character" + (remaining > 1 ? "s" : "");
        return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer;
      }
      var quoteRE = quoteREs[opts.quoteStyle || "single"];
      quoteRE.lastIndex = 0;
      var s2 = $replace.call($replace.call(str, quoteRE, "\\$1"), /[\x00-\x1f]/g, lowbyte);
      return wrapQuotes(s2, "single", opts);
    }
    function lowbyte(c) {
      var n = c.charCodeAt(0);
      var x2 = {
        8: "b",
        9: "t",
        10: "n",
        12: "f",
        13: "r"
      }[n];
      if (x2) {
        return "\\" + x2;
      }
      return "\\x" + (n < 16 ? "0" : "") + $toUpperCase.call(n.toString(16));
    }
    function markBoxed(str) {
      return "Object(" + str + ")";
    }
    function weakCollectionOf(type) {
      return type + " { ? }";
    }
    function collectionOf(type, size, entries, indent) {
      var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ", ");
      return type + " (" + size + ") {" + joinedEntries + "}";
    }
    function singleLineValues(xs) {
      for (var i2 = 0; i2 < xs.length; i2++) {
        if (indexOf(xs[i2], "\n") >= 0) {
          return false;
        }
      }
      return true;
    }
    function getIndent(opts, depth) {
      var baseIndent;
      if (opts.indent === "	") {
        baseIndent = "	";
      } else if (typeof opts.indent === "number" && opts.indent > 0) {
        baseIndent = $join.call(Array(opts.indent + 1), " ");
      } else {
        return null;
      }
      return {
        base: baseIndent,
        prev: $join.call(Array(depth + 1), baseIndent)
      };
    }
    function indentedJoin(xs, indent) {
      if (xs.length === 0) {
        return "";
      }
      var lineJoiner = "\n" + indent.prev + indent.base;
      return lineJoiner + $join.call(xs, "," + lineJoiner) + "\n" + indent.prev;
    }
    function arrObjKeys(obj, inspect) {
      var isArr = isArray(obj);
      var xs = [];
      if (isArr) {
        xs.length = obj.length;
        for (var i2 = 0; i2 < obj.length; i2++) {
          xs[i2] = has(obj, i2) ? inspect(obj[i2], obj) : "";
        }
      }
      var syms = typeof gOPS === "function" ? gOPS(obj) : [];
      var symMap;
      if (hasShammedSymbols) {
        symMap = {};
        for (var k = 0; k < syms.length; k++) {
          symMap["$" + syms[k]] = syms[k];
        }
      }
      for (var key in obj) {
        if (!has(obj, key)) {
          continue;
        }
        if (isArr && String(Number(key)) === key && key < obj.length) {
          continue;
        }
        if (hasShammedSymbols && symMap["$" + key] instanceof Symbol) {
          continue;
        } else if ($test.call(/[^\w$]/, key)) {
          xs.push(inspect(key, obj) + ": " + inspect(obj[key], obj));
        } else {
          xs.push(key + ": " + inspect(obj[key], obj));
        }
      }
      if (typeof gOPS === "function") {
        for (var j = 0; j < syms.length; j++) {
          if (isEnumerable.call(obj, syms[j])) {
            xs.push("[" + inspect(syms[j]) + "]: " + inspect(obj[syms[j]], obj));
          }
        }
      }
      return xs;
    }
  }
});

// node_modules/side-channel-list/index.js
var require_side_channel_list = __commonJS({
  "node_modules/side-channel-list/index.js"(exports2, module2) {
    "use strict";
    var inspect = require_object_inspect();
    var $TypeError = require_type();
    var listGetNode = function(list, key, isDelete) {
      var prev = list;
      var curr;
      for (; (curr = prev.next) != null; prev = curr) {
        if (curr.key === key) {
          prev.next = curr.next;
          if (!isDelete) {
            curr.next = /** @type {NonNullable<typeof list.next>} */
            list.next;
            list.next = curr;
          }
          return curr;
        }
      }
    };
    var listGet = function(objects, key) {
      if (!objects) {
        return void 0;
      }
      var node = listGetNode(objects, key);
      return node && node.value;
    };
    var listSet = function(objects, key, value) {
      var node = listGetNode(objects, key);
      if (node) {
        node.value = value;
      } else {
        objects.next = /** @type {import('./list.d.ts').ListNode<typeof value, typeof key>} */
        {
          // eslint-disable-line no-param-reassign, no-extra-parens
          key,
          next: objects.next,
          value
        };
      }
    };
    var listHas = function(objects, key) {
      if (!objects) {
        return false;
      }
      return !!listGetNode(objects, key);
    };
    var listDelete = function(objects, key) {
      if (objects) {
        return listGetNode(objects, key, true);
      }
    };
    module2.exports = function getSideChannelList() {
      var $o;
      var channel = {
        assert: function(key) {
          if (!channel.has(key)) {
            throw new $TypeError("Side channel does not contain " + inspect(key));
          }
        },
        "delete": function(key) {
          var deletedNode = listDelete($o, key);
          if (deletedNode && $o && !$o.next) {
            $o = void 0;
          }
          return !!deletedNode;
        },
        get: function(key) {
          return listGet($o, key);
        },
        has: function(key) {
          return listHas($o, key);
        },
        set: function(key, value) {
          if (!$o) {
            $o = {
              next: void 0
            };
          }
          listSet(
            /** @type {NonNullable<typeof $o>} */
            $o,
            key,
            value
          );
        }
      };
      return channel;
    };
  }
});

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// node_modules/function-bind/implementation.js
var require_implementation = __commonJS({
  "node_modules/function-bind/implementation.js"(exports2, module2) {
    "use strict";
    var ERROR_MESSAGE = "Function.prototype.bind called on incompatible ";
    var toStr = Object.prototype.toString;
    var max = Math.max;
    var funcType = "[object Function]";
    var concatty = function concatty2(a, b) {
      var arr = [];
      for (var i2 = 0; i2 < a.length; i2 += 1) {
        arr[i2] = a[i2];
      }
      for (var j = 0; j < b.length; j += 1) {
        arr[j + a.length] = b[j];
      }
      return arr;
    };
    var slicy = function slicy2(arrLike, offset) {
      var arr = [];
      for (var i2 = offset || 0, j = 0; i2 < arrLike.length; i2 += 1, j += 1) {
        arr[j] = arrLike[i2];
      }
      return arr;
    };
    var joiny = function(arr, joiner) {
      var str = "";
      for (var i2 = 0; i2 < arr.length; i2 += 1) {
        str += arr[i2];
        if (i2 + 1 < arr.length) {
          str += joiner;
        }
      }
      return str;
    };
    module2.exports = function bind(that) {
      var target = this;
      if (typeof target !== "function" || toStr.apply(target) !== funcType) {
        throw new TypeError(ERROR_MESSAGE + target);
      }
      var args = slicy(arguments, 1);
      var bound;
      var binder = function() {
        if (this instanceof bound) {
          var result = target.apply(
            this,
            concatty(args, arguments)
          );
          if (Object(result) === result) {
            return result;
          }
          return this;
        }
        return target.apply(
          that,
          concatty(args, arguments)
        );
      };
      var boundLength = max(0, target.length - args.length);
      var boundArgs = [];
      for (var i2 = 0; i2 < boundLength; i2++) {
        boundArgs[i2] = "$" + i2;
      }
      bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder);
      if (target.prototype) {
        var Empty = function Empty2() {
        };
        Empty.prototype = target.prototype;
        bound.prototype = new Empty();
        Empty.prototype = null;
      }
      return bound;
    };
  }
});

// node_modules/function-bind/index.js
var require_function_bind = __commonJS({
  "node_modules/function-bind/index.js"(exports2, module2) {
    "use strict";
    var implementation = require_implementation();
    module2.exports = Function.prototype.bind || implementation;
  }
});

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

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

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

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

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

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

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

// node_modules/hasown/index.js
var require_hasown = __commonJS({
  "node_modules/hasown/index.js"(exports2, module2) {
    "use strict";
    var call = Function.prototype.call;
    var $hasOwn = Object.prototype.hasOwnProperty;
    var bind = require_function_bind();
    module2.exports = bind.call(call, $hasOwn);
  }
});

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

// node_modules/call-bound/index.js
var require_call_bound = __commonJS({
  "node_modules/call-bound/index.js"(exports2, module2) {
    "use strict";
    var GetIntrinsic = require_get_intrinsic();
    var callBindBasic = require_call_bind_apply_helpers();
    var $indexOf = callBindBasic([GetIntrinsic("%String.prototype.indexOf%")]);
    module2.exports = function callBoundIntrinsic(name, allowMissing) {
      var intrinsic = (
        /** @type {(this: unknown, ...args: unknown[]) => unknown} */
        GetIntrinsic(name, !!allowMissing)
      );
      if (typeof intrinsic === "function" && $indexOf(name, ".prototype.") > -1) {
        return callBindBasic(
          /** @type {const} */
          [intrinsic]
        );
      }
      return intrinsic;
    };
  }
});

// node_modules/side-channel-map/index.js
var require_side_channel_map = __commonJS({
  "node_modules/side-channel-map/index.js"(exports2, module2) {
    "use strict";
    var GetIntrinsic = require_get_intrinsic();
    var callBound = require_call_bound();
    var inspect = require_object_inspect();
    var $TypeError = require_type();
    var $Map = GetIntrinsic("%Map%", true);
    var $mapGet = callBound("Map.prototype.get", true);
    var $mapSet = callBound("Map.prototype.set", true);
    var $mapHas = callBound("Map.prototype.has", true);
    var $mapDelete = callBound("Map.prototype.delete", true);
    var $mapSize = callBound("Map.prototype.size", true);
    module2.exports = !!$Map && /** @type {Exclude<import('.'), false>} */
    function getSideChannelMap() {
      var $m;
      var channel = {
        assert: function(key) {
          if (!channel.has(key)) {
            throw new $TypeError("Side channel does not contain " + inspect(key));
          }
        },
        "delete": function(key) {
          if ($m) {
            var result = $mapDelete($m, key);
            if ($mapSize($m) === 0) {
              $m = void 0;
            }
            return result;
          }
          return false;
        },
        get: function(key) {
          if ($m) {
            return $mapGet($m, key);
          }
        },
        has: function(key) {
          if ($m) {
            return $mapHas($m, key);
          }
          return false;
        },
        set: function(key, value) {
          if (!$m) {
            $m = new $Map();
          }
          $mapSet($m, key, value);
        }
      };
      return channel;
    };
  }
});

// node_modules/side-channel-weakmap/index.js
var require_side_channel_weakmap = __commonJS({
  "node_modules/side-channel-weakmap/index.js"(exports2, module2) {
    "use strict";
    var GetIntrinsic = require_get_intrinsic();
    var callBound = require_call_bound();
    var inspect = require_object_inspect();
    var getSideChannelMap = require_side_channel_map();
    var $TypeError = require_type();
    var $WeakMap = GetIntrinsic("%WeakMap%", true);
    var $weakMapGet = callBound("WeakMap.prototype.get", true);
    var $weakMapSet = callBound("WeakMap.prototype.set", true);
    var $weakMapHas = callBound("WeakMap.prototype.has", true);
    var $weakMapDelete = callBound("WeakMap.prototype.delete", true);
    module2.exports = $WeakMap ? (
      /** @type {Exclude<import('.'), false>} */
      function getSideChannelWeakMap() {
        var $wm;
        var $m;
        var channel = {
          assert: function(key) {
            if (!channel.has(key)) {
              throw new $TypeError("Side channel does not contain " + inspect(key));
            }
          },
          "delete": function(key) {
            if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
              if ($wm) {
                return $weakMapDelete($wm, key);
              }
            } else if (getSideChannelMap) {
              if ($m) {
                return $m["delete"](key);
              }
            }
            return false;
          },
          get: function(key) {
            if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
              if ($wm) {
                return $weakMapGet($wm, key);
              }
            }
            return $m && $m.get(key);
          },
          has: function(key) {
            if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
              if ($wm) {
                return $weakMapHas($wm, key);
              }
            }
            return !!$m && $m.has(key);
          },
          set: function(key, value) {
            if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
              if (!$wm) {
                $wm = new $WeakMap();
              }
              $weakMapSet($wm, key, value);
            } else if (getSideChannelMap) {
              if (!$m) {
                $m = getSideChannelMap();
              }
              $m.set(key, value);
            }
          }
        };
        return channel;
      }
    ) : getSideChannelMap;
  }
});

// node_modules/side-channel/index.js
var require_side_channel = __commonJS({
  "node_modules/side-channel/index.js"(exports2, module2) {
    "use strict";
    var $TypeError = require_type();
    var inspect = require_object_inspect();
    var getSideChannelList = require_side_channel_list();
    var getSideChannelMap = require_side_channel_map();
    var getSideChannelWeakMap = require_side_channel_weakmap();
    var makeChannel = getSideChannelWeakMap || getSideChannelMap || getSideChannelList;
    module2.exports = function getSideChannel() {
      var $channelData;
      var channel = {
        assert: function(key) {
          if (!channel.has(key)) {
            var keyDesc = key && Object(key) === key ? "the given object key" : inspect(key);
            throw new $TypeError("Side channel does not contain " + keyDesc);
          }
        },
        "delete": function(key) {
          return !!$channelData && $channelData["delete"](key);
        },
        get: function(key) {
          return $channelData && $channelData.get(key);
        },
        has: function(key) {
          return !!$channelData && $channelData.has(key);
        },
        set: function(key, value) {
          if (!$channelData) {
            $channelData = makeChannel();
          }
          $channelData.set(key, value);
        }
      };
      return channel;
    };
  }
});

// node_modules/qs/lib/formats.js
var require_formats = __commonJS({
  "node_modules/qs/lib/formats.js"(exports2, module2) {
    "use strict";
    var replace = String.prototype.replace;
    var percentTwenties = /%20/g;
    var Format = {
      RFC1738: "RFC1738",
      RFC3986: "RFC3986"
    };
    module2.exports = {
      "default": Format.RFC3986,
      formatters: {
        RFC1738: function(value) {
          return replace.call(value, percentTwenties, "+");
        },
        RFC3986: function(value) {
          return String(value);
        }
      },
      RFC1738: Format.RFC1738,
      RFC3986: Format.RFC3986
    };
  }
});

// node_modules/qs/lib/utils.js
var require_utils3 = __commonJS({
  "node_modules/qs/lib/utils.js"(exports2, module2) {
    "use strict";
    var formats = require_formats();
    var getSideChannel = require_side_channel();
    var defineProperty = require_es_define_property();
    var has = Object.prototype.hasOwnProperty;
    var isArray = Array.isArray;
    var overflowChannel = getSideChannel();
    var markOverflow = function markOverflow2(obj, maxIndex) {
      overflowChannel.set(obj, maxIndex);
      return obj;
    };
    var isOverflow = function isOverflow2(obj) {
      return overflowChannel.has(obj);
    };
    var getMaxIndex = function getMaxIndex2(obj) {
      return overflowChannel.get(obj);
    };
    var setMaxIndex = function setMaxIndex2(obj, maxIndex) {
      overflowChannel.set(obj, maxIndex);
    };
    var hexTable = (function() {
      var array2 = [];
      for (var i2 = 0; i2 < 256; ++i2) {
        array2[array2.length] = "%" + ((i2 < 16 ? "0" : "") + i2.toString(16)).toUpperCase();
      }
      return array2;
    })();
    var compactQueue = function compactQueue2(queue) {
      while (queue.length > 1) {
        var item = queue.pop();
        var obj = item.obj[item.prop];
        if (isArray(obj)) {
          var compacted = [];
          for (var j = 0; j < obj.length; ++j) {
            if (typeof obj[j] !== "undefined") {
              compacted[compacted.length] = obj[j];
            }
          }
          item.obj[item.prop] = compacted;
        }
      }
    };
    var arrayToObject = function arrayToObject2(source, options) {
      var obj = options && options.plainObjects ? { __proto__: null } : {};
      for (var i2 = 0; i2 < source.length; ++i2) {
        if (typeof source[i2] !== "undefined") {
          obj[i2] = source[i2];
        }
      }
      return obj;
    };
    var setProperty = function setProperty2(obj, key, value) {
      if (key === "__proto__" && defineProperty) {
        defineProperty(obj, key, {
          configurable: true,
          enumerable: true,
          value,
          writable: true
        });
      } else {
        obj[key] = value;
      }
    };
    var merge2 = function merge3(target, source, options) {
      if (!source) {
        return target;
      }
      if (typeof source !== "object" && typeof source !== "function") {
        if (isArray(target)) {
          var nextIndex = target.length;
          if (options && typeof options.arrayLimit === "number" && nextIndex >= options.arrayLimit) {
            if (options.throwOnLimitExceeded) {
              throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array.");
            }
            return markOverflow(arrayToObject(target.concat(source), options), nextIndex);
          }
          target[nextIndex] = source;
        } else if (target && typeof target === "object") {
          if (isOverflow(target)) {
            var newIndex = getMaxIndex(target) + 1;
            target[newIndex] = source;
            setMaxIndex(target, newIndex);
          } else if (options && options.strictMerge) {
            return [target, source];
          } else if (options && (options.plainObjects || options.allowPrototypes) || !has.call(Object.prototype, source)) {
            target[source] = true;
          }
        } else {
          return [target, source];
        }
        return target;
      }
      if (!target || typeof target !== "object") {
        if (isOverflow(source)) {
          var sourceKeys = Object.keys(source);
          var result = options && options.plainObjects ? { __proto__: null, 0: target } : { 0: target };
          for (var m2 = 0; m2 < sourceKeys.length; m2++) {
            var oldKey = parseInt(sourceKeys[m2], 10);
            result[oldKey + 1] = source[sourceKeys[m2]];
          }
          return markOverflow(result, getMaxIndex(source) + 1);
        }
        var combined = [target].concat(source);
        if (options && typeof options.arrayLimit === "number" && combined.length > options.arrayLimit) {
          if (options.throwOnLimitExceeded) {
            throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array.");
          }
          return markOverflow(arrayToObject(combined, options), combined.length - 1);
        }
        return combined;
      }
      var mergeTarget = target;
      if (isArray(target) && !isArray(source)) {
        mergeTarget = arrayToObject(target, options);
      }
      if (isArray(target) && isArray(source)) {
        source.forEach(function(item, i2) {
          if (has.call(target, i2)) {
            var targetItem = target[i2];
            if (targetItem && typeof targetItem === "object" && item && typeof item === "object") {
              target[i2] = merge3(targetItem, item, options);
            } else {
              target[target.length] = item;
            }
          } else {
            target[i2] = item;
          }
        });
        if (options && typeof options.arrayLimit === "number" && target.length > options.arrayLimit) {
          if (options.throwOnLimitExceeded) {
            throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array.");
          }
          return markOverflow(arrayToObject(target, options), target.length - 1);
        }
        return target;
      }
      return Object.keys(source).reduce(function(acc, key) {
        var value = source[key];
        if (has.call(acc, key)) {
          setProperty(acc, key, merge3(acc[key], value, options));
        } else {
          setProperty(acc, key, value);
        }
        if (isOverflow(source) && !isOverflow(acc)) {
          markOverflow(acc, getMaxIndex(source));
        }
        if (isOverflow(acc)) {
          var keyNum = parseInt(key, 10);
          if (String(keyNum) === key && keyNum >= 0 && keyNum > getMaxIndex(acc)) {
            setMaxIndex(acc, keyNum);
          }
        }
        return acc;
      }, mergeTarget);
    };
    var assign = function assignSingleSource(target, source) {
      return Object.keys(source).reduce(function(acc, key) {
        setProperty(acc, key, source[key]);
        return acc;
      }, target);
    };
    var decode3 = function(str, defaultDecoder, charset) {
      var strWithoutPlus = str.replace(/\+/g, " ");
      if (charset === "iso-8859-1") {
        return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
      }
      try {
        return decodeURIComponent(strWithoutPlus);
      } catch (e2) {
        return strWithoutPlus;
      }
    };
    var limit = 1024;
    var encode3 = function encode4(str, defaultEncoder, charset, kind, format) {
      if (str.length === 0) {
        return str;
      }
      var string4 = str;
      if (typeof str === "symbol") {
        string4 = Symbol.prototype.toString.call(str);
      } else if (typeof str !== "string") {
        string4 = String(str);
      }
      if (charset === "iso-8859-1") {
        return escape(string4).replace(/%u[0-9a-f]{4}/gi, function($0) {
          return "%26%23" + parseInt($0.slice(2), 16) + "%3B";
        });
      }
      var out = "";
      for (var j = 0; j < string4.length; j += limit) {
        var segment = string4.length >= limit ? string4.slice(j, j + limit) : string4;
        if (j + limit < string4.length) {
          var last = segment.charCodeAt(segment.length - 1);
          if (last >= 55296 && last <= 56319) {
            segment = segment.slice(0, -1);
            j -= 1;
          }
        }
        var arr = [];
        for (var i2 = 0; i2 < segment.length; ++i2) {
          var c = segment.charCodeAt(i2);
          if (c === 45 || c === 46 || c === 95 || c === 126 || c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 97 && c <= 122 || format === formats.RFC1738 && (c === 40 || c === 41)) {
            arr[arr.length] = segment.charAt(i2);
            continue;
          }
          if (c < 128) {
            arr[arr.length] = hexTable[c];
            continue;
          }
          if (c < 2048) {
            arr[arr.length] = hexTable[192 | c >> 6] + hexTable[128 | c & 63];
            continue;
          }
          if (c < 55296 || c >= 57344) {
            arr[arr.length] = hexTable[224 | c >> 12] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63];
            continue;
          }
          i2 += 1;
          c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i2) & 1023);
          arr[arr.length] = hexTable[240 | c >> 18] + hexTable[128 | c >> 12 & 63] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63];
        }
        out += arr.join("");
      }
      return out;
    };
    var compact = function compact2(value) {
      var queue = [{ obj: { o: value }, prop: "o" }];
      var refs = getSideChannel();
      for (var i2 = 0; i2 < queue.length; ++i2) {
        var item = queue[i2];
        var obj = item.obj[item.prop];
        var keys = Object.keys(obj);
        for (var j = 0; j < keys.length; ++j) {
          var key = keys[j];
          var val = obj[key];
          if (typeof val === "object" && val !== null && !refs.has(val)) {
            queue[queue.length] = { obj, prop: key };
            refs.set(val, true);
          }
        }
      }
      compactQueue(queue);
      return value;
    };
    var isRegExp = function isRegExp2(obj) {
      return Object.prototype.toString.call(obj) === "[object RegExp]";
    };
    var isBuffer = function isBuffer2(obj) {
      if (!obj || typeof obj !== "object") {
        return false;
      }
      return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
    };
    var combine = function combine2(a, b, arrayLimit, plainObjects, throwOnLimitExceeded) {
      if (isOverflow(a)) {
        if (throwOnLimitExceeded) {
          throw new RangeError("Array limit exceeded. Only " + arrayLimit + " element" + (arrayLimit === 1 ? "" : "s") + " allowed in an array.");
        }
        var newIndex = getMaxIndex(a) + 1;
        a[newIndex] = b;
        setMaxIndex(a, newIndex);
        return a;
      }
      var result = [].concat(a, b);
      if (result.length > arrayLimit) {
        if (throwOnLimitExceeded) {
          throw new RangeError("Array limit exceeded. Only " + arrayLimit + " element" + (arrayLimit === 1 ? "" : "s") + " allowed in an array.");
        }
        return markOverflow(arrayToObject(result, { plainObjects }), result.length - 1);
      }
      return result;
    };
    var maybeMap = function maybeMap2(val, fn) {
      if (isArray(val)) {
        var mapped = [];
        for (var i2 = 0; i2 < val.length; i2 += 1) {
          mapped[mapped.length] = fn(val[i2]);
        }
        return mapped;
      }
      return fn(val);
    };
    module2.exports = {
      arrayToObject,
      assign,
      combine,
      compact,
      decode: decode3,
      encode: encode3,
      isBuffer,
      isOverflow,
      isRegExp,
      markOverflow,
      maybeMap,
      merge: merge2
    };
  }
});

// node_modules/qs/lib/stringify.js
var require_stringify2 = __commonJS({
  "node_modules/qs/lib/stringify.js"(exports2, module2) {
    "use strict";
    var getSideChannel = require_side_channel();
    var utils = require_utils3();
    var formats = require_formats();
    var has = Object.prototype.hasOwnProperty;
    var arrayPrefixGenerators = {
      brackets: function brackets(prefix) {
        return prefix + "[]";
      },
      comma: "comma",
      indices: function indices(prefix, key) {
        return prefix + "[" + key + "]";
      },
      repeat: function repeat(prefix) {
        return prefix;
      }
    };
    var isArray = Array.isArray;
    var push = Array.prototype.push;
    var pushToArray = function(arr, valueOrArray) {
      push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]);
    };
    var toISO = Date.prototype.toISOString;
    var defaultFormat = formats["default"];
    var defaults = {
      addQueryPrefix: false,
      allowDots: false,
      allowEmptyArrays: false,
      arrayFormat: "indices",
      charset: "utf-8",
      charsetSentinel: false,
      commaRoundTrip: false,
      delimiter: "&",
      encode: true,
      encodeDotInKeys: false,
      encoder: utils.encode,
      encodeValuesOnly: false,
      filter: void 0,
      format: defaultFormat,
      formatter: formats.formatters[defaultFormat],
      // deprecated
      indices: false,
      serializeDate: function serializeDate(date5) {
        return toISO.call(date5);
      },
      skipNulls: false,
      strictNullHandling: false
    };
    var isNonNullishPrimitive = function isNonNullishPrimitive2(v) {
      return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint";
    };
    var sentinel = {};
    var stringify = function stringify2(object3, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) {
      var obj = object3;
      var tmpSc = sideChannel;
      var step = 0;
      var findFlag = false;
      while ((tmpSc = tmpSc.get(sentinel)) !== void 0 && !findFlag) {
        var pos = tmpSc.get(object3);
        step += 1;
        if (typeof pos !== "undefined") {
          if (pos === step) {
            throw new RangeError("Cyclic object value");
          } else {
            findFlag = true;
          }
        }
        if (typeof tmpSc.get(sentinel) === "undefined") {
          step = 0;
        }
      }
      if (typeof filter === "function") {
        obj = filter(prefix, obj);
      } else if (obj instanceof Date) {
        obj = serializeDate(obj);
      } else if (generateArrayPrefix === "comma" && isArray(obj)) {
        obj = utils.maybeMap(obj, function(value2) {
          if (value2 instanceof Date) {
            return serializeDate(value2);
          }
          return value2;
        });
      }
      if (obj === null) {
        if (strictNullHandling) {
          return formatter(encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, "key", format) : prefix);
        }
        obj = "";
      }
      if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) {
        if (encoder) {
          var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format);
          return [formatter(keyValue) + "=" + formatter(encoder(obj, defaults.encoder, charset, "value", format))];
        }
        return [formatter(prefix) + "=" + formatter(String(obj))];
      }
      var values = [];
      if (typeof obj === "undefined") {
        return values;
      }
      var objKeys;
      if (generateArrayPrefix === "comma" && isArray(obj)) {
        if (encodeValuesOnly && encoder) {
          obj = utils.maybeMap(obj, function(v) {
            return v == null ? v : encoder(v);
          });
        }
        objKeys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }];
      } else if (isArray(filter)) {
        objKeys = filter;
      } else {
        var keys = Object.keys(obj);
        objKeys = sort ? keys.sort(sort) : keys;
      }
      var encodedPrefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix);
      var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encodedPrefix + "[]" : encodedPrefix;
      if (allowEmptyArrays && isArray(obj) && obj.length === 0) {
        return adjustedPrefix + "[]";
      }
      for (var j = 0; j < objKeys.length; ++j) {
        var key = objKeys[j];
        var value = typeof key === "object" && key && typeof key.value !== "undefined" ? key.value : obj[key];
        if (skipNulls && value === null) {
          continue;
        }
        var encodedKey = allowDots && encodeDotInKeys ? String(key).replace(/\./g, "%2E") : String(key);
        var keyPrefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjustedPrefix, encodedKey) : adjustedPrefix : adjustedPrefix + (allowDots ? "." + encodedKey : "[" + encodedKey + "]");
        sideChannel.set(object3, step);
        var valueSideChannel = getSideChannel();
        valueSideChannel.set(sentinel, sideChannel);
        pushToArray(values, stringify2(
          value,
          keyPrefix,
          generateArrayPrefix,
          commaRoundTrip,
          allowEmptyArrays,
          strictNullHandling,
          skipNulls,
          encodeDotInKeys,
          generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder,
          filter,
          sort,
          allowDots,
          serializeDate,
          format,
          formatter,
          encodeValuesOnly,
          charset,
          valueSideChannel
        ));
      }
      return values;
    };
    var normalizeStringifyOptions = function normalizeStringifyOptions2(opts) {
      if (!opts) {
        return defaults;
      }
      if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") {
        throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");
      }
      if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") {
        throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");
      }
      if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") {
        throw new TypeError("Encoder has to be a function.");
      }
      var charset = opts.charset || defaults.charset;
      if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") {
        throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
      }
      var format = formats["default"];
      if (typeof opts.format !== "undefined") {
        if (!has.call(formats.formatters, opts.format)) {
          throw new TypeError("Unknown format option provided.");
        }
        format = opts.format;
      }
      var formatter = formats.formatters[format];
      var filter = defaults.filter;
      if (typeof opts.filter === "function" || isArray(opts.filter)) {
        filter = opts.filter;
      }
      var arrayFormat;
      if (opts.arrayFormat in arrayPrefixGenerators) {
        arrayFormat = opts.arrayFormat;
      } else if ("indices" in opts) {
        arrayFormat = opts.indices ? "indices" : "repeat";
      } else {
        arrayFormat = defaults.arrayFormat;
      }
      if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") {
        throw new TypeError("`commaRoundTrip` must be a boolean, or absent");
      }
      var allowDots = typeof opts.allowDots === "undefined" ? opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots;
      return {
        addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix,
        allowDots,
        allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,
        arrayFormat,
        charset,
        charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel,
        commaRoundTrip: !!opts.commaRoundTrip,
        delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter,
        encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode,
        encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys,
        encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder,
        encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
        filter,
        format,
        formatter,
        serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate,
        skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls,
        sort: typeof opts.sort === "function" ? opts.sort : null,
        strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling
      };
    };
    module2.exports = function(object3, opts) {
      var obj = object3;
      var options = normalizeStringifyOptions(opts);
      var objKeys;
      var filter;
      if (typeof options.filter === "function") {
        filter = options.filter;
        obj = filter("", obj);
      } else if (isArray(options.filter)) {
        filter = options.filter;
        objKeys = filter;
      }
      var keys = [];
      if (typeof obj !== "object" || obj === null) {
        return "";
      }
      var generateArrayPrefix = arrayPrefixGenerators[options.arrayFormat];
      var commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip;
      if (!objKeys) {
        objKeys = Object.keys(obj);
      }
      if (options.sort) {
        objKeys.sort(options.sort);
      }
      var sideChannel = getSideChannel();
      for (var i2 = 0; i2 < objKeys.length; ++i2) {
        var key = objKeys[i2];
        if (typeof key === "undefined" || key === null) {
          continue;
        }
        var value = obj[key];
        if (options.skipNulls && value === null) {
          continue;
        }
        pushToArray(keys, stringify(
          value,
          key,
          generateArrayPrefix,
          commaRoundTrip,
          options.allowEmptyArrays,
          options.strictNullHandling,
          options.skipNulls,
          options.encodeDotInKeys,
          options.encode ? options.encoder : null,
          options.filter,
          options.sort,
          options.allowDots,
          options.serializeDate,
          options.format,
          options.formatter,
          options.encodeValuesOnly,
          options.charset,
          sideChannel
        ));
      }
      var joined = keys.join(options.delimiter);
      var prefix = options.addQueryPrefix === true ? "?" : "";
      if (options.charsetSentinel) {
        if (options.charset === "iso-8859-1") {
          prefix += "utf8=%26%2310003%3B" + options.delimiter;
        } else {
          prefix += "utf8=%E2%9C%93" + options.delimiter;
        }
      }
      return joined.length > 0 ? prefix + joined : "";
    };
  }
});

// node_modules/qs/lib/parse.js
var require_parse2 = __commonJS({
  "node_modules/qs/lib/parse.js"(exports2, module2) {
    "use strict";
    var utils = require_utils3();
    var has = Object.prototype.hasOwnProperty;
    var isArray = Array.isArray;
    var defaults = {
      allowDots: false,
      allowEmptyArrays: false,
      allowPrototypes: false,
      allowSparse: false,
      arrayLimit: 20,
      charset: "utf-8",
      charsetSentinel: false,
      comma: false,
      decodeDotInKeys: false,
      decoder: utils.decode,
      delimiter: "&",
      depth: 5,
      duplicates: "combine",
      ignoreQueryPrefix: false,
      interpretNumericEntities: false,
      parameterLimit: 1e3,
      parseArrays: true,
      plainObjects: false,
      strictDepth: false,
      strictMerge: true,
      strictNullHandling: false,
      throwOnLimitExceeded: false
    };
    var interpretNumericEntities = function(str) {
      return str.replace(/&#(\d+);/g, function($0, numberStr) {
        return String.fromCharCode(parseInt(numberStr, 10));
      });
    };
    var parseArrayValue = function(val, options, currentArrayLength, isFlatArrayValue) {
      if (val && typeof val === "string" && options.comma && val.indexOf(",") > -1) {
        if (isFlatArrayValue && options.throwOnLimitExceeded) {
          var commaCount = 0;
          var commaIndex = val.indexOf(",");
          while (commaIndex > -1) {
            commaCount += 1;
            if (commaCount >= options.arrayLimit) {
              throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array.");
            }
            commaIndex = val.indexOf(",", commaIndex + 1);
          }
        }
        return val.split(",");
      }
      if (options.throwOnLimitExceeded && currentArrayLength >= options.arrayLimit) {
        throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array.");
      }
      return val;
    };
    var isoSentinel = "utf8=%26%2310003%3B";
    var charsetSentinel = "utf8=%E2%9C%93";
    var parseValues = function parseQueryStringValues(str, options) {
      var obj = { __proto__: null };
      var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, "") : str;
      cleanStr = cleanStr.replace(/%5B/gi, "[").replace(/%5D/gi, "]");
      var limit = options.parameterLimit === Infinity ? void 0 : options.parameterLimit;
      var parts = cleanStr.split(
        options.delimiter,
        options.throwOnLimitExceeded && typeof limit !== "undefined" ? limit + 1 : limit
      );
      if (options.throwOnLimitExceeded && typeof limit !== "undefined" && parts.length > limit) {
        throw new RangeError("Parameter limit exceeded. Only " + limit + " parameter" + (limit === 1 ? "" : "s") + " allowed.");
      }
      var skipIndex = -1;
      var i2;
      var charset = options.charset;
      if (options.charsetSentinel) {
        for (i2 = 0; i2 < parts.length; ++i2) {
          if (parts[i2].indexOf("utf8=") === 0) {
            if (parts[i2] === charsetSentinel) {
              charset = "utf-8";
            } else if (parts[i2] === isoSentinel) {
              charset = "iso-8859-1";
            }
            skipIndex = i2;
            i2 = parts.length;
          }
        }
      }
      for (i2 = 0; i2 < parts.length; ++i2) {
        if (i2 === skipIndex) {
          continue;
        }
        var part = parts[i2];
        var bracketEqualsPos = part.indexOf("]=");
        var pos = bracketEqualsPos === -1 ? part.indexOf("=") : bracketEqualsPos + 1;
        var key;
        var val;
        if (pos === -1) {
          key = options.decoder(part, defaults.decoder, charset, "key");
          val = options.strictNullHandling ? null : "";
        } else {
          key = options.decoder(part.slice(0, pos), defaults.decoder, charset, "key");
          if (key !== null) {
            val = utils.maybeMap(
              parseArrayValue(
                part.slice(pos + 1),
                options,
                isArray(obj[key]) ? obj[key].length : 0,
                part.indexOf("[]=") === -1
              ),
              function(encodedVal) {
                return options.decoder(encodedVal, defaults.decoder, charset, "value");
              }
            );
          }
        }
        if (val && options.interpretNumericEntities && charset === "iso-8859-1") {
          val = interpretNumericEntities(String(val));
        }
        if (part.indexOf("[]=") > -1) {
          val = isArray(val) ? [val] : val;
        }
        if (options.comma && isArray(val) && val.length > options.arrayLimit) {
          val = utils.combine([], val, options.arrayLimit, options.plainObjects, options.throwOnLimitExceeded);
        }
        if (key !== null) {
          var existing = has.call(obj, key);
          if (existing && (options.duplicates === "combine" || part.indexOf("[]=") > -1)) {
            obj[key] = utils.combine(
              obj[key],
              val,
              options.arrayLimit,
              options.plainObjects,
              options.throwOnLimitExceeded
            );
          } else if (!existing || options.duplicates === "last") {
            obj[key] = val;
          }
        }
      }
      return obj;
    };
    var parseObject = function(chain, val, options, valuesParsed) {
      var currentArrayLength = 0;
      if (chain.length > 0 && chain[chain.length - 1] === "[]") {
        var parentKey = chain.slice(0, -1).join("");
        currentArrayLength = Array.isArray(val) && val[parentKey] ? val[parentKey].length : 0;
      }
      var leaf = valuesParsed ? val : parseArrayValue(val, options, currentArrayLength);
      for (var i2 = chain.length - 1; i2 >= 0; --i2) {
        var obj;
        var root = chain[i2];
        if (root === "[]" && options.parseArrays) {
          if (utils.isOverflow(leaf)) {
            obj = leaf;
          } else {
            obj = options.allowEmptyArrays && (leaf === "" || options.strictNullHandling && leaf === null) ? [] : utils.combine(
              [],
              leaf,
              options.arrayLimit,
              options.plainObjects,
              options.throwOnLimitExceeded
            );
          }
        } else {
          obj = options.plainObjects ? { __proto__: null } : {};
          var cleanRoot = root.charAt(0) === "[" && root.charAt(root.length - 1) === "]" ? root.slice(1, -1) : root;
          var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, ".") : cleanRoot;
          var index = parseInt(decodedRoot, 10);
          var isValidArrayIndex = !isNaN(index) && root !== decodedRoot && String(index) === decodedRoot && index >= 0 && options.parseArrays;
          if (!options.parseArrays && decodedRoot === "") {
            obj = { 0: leaf };
          } else if (isValidArrayIndex && index < options.arrayLimit) {
            obj = [];
            obj[index] = leaf;
          } else if (isValidArrayIndex && options.throwOnLimitExceeded) {
            throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array.");
          } else if (isValidArrayIndex) {
            obj[index] = leaf;
            utils.markOverflow(obj, index);
          } else if (decodedRoot !== "__proto__") {
            obj[decodedRoot] = leaf;
          }
        }
        leaf = obj;
      }
      return leaf;
    };
    var splitKeyIntoSegments = function splitKeyIntoSegments2(originalKey, options) {
      var key = options.allowDots ? originalKey.replace(/\.([^.[]+)/g, "[$1]") : originalKey;
      if (options.depth <= 0) {
        if (!options.plainObjects && has.call(Object.prototype, key)) {
          if (!options.allowPrototypes) {
            return;
          }
        }
        return [key];
      }
      var segments = [];
      var first = key.indexOf("[");
      var parent = first >= 0 ? key.slice(0, first) : key;
      if (parent) {
        if (!options.plainObjects && has.call(Object.prototype, parent)) {
          if (!options.allowPrototypes) {
            return;
          }
        }
        segments[segments.length] = parent;
      }
      var n = key.length;
      var open = first;
      var collected = 0;
      while (open >= 0 && collected < options.depth) {
        var level = 1;
        var i2 = open + 1;
        var close = -1;
        while (i2 < n && close < 0) {
          var cu = key.charCodeAt(i2);
          if (cu === 91) {
            level += 1;
          } else if (cu === 93) {
            level -= 1;
            if (level === 0) {
              close = i2;
            }
          }
          i2 += 1;
        }
        if (close < 0) {
          segments[segments.length] = "[" + key.slice(open) + "]";
          return segments;
        }
        var seg = key.slice(open, close + 1);
        var content = seg.slice(1, -1);
        if (!options.plainObjects && has.call(Object.prototype, content) && !options.allowPrototypes) {
          return;
        }
        segments[segments.length] = seg;
        collected += 1;
        open = key.indexOf("[", close + 1);
      }
      if (open >= 0) {
        if (options.strictDepth === true) {
          throw new RangeError("Input depth exceeded depth option of " + options.depth + " and strictDepth is true");
        }
        segments[segments.length] = "[" + key.slice(open) + "]";
      }
      return segments;
    };
    var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {
      if (!givenKey) {
        return;
      }
      var keys = splitKeyIntoSegments(givenKey, options);
      if (!keys) {
        return;
      }
      return parseObject(keys, val, options, valuesParsed);
    };
    var normalizeParseOptions = function normalizeParseOptions2(opts) {
      if (!opts) {
        return defaults;
      }
      if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") {
        throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");
      }
      if (typeof opts.decodeDotInKeys !== "undefined" && typeof opts.decodeDotInKeys !== "boolean") {
        throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");
      }
      if (opts.decoder !== null && typeof opts.decoder !== "undefined" && typeof opts.decoder !== "function") {
        throw new TypeError("Decoder has to be a function.");
      }
      if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") {
        throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
      }
      if (typeof opts.throwOnLimitExceeded !== "undefined" && typeof opts.throwOnLimitExceeded !== "boolean") {
        throw new TypeError("`throwOnLimitExceeded` option must be a boolean");
      }
      var charset = typeof opts.charset === "undefined" ? defaults.charset : opts.charset;
      var duplicates = typeof opts.duplicates === "undefined" ? defaults.duplicates : opts.duplicates;
      if (duplicates !== "combine" && duplicates !== "first" && duplicates !== "last") {
        throw new TypeError("The duplicates option must be either combine, first, or last");
      }
      var allowDots = typeof opts.allowDots === "undefined" ? opts.decodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots;
      return {
        allowDots,
        allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,
        allowPrototypes: typeof opts.allowPrototypes === "boolean" ? opts.allowPrototypes : defaults.allowPrototypes,
        allowSparse: typeof opts.allowSparse === "boolean" ? opts.allowSparse : defaults.allowSparse,
        arrayLimit: typeof opts.arrayLimit === "number" ? opts.arrayLimit : defaults.arrayLimit,
        charset,
        charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel,
        comma: typeof opts.comma === "boolean" ? opts.comma : defaults.comma,
        decodeDotInKeys: typeof opts.decodeDotInKeys === "boolean" ? opts.decodeDotInKeys : defaults.decodeDotInKeys,
        decoder: typeof opts.decoder === "function" ? opts.decoder : defaults.decoder,
        delimiter: typeof opts.delimiter === "string" || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,
        // eslint-disable-next-line no-implicit-coercion, no-extra-parens
        depth: typeof opts.depth === "number" || opts.depth === false ? +opts.depth : defaults.depth,
        duplicates,
        ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
        interpretNumericEntities: typeof opts.interpretNumericEntities === "boolean" ? opts.interpretNumericEntities : defaults.interpretNumericEntities,
        parameterLimit: typeof opts.parameterLimit === "number" ? opts.parameterLimit : defaults.parameterLimit,
        parseArrays: opts.parseArrays !== false,
        plainObjects: typeof opts.plainObjects === "boolean" ? opts.plainObjects : defaults.plainObjects,
        strictDepth: typeof opts.strictDepth === "boolean" ? !!opts.strictDepth : defaults.strictDepth,
        strictMerge: typeof opts.strictMerge === "boolean" ? !!opts.strictMerge : defaults.strictMerge,
        strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling,
        throwOnLimitExceeded: typeof opts.throwOnLimitExceeded === "boolean" ? opts.throwOnLimitExceeded : false
      };
    };
    module2.exports = function(str, opts) {
      var options = normalizeParseOptions(opts);
      if (str === "" || str === null || typeof str === "undefined") {
        return options.plainObjects ? { __proto__: null } : {};
      }
      var tempObj = typeof str === "string" ? parseValues(str, options) : str;
      var obj = options.plainObjects ? { __proto__: null } : {};
      var keys = Object.keys(tempObj);
      for (var i2 = 0; i2 < keys.length; ++i2) {
        var key = keys[i2];
        var newObj = parseKeys(key, tempObj[key], options, typeof str === "string");
        obj = utils.merge(obj, newObj, options);
      }
      if (options.allowSparse === true) {
        return obj;
      }
      return utils.compact(obj);
    };
  }
});

// node_modules/qs/lib/index.js
var require_lib4 = __commonJS({
  "node_modules/qs/lib/index.js"(exports2, module2) {
    "use strict";
    var stringify = require_stringify2();
    var parse3 = require_parse2();
    var formats = require_formats();
    module2.exports = {
      formats,
      parse: parse3,
      stringify
    };
  }
});

// node_modules/url-template/lib/url-template.js
var require_url_template = __commonJS({
  "node_modules/url-template/lib/url-template.js"(exports2, module2) {
    (function(root, factory) {
      if (typeof exports2 === "object") {
        module2.exports = factory();
      } else if (typeof define === "function" && define.amd) {
        define([], factory);
      } else {
        root.urltemplate = factory();
      }
    })(exports2, function() {
      function UrlTemplate() {
      }
      UrlTemplate.prototype.encodeReserved = function(str) {
        return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) {
          if (!/%[0-9A-Fa-f]/.test(part)) {
            part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
          }
          return part;
        }).join("");
      };
      UrlTemplate.prototype.encodeUnreserved = function(str) {
        return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
          return "%" + c.charCodeAt(0).toString(16).toUpperCase();
        });
      };
      UrlTemplate.prototype.encodeValue = function(operator, value, key) {
        value = operator === "+" || operator === "#" ? this.encodeReserved(value) : this.encodeUnreserved(value);
        if (key) {
          return this.encodeUnreserved(key) + "=" + value;
        } else {
          return value;
        }
      };
      UrlTemplate.prototype.isDefined = function(value) {
        return value !== void 0 && value !== null;
      };
      UrlTemplate.prototype.isKeyOperator = function(operator) {
        return operator === ";" || operator === "&" || operator === "?";
      };
      UrlTemplate.prototype.getValues = function(context, operator, key, modifier) {
        var value = context[key], result = [];
        if (this.isDefined(value) && value !== "") {
          if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
            value = value.toString();
            if (modifier && modifier !== "*") {
              value = value.substring(0, parseInt(modifier, 10));
            }
            result.push(this.encodeValue(operator, value, this.isKeyOperator(operator) ? key : null));
          } else {
            if (modifier === "*") {
              if (Array.isArray(value)) {
                value.filter(this.isDefined).forEach(function(value2) {
                  result.push(this.encodeValue(operator, value2, this.isKeyOperator(operator) ? key : null));
                }, this);
              } else {
                Object.keys(value).forEach(function(k) {
                  if (this.isDefined(value[k])) {
                    result.push(this.encodeValue(operator, value[k], k));
                  }
                }, this);
              }
            } else {
              var tmp = [];
              if (Array.isArray(value)) {
                value.filter(this.isDefined).forEach(function(value2) {
                  tmp.push(this.encodeValue(operator, value2));
                }, this);
              } else {
                Object.keys(value).forEach(function(k) {
                  if (this.isDefined(value[k])) {
                    tmp.push(this.encodeUnreserved(k));
                    tmp.push(this.encodeValue(operator, value[k].toString()));
                  }
                }, this);
              }
              if (this.isKeyOperator(operator)) {
                result.push(this.encodeUnreserved(key) + "=" + tmp.join(","));
              } else if (tmp.length !== 0) {
                result.push(tmp.join(","));
              }
            }
          }
        } else {
          if (operator === ";") {
            if (this.isDefined(value)) {
              result.push(this.encodeUnreserved(key));
            }
          } else if (value === "" && (operator === "&" || operator === "?")) {
            result.push(this.encodeUnreserved(key) + "=");
          } else if (value === "") {
            result.push("");
          }
        }
        return result;
      };
      UrlTemplate.prototype.parse = function(template) {
        var that = this;
        var operators = ["+", "#", ".", "/", ";", "?", "&"];
        return {
          expand: function(context) {
            return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function(_, expression, literal2) {
              if (expression) {
                var operator = null, values = [];
                if (operators.indexOf(expression.charAt(0)) !== -1) {
                  operator = expression.charAt(0);
                  expression = expression.substr(1);
                }
                expression.split(/,/g).forEach(function(variable) {
                  var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
                  values.push.apply(values, that.getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
                });
                if (operator && operator !== "+") {
                  var separator = ",";
                  if (operator === "?") {
                    separator = "&";
                  } else if (operator !== "#") {
                    separator = operator;
                  }
                  return (values.length !== 0 ? operator : "") + values.join(separator);
                } else {
                  return values.join(",");
                }
              } else {
                return that.encodeReserved(literal2);
              }
            });
          }
        };
      };
      return new UrlTemplate();
    });
  }
});

// node_modules/googleapis-common/build/src/isbrowser.js
var require_isbrowser = __commonJS({
  "node_modules/googleapis-common/build/src/isbrowser.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isBrowser = isBrowser;
    function isBrowser() {
      return typeof window !== "undefined";
    }
  }
});

// node_modules/googleapis-common/build/src/util.js
var require_util4 = __commonJS({
  "node_modules/googleapis-common/build/src/util.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.headersToClassicHeaders = headersToClassicHeaders;
    exports2.marshallGaxiosResponse = marshallGaxiosResponse;
    function headersToClassicHeaders(headers) {
      let classicHeaders = {};
      if (headers instanceof Headers) {
        headers.forEach((value, key) => {
          classicHeaders[key] = value;
        });
      } else if (Array.isArray(headers)) {
        for (const [key, value] of headers) {
          classicHeaders[key] = value;
        }
      } else {
        classicHeaders = headers || {};
      }
      return classicHeaders;
    }
    function marshallGaxiosResponse(res) {
      return Object.defineProperties(res || {}, {
        headers: {
          configurable: true,
          writable: true,
          enumerable: true,
          value: headersToClassicHeaders(res?.headers)
        }
      });
    }
  }
});

// node_modules/googleapis-common/build/src/http2.js
var require_http2 = __commonJS({
  "node_modules/googleapis-common/build/src/http2.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.sessions = void 0;
    exports2.request = request;
    exports2.closeSession = closeSession;
    var http22 = require("http2");
    var zlib2 = require("zlib");
    var url_1 = require("url");
    var qs = require_lib4();
    var extend2 = require_extend();
    var stream_1 = require("stream");
    var util2 = require("util");
    var process4 = require("process");
    var util_1 = require_util4();
    var { HTTP2_HEADER_CONTENT_ENCODING, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS } = http22.constants;
    var DEBUG = !!process4.env.HTTP2_DEBUG;
    exports2.sessions = {};
    async function request(config2) {
      const opts = extend2(true, {}, config2);
      opts.validateStatus = opts.validateStatus || validateStatus;
      opts.responseType = opts.responseType || "json";
      const url2 = new url_1.URL(opts.url);
      const sessionData = _getClient(url2.host);
      if (sessionData.timeoutHandle !== void 0) {
        clearTimeout(sessionData.timeoutHandle);
      }
      let pathWithQs = url2.pathname;
      if (config2.params && Object.keys(config2.params).length > 0) {
        const serializer = config2.paramsSerializer || qs.stringify;
        const q = serializer(opts.params);
        pathWithQs += `?${q}`;
      }
      const headers = (0, util_1.headersToClassicHeaders)(opts.headers);
      headers[HTTP2_HEADER_PATH] = pathWithQs;
      headers[HTTP2_HEADER_METHOD] = config2.method || "GET";
      opts.headers = headers;
      if (!headers[HTTP2_HEADER_CONTENT_TYPE]) {
        if (opts.responseType !== "text") {
          headers[HTTP2_HEADER_CONTENT_TYPE] = "application/json";
        }
      }
      const res = {
        config: config2,
        headers: {},
        status: 0,
        data: {},
        statusText: ""
      };
      const chunks = [];
      const session = sessionData.session;
      let req;
      return new Promise((resolve2, reject) => {
        try {
          req = session.request(headers).on("response", (responseHeaders) => {
            Object.assign(res, {
              headers: responseHeaders,
              status: responseHeaders[HTTP2_HEADER_STATUS]
            });
            let stream = req;
            if (responseHeaders[HTTP2_HEADER_CONTENT_ENCODING] === "gzip") {
              stream = req.pipe(zlib2.createGunzip());
            }
            if (opts.responseType === "stream") {
              res.data = stream;
              resolve2(res);
              return;
            }
            stream.on("data", (d) => {
              chunks.push(d);
            }).on("error", (err) => {
              reject(err);
              return;
            }).on("end", () => {
              const buf = Buffer.concat(chunks);
              let data = buf;
              if (buf) {
                if (opts.responseType === "json") {
                  try {
                    data = JSON.parse(buf.toString("utf8"));
                  } catch {
                    data = buf.toString("utf8");
                  }
                } else if (opts.responseType === "text") {
                  data = buf.toString("utf8");
                } else if (opts.responseType === "arraybuffer") {
                  data = buf.buffer;
                }
                res.data = data;
              }
              if (!opts.validateStatus(res.status)) {
                let message = `Request failed with status code ${res.status}. `;
                if (res.data && typeof res.data === "object") {
                  const body = util2.inspect(res.data, { depth: 5 });
                  message = `${message}
'${body}`;
                }
                reject(new Error(message, { cause: res }));
              }
              resolve2(res);
              return;
            });
          }).on("error", (e2) => {
            reject(e2);
            return;
          });
        } catch (e2) {
          closeSession(url2).then(() => reject(e2)).catch(reject);
          return;
        }
        res.request = req;
        if (config2.data) {
          if (config2.data instanceof stream_1.Stream) {
            config2.data.pipe(req);
          } else if (typeof config2.data === "string") {
            const data = Buffer.from(config2.data);
            req.end(data);
          } else if (typeof config2.data === "object") {
            const data = JSON.stringify(config2.data);
            req.end(data);
          }
        }
        sessionData.timeoutHandle = setTimeout(() => closeSession(url2), 500);
      });
    }
    function validateStatus(status) {
      return status >= 200 && status < 300;
    }
    function _getClient(host) {
      if (!exports2.sessions[host]) {
        if (DEBUG) {
          console.log(`Creating client for ${host}`);
        }
        const session = http22.connect(`https://${host}`);
        session.on("error", (e2) => {
          console.error(`*ERROR*: ${e2}`);
          delete exports2.sessions[host];
        }).on("goaway", (errorCode, lastStreamId) => {
          console.error(`*GOAWAY*: ${errorCode} : ${lastStreamId}`);
          delete exports2.sessions[host];
        });
        exports2.sessions[host] = { session };
      } else {
        if (DEBUG) {
          console.log(`Used cached client for ${host}`);
        }
      }
      return exports2.sessions[host];
    }
    async function closeSession(url2) {
      const sessionData = exports2.sessions[url2.host];
      if (!sessionData) {
        return;
      }
      const { session } = sessionData;
      delete exports2.sessions[url2.host];
      if (DEBUG) {
        console.error(`Closing ${url2.host}`);
      }
      session.close(() => {
        if (DEBUG) {
          console.error(`Closed ${url2.host}`);
        }
      });
      setTimeout(() => {
        if (session && !session.destroyed) {
          if (DEBUG) {
            console.log(`Forcing close ${url2.host}`);
          }
          if (session) {
            session.destroy();
          }
        }
      }, 1e3);
    }
  }
});

// node_modules/googleapis-common/package.json
var require_package5 = __commonJS({
  "node_modules/googleapis-common/package.json"(exports2, module2) {
    module2.exports = {
      name: "googleapis-common",
      version: "8.0.3",
      description: "A common tooling library used by the googleapis npm module. You probably don't want to use this directly.",
      repository: {
        type: "git",
        directory: "core/packages/nodejs-googleapis-common",
        url: "https://github.com/googleapis/google-cloud-node.git"
      },
      main: "build/src/index.js",
      types: "build/src/index.d.ts",
      files: [
        "build/src",
        "!build/src/**/*.map"
      ],
      scripts: {
        prebenchmark: "npm run compile",
        benchmark: "node build/benchmark/bench.js",
        compile: "tsc -p .",
        test: "c8 mocha build/test",
        "system-test": "c8 mocha build/system-test --timeout 600000",
        "presystem-test": "npm run compile",
        fix: "gts fix",
        prepare: "npm run compile",
        pretest: "npm run compile",
        lint: "gts check",
        "samples-test": "mocha build/samples-test",
        docs: "jsdoc -c .jsdoc.js",
        webpack: "webpack",
        "browser-test": "karma start",
        prelint: "cd samples; npm link ../; npm install",
        clean: "gts clean",
        precompile: "gts clean"
      },
      keywords: [],
      author: "Google LLC",
      license: "Apache-2.0",
      dependencies: {
        extend: "^3.0.2",
        gaxios: "7.1.3",
        "google-auth-library": "10.5.0",
        "google-logging-utils": "1.1.3",
        qs: "^6.7.0",
        "url-template": "^2.0.8"
      },
      devDependencies: {
        "@babel/plugin-proposal-private-methods": "^7.18.6",
        "@types/extend": "^3.0.1",
        "@types/mocha": "^10.0.10",
        "@types/mv": "^2.1.0",
        "@types/ncp": "^2.0.8",
        "@types/nock": "^11.0.0",
        "@types/proxyquire": "^1.3.31",
        "@types/qs": "^6.5.3",
        "@types/sinon": "^21.0.0",
        "@types/tmp": "^0.2.6",
        "@types/url-template": "^2.0.28",
        c8: "^10.1.3",
        codecov: "^3.8.3",
        gts: "^6.0.2",
        http2spy: "^2.0.0",
        "is-docker": "^3.0.0",
        jsdoc: "^4.0.4",
        "jsdoc-fresh": "^5.0.0",
        "jsdoc-region-tag": "^4.0.0",
        karma: "^6.0.0",
        "karma-chrome-launcher": "^3.0.0",
        "karma-coverage": "^2.0.0",
        "karma-firefox-launcher": "^2.0.0",
        "karma-mocha": "^2.0.0",
        "karma-remap-coverage": "^0.1.5",
        "karma-sourcemap-loader": "^0.4.0",
        "karma-webpack": "^5.0.1",
        mocha: "^11.1.0",
        mv: "^2.1.1",
        ncp: "^2.0.0",
        nock: "^14.0.5",
        "null-loader": "^4.0.1",
        "path-to-regexp": "^6.0.0",
        proxyquire: "^2.1.3",
        puppeteer: "^24.0.0",
        sinon: "21.0.3",
        tmp: "0.2.5",
        "ts-loader": "^9.5.2",
        typescript: "5.8.3",
        webpack: "^5.97.1",
        "webpack-cli": "^6.0.1"
      },
      engines: {
        node: ">=18"
      },
      homepage: "https://github.com/googleapis/google-cloud-node/tree/main/core/packages/nodejs-googleapis-common"
    };
  }
});

// node_modules/googleapis-common/build/src/apirequest.js
var require_apirequest = __commonJS({
  "node_modules/googleapis-common/build/src/apirequest.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createAPIRequest = createAPIRequest;
    var gaxios_1 = require_src5();
    var qs = require_lib4();
    var stream = require("stream");
    var urlTemplate = require_url_template();
    var extend2 = require_extend();
    var isbrowser_1 = require_isbrowser();
    var h2 = require_http2();
    var util_1 = require_util4();
    var pkg = require_package5();
    var randomUUID = () => globalThis.crypto?.randomUUID() || require("crypto").randomUUID();
    function isReadableStream(obj) {
      return obj !== null && typeof obj === "object" && typeof obj.pipe === "function" && obj.readable !== false && typeof obj._read === "function" && typeof obj._readableState === "object";
    }
    function getMissingParams(params, required2) {
      const missing = new Array();
      required2.forEach((param) => {
        if (params[param] === void 0) {
          missing.push(param);
        }
      });
      return missing.length > 0 ? missing : null;
    }
    function createAPIRequest(parameters, callback) {
      if (callback) {
        createAPIRequestAsync(parameters).then((r2) => callback(null, r2), callback);
      } else {
        return createAPIRequestAsync(parameters);
      }
    }
    async function createAPIRequestAsync(parameters) {
      const options = extend2(
        true,
        {},
        // Ensure we don't leak settings upstream
        parameters.context.google?._options || {},
        // Google level options
        parameters.context._options || {},
        // Per-API options
        parameters.options
      );
      const params = extend2(
        true,
        {},
        // New base object
        options.params,
        // Combined global/per-api params
        parameters.params
      );
      options.userAgentDirectives = options.userAgentDirectives || [];
      const media = params.media || {};
      let resource = params.requestBody;
      if (!params.requestBody && params.resource && (!parameters.requiredParams.includes("resource") || typeof params.resource !== "string")) {
        resource = params.resource;
        delete params.resource;
      }
      delete params.requestBody;
      let authClient = params.auth || options.auth;
      const defaultMime = typeof media.body === "string" ? "text/plain" : "application/octet-stream";
      delete params.media;
      delete params.auth;
      const headers = (0, util_1.headersToClassicHeaders)(params.headers || {});
      populateAPIHeader(headers, options.apiVersion);
      delete params.headers;
      Object.keys(params).forEach((key) => {
        if (key.slice(-1) === "_") {
          const newKey = key.slice(0, -1);
          params[newKey] = params[key];
          delete params[key];
        }
      });
      const missingParams = getMissingParams(params, parameters.requiredParams);
      if (missingParams) {
        throw new Error("Missing required parameters: " + missingParams.join(", "));
      }
      if (options.url) {
        let url2 = options.url;
        if (typeof url2 === "object") {
          url2 = url2.toString();
        }
        options.url = urlTemplate.parse(url2).expand(params);
      }
      if (parameters.mediaUrl) {
        parameters.mediaUrl = urlTemplate.parse(parameters.mediaUrl).expand(params);
      }
      if (parameters.context._options.rootUrl !== void 0 && options.url !== void 0) {
        const originalUrl = new URL(options.url);
        const path = originalUrl.href.substr(originalUrl.origin.length);
        options.url = new URL(path, parameters.context._options.rootUrl).href;
      }
      options.paramsSerializer = (params2) => {
        return qs.stringify(params2, { arrayFormat: "repeat" });
      };
      parameters.pathParams.forEach((param) => delete params[param]);
      if (typeof authClient === "string") {
        params.key = params.key || authClient;
        authClient = void 0;
      }
      function multipartUpload(multipart) {
        const boundary = randomUUID();
        const finale = `--${boundary}--`;
        const rStream = new stream.PassThrough({
          flush(callback) {
            this.push("\r\n");
            this.push(finale);
            callback();
          }
        });
        const pStream = new ProgressStream();
        const isStream = isReadableStream(multipart[1].body);
        headers["content-type"] = `multipart/related; boundary=${boundary}`;
        for (const part of multipart) {
          const preamble = `--${boundary}\r
content-type: ${part["content-type"]}\r
\r
`;
          rStream.push(preamble);
          if (typeof part.body === "string") {
            rStream.push(part.body);
            rStream.push("\r\n");
          } else {
            pStream.on("progress", (bytesRead) => {
              if (options.onUploadProgress) {
                options.onUploadProgress({ bytesRead });
              }
            });
            part.body.pipe(pStream).pipe(rStream);
          }
        }
        if (!isStream) {
          rStream.push(finale);
          rStream.push(null);
        }
        options.data = rStream;
      }
      function browserMultipartUpload(multipart) {
        const boundary = randomUUID();
        const finale = `--${boundary}--`;
        headers["content-type"] = `multipart/related; boundary=${boundary}`;
        let content = "";
        for (const part of multipart) {
          const preamble = `--${boundary}\r
content-type: ${part["content-type"]}\r
\r
`;
          content += preamble;
          if (typeof part.body === "string") {
            content += part.body;
            content += "\r\n";
          }
        }
        content += finale;
        options.data = content;
      }
      if (parameters.mediaUrl && media.body) {
        options.url = parameters.mediaUrl;
        if (resource) {
          params.uploadType = "multipart";
          const multipart = [
            { "content-type": "application/json", body: JSON.stringify(resource) },
            {
              "content-type": media.mimeType || resource && resource.mimeType || defaultMime,
              body: media.body
            }
          ];
          if (!(0, isbrowser_1.isBrowser)()) {
            multipartUpload(multipart);
          } else {
            browserMultipartUpload(multipart);
          }
        } else {
          params.uploadType = "media";
          Object.assign(headers, { "content-type": media.mimeType || defaultMime });
          options.data = media.body;
        }
      } else {
        options.data = resource || void 0;
      }
      options.headers = gaxios_1.Gaxios.mergeHeaders(options.headers || {}, headers);
      options.params = params;
      if (!(0, isbrowser_1.isBrowser)()) {
        options.headers.set("Accept-Encoding", "gzip");
        options.userAgentDirectives.push({
          product: "google-api-nodejs-client",
          version: pkg.version,
          comment: "gzip"
        });
        const userAgent = options.userAgentDirectives.map((d) => {
          let line = `${d.product}/${d.version}`;
          if (d.comment) {
            line += ` (${d.comment})`;
          }
          return line;
        }).join(" ");
        options.headers.set("User-Agent", userAgent);
      }
      if (!options.validateStatus) {
        options.validateStatus = (status) => {
          return status >= 200 && status < 300 || status === 304;
        };
      }
      options.retry = options.retry === void 0 ? true : options.retry;
      delete options.auth;
      if (options.universeDomain && options.universe_domain && options.universeDomain !== options.universe_domain) {
        throw new Error("Please set either universe_domain or universeDomain, but not both.");
      }
      const universeDomainEnvVar = typeof process === "object" && typeof process.env === "object" ? process.env["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] : void 0;
      const universeDomain = options.universeDomain ?? options.universe_domain ?? universeDomainEnvVar ?? "googleapis.com";
      if (universeDomain !== "googleapis.com" && options.url) {
        const url2 = new URL(options.url);
        if (url2.hostname.endsWith(".googleapis.com")) {
          url2.hostname = url2.hostname.replace(/googleapis\.com$/, universeDomain);
          options.url = url2.toString();
        }
      }
      if (!Object.keys(options.params).length) {
        delete options.params;
        delete options.paramsSerializer;
      }
      if (authClient && typeof authClient === "object") {
        const universeFromAuth = typeof authClient.getUniverseDomain === "function" ? await authClient.getUniverseDomain() : void 0;
        if (universeFromAuth && universeDomain !== universeFromAuth) {
          throw new Error(`The configured universe domain (${universeDomain}) does not match the universe domain found in the credentials (${universeFromAuth}). If you haven't configured the universe domain explicitly, googleapis.com is the default.`);
        }
        if (options.http2) {
          const authHeaders = await authClient.getRequestHeaders(options.url);
          const mooOpts = Object.assign({}, options);
          mooOpts.headers = gaxios_1.Gaxios.mergeHeaders(mooOpts.headers, authHeaders);
          return h2.request(mooOpts);
        } else {
          const res = await authClient.request(options);
          return (0, util_1.marshallGaxiosResponse)(res);
        }
      } else {
        return new gaxios_1.Gaxios().request(options).then((res) => (0, util_1.marshallGaxiosResponse)(res));
      }
    }
    var ProgressStream = class extends stream.Transform {
      bytesRead = 0;
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      _transform(chunk, encoding, callback) {
        this.bytesRead += chunk.length;
        this.emit("progress", this.bytesRead);
        this.push(chunk);
        callback();
      }
    };
    function populateAPIHeader(headers, apiVersion) {
      if (!(0, isbrowser_1.isBrowser)()) {
        headers["x-goog-api-client"] = `gdcl/${pkg.version} gl-node/${process.versions.node}`;
      }
      if (apiVersion) {
        headers["x-goog-api-version"] = apiVersion;
      }
    }
  }
});

// node_modules/googleapis-common/build/src/authplus.js
var require_authplus = __commonJS({
  "node_modules/googleapis-common/build/src/authplus.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AuthPlus = void 0;
    var google_auth_library_1 = require_src8();
    var AuthPlus = class extends google_auth_library_1.GoogleAuth {
      JWT = google_auth_library_1.JWT;
      Compute = google_auth_library_1.Compute;
      OAuth2 = google_auth_library_1.OAuth2Client;
      GoogleAuth = google_auth_library_1.GoogleAuth;
      AwsClient = google_auth_library_1.AwsClient;
      IdentityPoolClient = google_auth_library_1.IdentityPoolClient;
      ExternalAccountClient = google_auth_library_1.ExternalAccountClient;
      _cachedAuth;
      /**
       * Override getClient(), memoizing an instance of auth for
       * subsequent calls to getProjectId().
       */
      async getClient(options) {
        this._cachedAuth = new google_auth_library_1.GoogleAuth(options);
        return this._cachedAuth.getClient();
      }
      getProjectId(callback) {
        if (callback) {
          return this._cachedAuth ? this._cachedAuth.getProjectId(callback) : super.getProjectId(callback);
        } else {
          return this._cachedAuth ? this._cachedAuth.getProjectId() : super.getProjectId();
        }
      }
    };
    exports2.AuthPlus = AuthPlus;
  }
});

// node_modules/googleapis-common/build/src/endpoint.js
var require_endpoint = __commonJS({
  "node_modules/googleapis-common/build/src/endpoint.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Endpoint = void 0;
    var apirequest_1 = require_apirequest();
    var Endpoint = class {
      _options;
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      google;
      constructor(options) {
        this._options = options || {};
      }
      /**
       * Given a schema, add methods and resources to a target.
       *
       * @param {object} target The target to which to apply the schema.
       * @param {object} rootSchema The top-level schema, so we don't lose track of it
       * during recursion.
       * @param {object} schema The current schema from which to extract methods and
       * resources.
       * @param {object} context The context to add to each method.
       */
      applySchema(target, rootSchema, schema, context) {
        this.applyMethodsFromSchema(target, rootSchema, schema, context);
        if (schema.resources) {
          for (const resourceName in schema.resources) {
            if (Object.prototype.hasOwnProperty.call(schema.resources, resourceName)) {
              const resource = schema.resources[resourceName];
              if (!target[resourceName]) {
                target[resourceName] = {};
              }
              this.applySchema(target[resourceName], rootSchema, resource, context);
            }
          }
        }
      }
      /**
       * Given a schema, add methods to a target.
       *
       * @param {object} target The target to which to apply the methods.
       * @param {object} rootSchema The top-level schema, so we don't lose track of it
       * during recursion.
       * @param {object} schema The current schema from which to extract methods.
       * @param {object} context The context to add to each method.
       */
      applyMethodsFromSchema(target, rootSchema, schema, context) {
        if (schema.methods) {
          for (const name in schema.methods) {
            if (Object.prototype.hasOwnProperty.call(schema.methods, name)) {
              const method = schema.methods[name];
              target[name] = this.makeMethod(rootSchema, method, context);
            }
          }
        }
      }
      /**
       * Given a method schema, add a method to a target.
       *
       * @param target The target to which to add the method.
       * @param schema The top-level schema that contains the rootUrl, etc.
       * @param method The method schema from which to generate the method.
       * @param context The context to add to the method.
       */
      makeMethod(schema, method, context) {
        return (paramsOrCallback, callback) => {
          const params = typeof paramsOrCallback === "function" ? {} : paramsOrCallback;
          callback = typeof paramsOrCallback === "function" ? paramsOrCallback : callback;
          const schemaUrl = buildurl(schema.rootUrl + schema.servicePath + method.path);
          const parameters = {
            options: {
              url: schemaUrl.substring(1, schemaUrl.length - 1),
              method: method.httpMethod,
              apiVersion: method.apiVersion
            },
            params,
            requiredParams: method.parameterOrder || [],
            pathParams: this.getPathParams(method.parameters),
            context
          };
          if (method.mediaUpload && method.mediaUpload.protocols && method.mediaUpload.protocols.simple && method.mediaUpload.protocols.simple.path) {
            const mediaUrl = buildurl(schema.rootUrl + method.mediaUpload.protocols.simple.path);
            parameters.mediaUrl = mediaUrl.substring(1, mediaUrl.length - 1);
          }
          if (!callback) {
            return (0, apirequest_1.createAPIRequest)(parameters);
          }
          (0, apirequest_1.createAPIRequest)(parameters, callback);
          return;
        };
      }
      getPathParams(params) {
        const pathParams = new Array();
        if (typeof params !== "object") {
          params = {};
        }
        Object.keys(params).forEach((key) => {
          if (params[key].location === "path") {
            pathParams.push(key);
          }
        });
        return pathParams;
      }
    };
    exports2.Endpoint = Endpoint;
    function buildurl(input) {
      return input ? `'${input}'`.replace(/([^:]\/)\/+/g, "$1") : "";
    }
  }
});

// node_modules/googleapis-common/build/src/discovery.js
var require_discovery = __commonJS({
  "node_modules/googleapis-common/build/src/discovery.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Discovery = void 0;
    var fs2 = require("fs");
    var gaxios_1 = require_src5();
    var resolve2 = require("url");
    var util2 = require("util");
    var apirequest_1 = require_apirequest();
    var endpoint_1 = require_endpoint();
    var readFile = util2.promisify(fs2.readFile);
    var Discovery = class {
      transporter = new gaxios_1.Gaxios();
      options;
      /**
       * Discovery for discovering API endpoints
       *
       * @param options Options for discovery
       */
      constructor(options) {
        this.options = options || {};
      }
      /**
       * Generate and Endpoint from an endpoint schema object.
       *
       * @param schema The schema from which to generate the Endpoint.
       * @return A function that creates an endpoint.
       */
      makeEndpoint(schema) {
        return (options) => {
          const ep = new endpoint_1.Endpoint(options);
          ep.applySchema(ep, schema, schema, ep);
          return ep;
        };
      }
      /**
       * Log output of generator. Works just like console.log
       */
      log(...args) {
        if (this.options && this.options.debug) {
          console.log(...args);
        }
      }
      /**
       * Generate all APIs and return as in-memory object.
       * @param discoveryUrl
       */
      async discoverAllAPIs(discoveryUrl) {
        const headers = new Headers(this.options.includePrivate ? {} : { "X-User-Ip": "0.0.0.0" });
        const res = await this.transporter.request({
          url: discoveryUrl,
          headers
        });
        const items = res.data.items;
        const apis = await Promise.all(items.map(async (api) => {
          const endpointCreator = await this.discoverAPI(api.discoveryRestUrl);
          return { api, endpointCreator };
        }));
        const versionIndex = {};
        const apisIndex = {};
        for (const set2 of apis) {
          if (!apisIndex[set2.api.name]) {
            versionIndex[set2.api.name] = {};
            apisIndex[set2.api.name] = (options) => {
              const type = typeof options;
              let version2;
              if (type === "string") {
                version2 = options;
                options = {};
              } else if (type === "object") {
                version2 = options.version;
                delete options.version;
              } else {
                throw new Error("Argument error: Accepts only string or object");
              }
              try {
                const ep = set2.endpointCreator(options, this);
                return Object.freeze(ep);
              } catch (e2) {
                throw new Error(util2.format('Unable to load endpoint %s("%s"): %s', set2.api.name, version2, e2.message));
              }
            };
          }
          versionIndex[set2.api.name][set2.api.version] = set2.endpointCreator;
        }
        return apisIndex;
      }
      /**
       * Generate API file given discovery URL
       *
       * @param apiDiscoveryUrl URL or filename of discovery doc for API
       * @returns A promise that resolves with a function that creates the endpoint
       */
      async discoverAPI(apiDiscoveryUrl) {
        if (typeof apiDiscoveryUrl === "string") {
          const parts = resolve2.parse(apiDiscoveryUrl);
          if (apiDiscoveryUrl && !parts.protocol) {
            this.log("Reading from file " + apiDiscoveryUrl);
            const file2 = await readFile(apiDiscoveryUrl, { encoding: "utf8" });
            return this.makeEndpoint(JSON.parse(file2));
          } else {
            this.log("Requesting " + apiDiscoveryUrl);
            const res = await this.transporter.request({
              url: apiDiscoveryUrl
            });
            return this.makeEndpoint(res.data);
          }
        } else {
          const options = apiDiscoveryUrl;
          this.log("Requesting " + options.url);
          const url2 = options.url;
          delete options.url;
          const parameters = {
            options: { url: url2, method: "GET" },
            requiredParams: [],
            pathParams: [],
            params: options,
            context: { google: { _options: {} }, _options: {} }
          };
          const res = await (0, apirequest_1.createAPIRequest)(parameters);
          return this.makeEndpoint(res.data);
        }
      }
    };
    exports2.Discovery = Discovery;
  }
});

// node_modules/googleapis-common/build/src/index.js
var require_src9 = __commonJS({
  "node_modules/googleapis-common/build/src/index.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __exportStar = exports2 && exports2.__exportStar || function(m2, exports3) {
      for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m2, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Endpoint = exports2.Discovery = exports2.AuthPlus = exports2.createAPIRequest = exports2.getAPI = exports2.GaxiosError = exports2.Gaxios = exports2.AwsClient = exports2.IdentityPoolClient = exports2.BaseExternalAccountClient = exports2.ExternalAccountClient = exports2.GoogleAuth = exports2.UserRefreshClient = exports2.Compute = exports2.JWT = exports2.OAuth2Client = exports2.gaxios = exports2.googleAuthLibrary = void 0;
    exports2.googleAuthLibrary = require_src8();
    exports2.gaxios = require_src5();
    var google_auth_library_1 = require_src8();
    Object.defineProperty(exports2, "OAuth2Client", { enumerable: true, get: function() {
      return google_auth_library_1.OAuth2Client;
    } });
    Object.defineProperty(exports2, "JWT", { enumerable: true, get: function() {
      return google_auth_library_1.JWT;
    } });
    Object.defineProperty(exports2, "Compute", { enumerable: true, get: function() {
      return google_auth_library_1.Compute;
    } });
    Object.defineProperty(exports2, "UserRefreshClient", { enumerable: true, get: function() {
      return google_auth_library_1.UserRefreshClient;
    } });
    Object.defineProperty(exports2, "GoogleAuth", { enumerable: true, get: function() {
      return google_auth_library_1.GoogleAuth;
    } });
    Object.defineProperty(exports2, "ExternalAccountClient", { enumerable: true, get: function() {
      return google_auth_library_1.ExternalAccountClient;
    } });
    Object.defineProperty(exports2, "BaseExternalAccountClient", { enumerable: true, get: function() {
      return google_auth_library_1.BaseExternalAccountClient;
    } });
    Object.defineProperty(exports2, "IdentityPoolClient", { enumerable: true, get: function() {
      return google_auth_library_1.IdentityPoolClient;
    } });
    Object.defineProperty(exports2, "AwsClient", { enumerable: true, get: function() {
      return google_auth_library_1.AwsClient;
    } });
    var gaxios_1 = require_src5();
    Object.defineProperty(exports2, "Gaxios", { enumerable: true, get: function() {
      return gaxios_1.Gaxios;
    } });
    Object.defineProperty(exports2, "GaxiosError", { enumerable: true, get: function() {
      return gaxios_1.GaxiosError;
    } });
    var apiIndex_1 = require_apiIndex();
    Object.defineProperty(exports2, "getAPI", { enumerable: true, get: function() {
      return apiIndex_1.getAPI;
    } });
    var apirequest_1 = require_apirequest();
    Object.defineProperty(exports2, "createAPIRequest", { enumerable: true, get: function() {
      return apirequest_1.createAPIRequest;
    } });
    var authplus_1 = require_authplus();
    Object.defineProperty(exports2, "AuthPlus", { enumerable: true, get: function() {
      return authplus_1.AuthPlus;
    } });
    var discovery_1 = require_discovery();
    Object.defineProperty(exports2, "Discovery", { enumerable: true, get: function() {
      return discovery_1.Discovery;
    } });
    var endpoint_1 = require_endpoint();
    Object.defineProperty(exports2, "Endpoint", { enumerable: true, get: function() {
      return endpoint_1.Endpoint;
    } });
    __exportStar(require_util4(), exports2);
  }
});

// node_modules/@googleapis/youtube/build/v3.js
var require_v3 = __commonJS({
  "node_modules/@googleapis/youtube/build/v3.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.youtube_v3 = void 0;
    var googleapis_common_1 = require_src9();
    var youtube_v3;
    (function(youtube_v32) {
      class Youtube {
        context;
        abuseReports;
        activities;
        captions;
        channelBanners;
        channels;
        channelSections;
        comments;
        commentThreads;
        i18nLanguages;
        i18nRegions;
        liveBroadcasts;
        liveChatBans;
        liveChatMessages;
        liveChatModerators;
        liveStreams;
        members;
        membershipsLevels;
        playlistImages;
        playlistItems;
        playlists;
        search;
        subscriptions;
        superChatEvents;
        tests;
        thirdPartyLinks;
        thumbnails;
        videoAbuseReportReasons;
        videoCategories;
        videos;
        videoTrainability;
        watermarks;
        youtube;
        constructor(options, google2) {
          this.context = {
            _options: options || {},
            google: google2
          };
          this.abuseReports = new Resource$Abusereports(this.context);
          this.activities = new Resource$Activities(this.context);
          this.captions = new Resource$Captions(this.context);
          this.channelBanners = new Resource$Channelbanners(this.context);
          this.channels = new Resource$Channels(this.context);
          this.channelSections = new Resource$Channelsections(this.context);
          this.comments = new Resource$Comments(this.context);
          this.commentThreads = new Resource$Commentthreads(this.context);
          this.i18nLanguages = new Resource$I18nlanguages(this.context);
          this.i18nRegions = new Resource$I18nregions(this.context);
          this.liveBroadcasts = new Resource$Livebroadcasts(this.context);
          this.liveChatBans = new Resource$Livechatbans(this.context);
          this.liveChatMessages = new Resource$Livechatmessages(this.context);
          this.liveChatModerators = new Resource$Livechatmoderators(this.context);
          this.liveStreams = new Resource$Livestreams(this.context);
          this.members = new Resource$Members(this.context);
          this.membershipsLevels = new Resource$Membershipslevels(this.context);
          this.playlistImages = new Resource$Playlistimages(this.context);
          this.playlistItems = new Resource$Playlistitems(this.context);
          this.playlists = new Resource$Playlists(this.context);
          this.search = new Resource$Search(this.context);
          this.subscriptions = new Resource$Subscriptions(this.context);
          this.superChatEvents = new Resource$Superchatevents(this.context);
          this.tests = new Resource$Tests(this.context);
          this.thirdPartyLinks = new Resource$Thirdpartylinks(this.context);
          this.thumbnails = new Resource$Thumbnails(this.context);
          this.videoAbuseReportReasons = new Resource$Videoabusereportreasons(this.context);
          this.videoCategories = new Resource$Videocategories(this.context);
          this.videos = new Resource$Videos(this.context);
          this.videoTrainability = new Resource$Videotrainability(this.context);
          this.watermarks = new Resource$Watermarks(this.context);
          this.youtube = new Resource$Youtube(this.context);
        }
      }
      youtube_v32.Youtube = Youtube;
      class Resource$Abusereports {
        context;
        constructor(context) {
          this.context = context;
        }
        insert(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/abuseReports").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Abusereports = Resource$Abusereports;
      class Resource$Activities {
        context;
        constructor(context) {
          this.context = context;
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/activities").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Activities = Resource$Activities;
      class Resource$Captions {
        context;
        constructor(context) {
          this.context = context;
        }
        delete(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/captions").replace(/([^:]\/)\/+/g, "$1"),
              method: "DELETE",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["id"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        download(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/captions/{id}").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["id"],
            pathParams: ["id"],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        insert(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/captions").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            mediaUrl: (rootUrl + "/upload/youtube/v3/captions").replace(/([^:]\/)\/+/g, "$1"),
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/captions").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part", "videoId"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        update(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/captions").replace(/([^:]\/)\/+/g, "$1"),
              method: "PUT",
              apiVersion: ""
            }, options),
            params,
            mediaUrl: (rootUrl + "/upload/youtube/v3/captions").replace(/([^:]\/)\/+/g, "$1"),
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Captions = Resource$Captions;
      class Resource$Channelbanners {
        context;
        constructor(context) {
          this.context = context;
        }
        insert(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/channelBanners/insert").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            mediaUrl: (rootUrl + "/upload/youtube/v3/channelBanners/insert").replace(/([^:]\/)\/+/g, "$1"),
            requiredParams: [],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Channelbanners = Resource$Channelbanners;
      class Resource$Channels {
        context;
        constructor(context) {
          this.context = context;
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/channels").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        update(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/channels").replace(/([^:]\/)\/+/g, "$1"),
              method: "PUT",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Channels = Resource$Channels;
      class Resource$Channelsections {
        context;
        constructor(context) {
          this.context = context;
        }
        delete(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/channelSections").replace(/([^:]\/)\/+/g, "$1"),
              method: "DELETE",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["id"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        insert(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/channelSections").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/channelSections").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        update(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/channelSections").replace(/([^:]\/)\/+/g, "$1"),
              method: "PUT",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Channelsections = Resource$Channelsections;
      class Resource$Comments {
        context;
        constructor(context) {
          this.context = context;
        }
        delete(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/comments").replace(/([^:]\/)\/+/g, "$1"),
              method: "DELETE",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["id"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        insert(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/comments").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/comments").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        markAsSpam(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/comments/markAsSpam").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["id"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        setModerationStatus(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/comments/setModerationStatus").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["id", "moderationStatus"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        update(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/comments").replace(/([^:]\/)\/+/g, "$1"),
              method: "PUT",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Comments = Resource$Comments;
      class Resource$Commentthreads {
        context;
        constructor(context) {
          this.context = context;
        }
        insert(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/commentThreads").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/commentThreads").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Commentthreads = Resource$Commentthreads;
      class Resource$I18nlanguages {
        context;
        constructor(context) {
          this.context = context;
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/i18nLanguages").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$I18nlanguages = Resource$I18nlanguages;
      class Resource$I18nregions {
        context;
        constructor(context) {
          this.context = context;
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/i18nRegions").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$I18nregions = Resource$I18nregions;
      class Resource$Livebroadcasts {
        context;
        constructor(context) {
          this.context = context;
        }
        bind(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveBroadcasts/bind").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["id", "part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        delete(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveBroadcasts").replace(/([^:]\/)\/+/g, "$1"),
              method: "DELETE",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["id"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        insert(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveBroadcasts").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        insertCuepoint(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveBroadcasts/cuepoint").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: [],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveBroadcasts").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        transition(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveBroadcasts/transition").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["broadcastStatus", "id", "part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        update(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveBroadcasts").replace(/([^:]\/)\/+/g, "$1"),
              method: "PUT",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Livebroadcasts = Resource$Livebroadcasts;
      class Resource$Livechatbans {
        context;
        constructor(context) {
          this.context = context;
        }
        delete(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveChat/bans").replace(/([^:]\/)\/+/g, "$1"),
              method: "DELETE",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["id"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        insert(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveChat/bans").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Livechatbans = Resource$Livechatbans;
      class Resource$Livechatmessages {
        context;
        constructor(context) {
          this.context = context;
        }
        delete(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveChat/messages").replace(/([^:]\/)\/+/g, "$1"),
              method: "DELETE",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["id"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        insert(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveChat/messages").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveChat/messages").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["liveChatId", "part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        transition(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveChat/messages/transition").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: [],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Livechatmessages = Resource$Livechatmessages;
      class Resource$Livechatmoderators {
        context;
        constructor(context) {
          this.context = context;
        }
        delete(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveChat/moderators").replace(/([^:]\/)\/+/g, "$1"),
              method: "DELETE",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["id"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        insert(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveChat/moderators").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveChat/moderators").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["liveChatId", "part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Livechatmoderators = Resource$Livechatmoderators;
      class Resource$Livestreams {
        context;
        constructor(context) {
          this.context = context;
        }
        delete(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveStreams").replace(/([^:]\/)\/+/g, "$1"),
              method: "DELETE",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["id"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        insert(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveStreams").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveStreams").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        update(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveStreams").replace(/([^:]\/)\/+/g, "$1"),
              method: "PUT",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Livestreams = Resource$Livestreams;
      class Resource$Members {
        context;
        constructor(context) {
          this.context = context;
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/members").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Members = Resource$Members;
      class Resource$Membershipslevels {
        context;
        constructor(context) {
          this.context = context;
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/membershipsLevels").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Membershipslevels = Resource$Membershipslevels;
      class Resource$Playlistimages {
        context;
        constructor(context) {
          this.context = context;
        }
        delete(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/playlistImages").replace(/([^:]\/)\/+/g, "$1"),
              method: "DELETE",
              apiVersion: ""
            }, options),
            params,
            requiredParams: [],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        insert(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/playlistImages").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            mediaUrl: (rootUrl + "/upload/youtube/v3/playlistImages").replace(/([^:]\/)\/+/g, "$1"),
            requiredParams: [],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/playlistImages").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: [],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        update(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/playlistImages").replace(/([^:]\/)\/+/g, "$1"),
              method: "PUT",
              apiVersion: ""
            }, options),
            params,
            mediaUrl: (rootUrl + "/upload/youtube/v3/playlistImages").replace(/([^:]\/)\/+/g, "$1"),
            requiredParams: [],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Playlistimages = Resource$Playlistimages;
      class Resource$Playlistitems {
        context;
        constructor(context) {
          this.context = context;
        }
        delete(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/playlistItems").replace(/([^:]\/)\/+/g, "$1"),
              method: "DELETE",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["id"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        insert(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/playlistItems").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/playlistItems").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        update(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/playlistItems").replace(/([^:]\/)\/+/g, "$1"),
              method: "PUT",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Playlistitems = Resource$Playlistitems;
      class Resource$Playlists {
        context;
        constructor(context) {
          this.context = context;
        }
        delete(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/playlists").replace(/([^:]\/)\/+/g, "$1"),
              method: "DELETE",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["id"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        insert(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/playlists").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/playlists").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        update(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/playlists").replace(/([^:]\/)\/+/g, "$1"),
              method: "PUT",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Playlists = Resource$Playlists;
      class Resource$Search {
        context;
        constructor(context) {
          this.context = context;
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/search").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Search = Resource$Search;
      class Resource$Subscriptions {
        context;
        constructor(context) {
          this.context = context;
        }
        delete(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/subscriptions").replace(/([^:]\/)\/+/g, "$1"),
              method: "DELETE",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["id"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        insert(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/subscriptions").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/subscriptions").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Subscriptions = Resource$Subscriptions;
      class Resource$Superchatevents {
        context;
        constructor(context) {
          this.context = context;
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/superChatEvents").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Superchatevents = Resource$Superchatevents;
      class Resource$Tests {
        context;
        constructor(context) {
          this.context = context;
        }
        insert(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/tests").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Tests = Resource$Tests;
      class Resource$Thirdpartylinks {
        context;
        constructor(context) {
          this.context = context;
        }
        delete(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/thirdPartyLinks").replace(/([^:]\/)\/+/g, "$1"),
              method: "DELETE",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["linkingToken", "type"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        insert(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/thirdPartyLinks").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/thirdPartyLinks").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        update(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/thirdPartyLinks").replace(/([^:]\/)\/+/g, "$1"),
              method: "PUT",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Thirdpartylinks = Resource$Thirdpartylinks;
      class Resource$Thumbnails {
        context;
        constructor(context) {
          this.context = context;
        }
        set(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/thumbnails/set").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            mediaUrl: (rootUrl + "/upload/youtube/v3/thumbnails/set").replace(/([^:]\/)\/+/g, "$1"),
            requiredParams: ["videoId"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Thumbnails = Resource$Thumbnails;
      class Resource$Videoabusereportreasons {
        context;
        constructor(context) {
          this.context = context;
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/videoAbuseReportReasons").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Videoabusereportreasons = Resource$Videoabusereportreasons;
      class Resource$Videocategories {
        context;
        constructor(context) {
          this.context = context;
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/videoCategories").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Videocategories = Resource$Videocategories;
      class Resource$Videos {
        context;
        constructor(context) {
          this.context = context;
        }
        batchGetStats(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/videos:batchGetStats").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: [],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        delete(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/videos").replace(/([^:]\/)\/+/g, "$1"),
              method: "DELETE",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["id"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        getRating(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/videos/getRating").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["id"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        insert(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/videos").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            mediaUrl: (rootUrl + "/upload/youtube/v3/videos").replace(/([^:]\/)\/+/g, "$1"),
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        list(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/videos").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        rate(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/videos/rate").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["id", "rating"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        reportAbuse(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/videos/reportAbuse").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: [],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        update(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/videos").replace(/([^:]\/)\/+/g, "$1"),
              method: "PUT",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["part"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Videos = Resource$Videos;
      class Resource$Videotrainability {
        context;
        constructor(context) {
          this.context = context;
        }
        get(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/videoTrainability").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: [],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Videotrainability = Resource$Videotrainability;
      class Resource$Watermarks {
        context;
        constructor(context) {
          this.context = context;
        }
        set(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/watermarks/set").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            mediaUrl: (rootUrl + "/upload/youtube/v3/watermarks/set").replace(/([^:]\/)\/+/g, "$1"),
            requiredParams: ["channelId"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
        unset(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/watermarks/unset").replace(/([^:]\/)\/+/g, "$1"),
              method: "POST",
              apiVersion: ""
            }, options),
            params,
            requiredParams: ["channelId"],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Watermarks = Resource$Watermarks;
      class Resource$Youtube {
        context;
        v3;
        constructor(context) {
          this.context = context;
          this.v3 = new Resource$Youtube$V3(this.context);
        }
      }
      youtube_v32.Resource$Youtube = Resource$Youtube;
      class Resource$Youtube$V3 {
        context;
        liveChat;
        constructor(context) {
          this.context = context;
          this.liveChat = new Resource$Youtube$V3$Livechat(this.context);
        }
      }
      youtube_v32.Resource$Youtube$V3 = Resource$Youtube$V3;
      class Resource$Youtube$V3$Livechat {
        context;
        messages;
        constructor(context) {
          this.context = context;
          this.messages = new Resource$Youtube$V3$Livechat$Messages(this.context);
        }
      }
      youtube_v32.Resource$Youtube$V3$Livechat = Resource$Youtube$V3$Livechat;
      class Resource$Youtube$V3$Livechat$Messages {
        context;
        constructor(context) {
          this.context = context;
        }
        stream(paramsOrCallback, optionsOrCallback, callback) {
          let params = paramsOrCallback || {};
          let options = optionsOrCallback || {};
          if (typeof paramsOrCallback === "function") {
            callback = paramsOrCallback;
            params = {};
            options = {};
          }
          if (typeof optionsOrCallback === "function") {
            callback = optionsOrCallback;
            options = {};
          }
          const rootUrl = options.rootUrl || "https://youtube.googleapis.com/";
          const parameters = {
            options: Object.assign({
              url: (rootUrl + "/youtube/v3/liveChat/messages/stream").replace(/([^:]\/)\/+/g, "$1"),
              method: "GET",
              apiVersion: ""
            }, options),
            params,
            requiredParams: [],
            pathParams: [],
            context: this.context
          };
          if (callback) {
            (0, googleapis_common_1.createAPIRequest)(parameters, callback);
          } else {
            return (0, googleapis_common_1.createAPIRequest)(parameters);
          }
        }
      }
      youtube_v32.Resource$Youtube$V3$Livechat$Messages = Resource$Youtube$V3$Livechat$Messages;
    })(youtube_v3 || (exports2.youtube_v3 = youtube_v3 = {}));
  }
});

// node_modules/@googleapis/youtube/build/index.js
var require_build = __commonJS({
  "node_modules/@googleapis/youtube/build/index.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AuthPlus = exports2.youtube_v3 = exports2.auth = exports2.VERSIONS = void 0;
    exports2.youtube = youtube;
    var googleapis_common_1 = require_src9();
    var v3_1 = require_v3();
    Object.defineProperty(exports2, "youtube_v3", { enumerable: true, get: function() {
      return v3_1.youtube_v3;
    } });
    exports2.VERSIONS = {
      v3: v3_1.youtube_v3.Youtube
    };
    function youtube(versionOrOptions) {
      return (0, googleapis_common_1.getAPI)("youtube", versionOrOptions, exports2.VERSIONS, this);
    }
    var auth = new googleapis_common_1.AuthPlus();
    exports2.auth = auth;
    var googleapis_common_2 = require_src9();
    Object.defineProperty(exports2, "AuthPlus", { enumerable: true, get: function() {
      return googleapis_common_2.AuthPlus;
    } });
  }
});

// googleapis-shim.js
var require_googleapis_shim = __commonJS({
  "googleapis-shim.js"(exports2, module2) {
    var { youtube } = require_build();
    module2.exports = { google: { youtube } };
  }
});

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

// node_modules/ajv/dist/compile/codegen/scope.js
var require_scope = __commonJS({
  "node_modules/ajv/dist/compile/codegen/scope.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ValueScope = exports2.ValueScopeName = exports2.Scope = exports2.varKinds = exports2.UsedValueState = void 0;
    var code_1 = require_code();
    var ValueError = class extends Error {
      constructor(name) {
        super(`CodeGen: "code" for ${name} not defined`);
        this.value = name.value;
      }
    };
    var UsedValueState;
    (function(UsedValueState2) {
      UsedValueState2[UsedValueState2["Started"] = 0] = "Started";
      UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed";
    })(UsedValueState || (exports2.UsedValueState = UsedValueState = {}));
    exports2.varKinds = {
      const: new code_1.Name("const"),
      let: new code_1.Name("let"),
      var: new code_1.Name("var")
    };
    var Scope = class {
      constructor({ prefixes, parent } = {}) {
        this._names = {};
        this._prefixes = prefixes;
        this._parent = parent;
      }
      toName(nameOrPrefix) {
        return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
      }
      name(prefix) {
        return new code_1.Name(this._newName(prefix));
      }
      _newName(prefix) {
        const ng = this._names[prefix] || this._nameGroup(prefix);
        return `${prefix}${ng.index++}`;
      }
      _nameGroup(prefix) {
        var _a3, _b;
        if (((_b = (_a3 = this._parent) === null || _a3 === void 0 ? void 0 : _a3._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) {
          throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
        }
        return this._names[prefix] = { prefix, index: 0 };
      }
    };
    exports2.Scope = Scope;
    var ValueScopeName = class extends code_1.Name {
      constructor(prefix, nameStr) {
        super(nameStr);
        this.prefix = prefix;
      }
      setValue(value, { property, itemIndex }) {
        this.value = value;
        this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`;
      }
    };
    exports2.ValueScopeName = ValueScopeName;
    var line = (0, code_1._)`\n`;
    var ValueScope = class extends Scope {
      constructor(opts) {
        super(opts);
        this._values = {};
        this._scope = opts.scope;
        this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };
      }
      get() {
        return this._scope;
      }
      name(prefix) {
        return new ValueScopeName(prefix, this._newName(prefix));
      }
      value(nameOrPrefix, value) {
        var _a3;
        if (value.ref === void 0)
          throw new Error("CodeGen: ref must be passed in value");
        const name = this.toName(nameOrPrefix);
        const { prefix } = name;
        const valueKey = (_a3 = value.key) !== null && _a3 !== void 0 ? _a3 : value.ref;
        let vs = this._values[prefix];
        if (vs) {
          const _name = vs.get(valueKey);
          if (_name)
            return _name;
        } else {
          vs = this._values[prefix] = /* @__PURE__ */ new Map();
        }
        vs.set(valueKey, name);
        const s2 = this._scope[prefix] || (this._scope[prefix] = []);
        const itemIndex = s2.length;
        s2[itemIndex] = value.ref;
        name.setValue(value, { property: prefix, itemIndex });
        return name;
      }
      getValue(prefix, keyOrRef) {
        const vs = this._values[prefix];
        if (!vs)
          return;
        return vs.get(keyOrRef);
      }
      scopeRefs(scopeName, values = this._values) {
        return this._reduceValues(values, (name) => {
          if (name.scopePath === void 0)
            throw new Error(`CodeGen: name "${name}" has no value`);
          return (0, code_1._)`${scopeName}${name.scopePath}`;
        });
      }
      scopeCode(values = this._values, usedValues, getCode) {
        return this._reduceValues(values, (name) => {
          if (name.value === void 0)
            throw new Error(`CodeGen: name "${name}" has no value`);
          return name.value.code;
        }, usedValues, getCode);
      }
      _reduceValues(values, valueCode, usedValues = {}, getCode) {
        let code = code_1.nil;
        for (const prefix in values) {
          const vs = values[prefix];
          if (!vs)
            continue;
          const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map();
          vs.forEach((name) => {
            if (nameSet.has(name))
              return;
            nameSet.set(name, UsedValueState.Started);
            let c = valueCode(name);
            if (c) {
              const def = this.opts.es5 ? exports2.varKinds.var : exports2.varKinds.const;
              code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`;
            } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) {
              code = (0, code_1._)`${code}${c}${this.opts._n}`;
            } else {
              throw new ValueError(name);
            }
            nameSet.set(name, UsedValueState.Completed);
          });
        }
        return code;
      }
    };
    exports2.ValueScope = ValueScope;
  }
});

// node_modules/ajv/dist/compile/codegen/index.js
var require_codegen = __commonJS({
  "node_modules/ajv/dist/compile/codegen/index.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.or = exports2.and = exports2.not = exports2.CodeGen = exports2.operators = exports2.varKinds = exports2.ValueScopeName = exports2.ValueScope = exports2.Scope = exports2.Name = exports2.regexpCode = exports2.stringify = exports2.getProperty = exports2.nil = exports2.strConcat = exports2.str = exports2._ = void 0;
    var code_1 = require_code();
    var scope_1 = require_scope();
    var code_2 = require_code();
    Object.defineProperty(exports2, "_", { enumerable: true, get: function() {
      return code_2._;
    } });
    Object.defineProperty(exports2, "str", { enumerable: true, get: function() {
      return code_2.str;
    } });
    Object.defineProperty(exports2, "strConcat", { enumerable: true, get: function() {
      return code_2.strConcat;
    } });
    Object.defineProperty(exports2, "nil", { enumerable: true, get: function() {
      return code_2.nil;
    } });
    Object.defineProperty(exports2, "getProperty", { enumerable: true, get: function() {
      return code_2.getProperty;
    } });
    Object.defineProperty(exports2, "stringify", { enumerable: true, get: function() {
      return code_2.stringify;
    } });
    Object.defineProperty(exports2, "regexpCode", { enumerable: true, get: function() {
      return code_2.regexpCode;
    } });
    Object.defineProperty(exports2, "Name", { enumerable: true, get: function() {
      return code_2.Name;
    } });
    var scope_2 = require_scope();
    Object.defineProperty(exports2, "Scope", { enumerable: true, get: function() {
      return scope_2.Scope;
    } });
    Object.defineProperty(exports2, "ValueScope", { enumerable: true, get: function() {
      return scope_2.ValueScope;
    } });
    Object.defineProperty(exports2, "ValueScopeName", { enumerable: true, get: function() {
      return scope_2.ValueScopeName;
    } });
    Object.defineProperty(exports2, "varKinds", { enumerable: true, get: function() {
      return scope_2.varKinds;
    } });
    exports2.operators = {
      GT: new code_1._Code(">"),
      GTE: new code_1._Code(">="),
      LT: new code_1._Code("<"),
      LTE: new code_1._Code("<="),
      EQ: new code_1._Code("==="),
      NEQ: new code_1._Code("!=="),
      NOT: new code_1._Code("!"),
      OR: new code_1._Code("||"),
      AND: new code_1._Code("&&"),
      ADD: new code_1._Code("+")
    };
    var Node = class {
      optimizeNodes() {
        return this;
      }
      optimizeNames(_names, _constants) {
        return this;
      }
    };
    var Def = class extends Node {
      constructor(varKind, name, rhs) {
        super();
        this.varKind = varKind;
        this.name = name;
        this.rhs = rhs;
      }
      render({ es5, _n }) {
        const varKind = es5 ? scope_1.varKinds.var : this.varKind;
        const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
        return `${varKind} ${this.name}${rhs};` + _n;
      }
      optimizeNames(names, constants) {
        if (!names[this.name.str])
          return;
        if (this.rhs)
          this.rhs = optimizeExpr(this.rhs, names, constants);
        return this;
      }
      get names() {
        return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
      }
    };
    var Assign = class extends Node {
      constructor(lhs, rhs, sideEffects) {
        super();
        this.lhs = lhs;
        this.rhs = rhs;
        this.sideEffects = sideEffects;
      }
      render({ _n }) {
        return `${this.lhs} = ${this.rhs};` + _n;
      }
      optimizeNames(names, constants) {
        if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
          return;
        this.rhs = optimizeExpr(this.rhs, names, constants);
        return this;
      }
      get names() {
        const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
        return addExprNames(names, this.rhs);
      }
    };
    var AssignOp = class extends Assign {
      constructor(lhs, op, rhs, sideEffects) {
        super(lhs, rhs, sideEffects);
        this.op = op;
      }
      render({ _n }) {
        return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
      }
    };
    var Label = class extends Node {
      constructor(label) {
        super();
        this.label = label;
        this.names = {};
      }
      render({ _n }) {
        return `${this.label}:` + _n;
      }
    };
    var Break = class extends Node {
      constructor(label) {
        super();
        this.label = label;
        this.names = {};
      }
      render({ _n }) {
        const label = this.label ? ` ${this.label}` : "";
        return `break${label};` + _n;
      }
    };
    var Throw = class extends Node {
      constructor(error51) {
        super();
        this.error = error51;
      }
      render({ _n }) {
        return `throw ${this.error};` + _n;
      }
      get names() {
        return this.error.names;
      }
    };
    var AnyCode = class extends Node {
      constructor(code) {
        super();
        this.code = code;
      }
      render({ _n }) {
        return `${this.code};` + _n;
      }
      optimizeNodes() {
        return `${this.code}` ? this : void 0;
      }
      optimizeNames(names, constants) {
        this.code = optimizeExpr(this.code, names, constants);
        return this;
      }
      get names() {
        return this.code instanceof code_1._CodeOrName ? this.code.names : {};
      }
    };
    var ParentNode = class extends Node {
      constructor(nodes = []) {
        super();
        this.nodes = nodes;
      }
      render(opts) {
        return this.nodes.reduce((code, n) => code + n.render(opts), "");
      }
      optimizeNodes() {
        const { nodes } = this;
        let i2 = nodes.length;
        while (i2--) {
          const n = nodes[i2].optimizeNodes();
          if (Array.isArray(n))
            nodes.splice(i2, 1, ...n);
          else if (n)
            nodes[i2] = n;
          else
            nodes.splice(i2, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      optimizeNames(names, constants) {
        const { nodes } = this;
        let i2 = nodes.length;
        while (i2--) {
          const n = nodes[i2];
          if (n.optimizeNames(names, constants))
            continue;
          subtractNames(names, n.names);
          nodes.splice(i2, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      get names() {
        return this.nodes.reduce((names, n) => addNames(names, n.names), {});
      }
    };
    var BlockNode = class extends ParentNode {
      render(opts) {
        return "{" + opts._n + super.render(opts) + "}" + opts._n;
      }
    };
    var Root = class extends ParentNode {
    };
    var Else = class extends BlockNode {
    };
    Else.kind = "else";
    var If = class _If extends BlockNode {
      constructor(condition, nodes) {
        super(nodes);
        this.condition = condition;
      }
      render(opts) {
        let code = `if(${this.condition})` + super.render(opts);
        if (this.else)
          code += "else " + this.else.render(opts);
        return code;
      }
      optimizeNodes() {
        super.optimizeNodes();
        const cond = this.condition;
        if (cond === true)
          return this.nodes;
        let e2 = this.else;
        if (e2) {
          const ns = e2.optimizeNodes();
          e2 = this.else = Array.isArray(ns) ? new Else(ns) : ns;
        }
        if (e2) {
          if (cond === false)
            return e2 instanceof _If ? e2 : e2.nodes;
          if (this.nodes.length)
            return this;
          return new _If(not(cond), e2 instanceof _If ? [e2] : e2.nodes);
        }
        if (cond === false || !this.nodes.length)
          return void 0;
        return this;
      }
      optimizeNames(names, constants) {
        var _a3;
        this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants);
        if (!(super.optimizeNames(names, constants) || this.else))
          return;
        this.condition = optimizeExpr(this.condition, names, constants);
        return this;
      }
      get names() {
        const names = super.names;
        addExprNames(names, this.condition);
        if (this.else)
          addNames(names, this.else.names);
        return names;
      }
    };
    If.kind = "if";
    var For = class extends BlockNode {
    };
    For.kind = "for";
    var ForLoop = class extends For {
      constructor(iteration) {
        super();
        this.iteration = iteration;
      }
      render(opts) {
        return `for(${this.iteration})` + super.render(opts);
      }
      optimizeNames(names, constants) {
        if (!super.optimizeNames(names, constants))
          return;
        this.iteration = optimizeExpr(this.iteration, names, constants);
        return this;
      }
      get names() {
        return addNames(super.names, this.iteration.names);
      }
    };
    var ForRange = class extends For {
      constructor(varKind, name, from, to) {
        super();
        this.varKind = varKind;
        this.name = name;
        this.from = from;
        this.to = to;
      }
      render(opts) {
        const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
        const { name, from, to } = this;
        return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
      }
      get names() {
        const names = addExprNames(super.names, this.from);
        return addExprNames(names, this.to);
      }
    };
    var ForIter = class extends For {
      constructor(loop, varKind, name, iterable) {
        super();
        this.loop = loop;
        this.varKind = varKind;
        this.name = name;
        this.iterable = iterable;
      }
      render(opts) {
        return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
      }
      optimizeNames(names, constants) {
        if (!super.optimizeNames(names, constants))
          return;
        this.iterable = optimizeExpr(this.iterable, names, constants);
        return this;
      }
      get names() {
        return addNames(super.names, this.iterable.names);
      }
    };
    var Func = class extends BlockNode {
      constructor(name, args, async) {
        super();
        this.name = name;
        this.args = args;
        this.async = async;
      }
      render(opts) {
        const _async = this.async ? "async " : "";
        return `${_async}function ${this.name}(${this.args})` + super.render(opts);
      }
    };
    Func.kind = "func";
    var Return = class extends ParentNode {
      render(opts) {
        return "return " + super.render(opts);
      }
    };
    Return.kind = "return";
    var Try = class extends BlockNode {
      render(opts) {
        let code = "try" + super.render(opts);
        if (this.catch)
          code += this.catch.render(opts);
        if (this.finally)
          code += this.finally.render(opts);
        return code;
      }
      optimizeNodes() {
        var _a3, _b;
        super.optimizeNodes();
        (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNodes();
        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
        return this;
      }
      optimizeNames(names, constants) {
        var _a3, _b;
        super.optimizeNames(names, constants);
        (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants);
        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);
        return this;
      }
      get names() {
        const names = super.names;
        if (this.catch)
          addNames(names, this.catch.names);
        if (this.finally)
          addNames(names, this.finally.names);
        return names;
      }
    };
    var Catch = class extends BlockNode {
      constructor(error51) {
        super();
        this.error = error51;
      }
      render(opts) {
        return `catch(${this.error})` + super.render(opts);
      }
    };
    Catch.kind = "catch";
    var Finally = class extends BlockNode {
      render(opts) {
        return "finally" + super.render(opts);
      }
    };
    Finally.kind = "finally";
    var CodeGen = class {
      constructor(extScope, opts = {}) {
        this._values = {};
        this._blockStarts = [];
        this._constants = {};
        this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
        this._extScope = extScope;
        this._scope = new scope_1.Scope({ parent: extScope });
        this._nodes = [new Root()];
      }
      toString() {
        return this._root.render(this.opts);
      }
      // returns unique name in the internal scope
      name(prefix) {
        return this._scope.name(prefix);
      }
      // reserves unique name in the external scope
      scopeName(prefix) {
        return this._extScope.name(prefix);
      }
      // reserves unique name in the external scope and assigns value to it
      scopeValue(prefixOrName, value) {
        const name = this._extScope.value(prefixOrName, value);
        const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set());
        vs.add(name);
        return name;
      }
      getScopeValue(prefix, keyOrRef) {
        return this._extScope.getValue(prefix, keyOrRef);
      }
      // return code that assigns values in the external scope to the names that are used internally
      // (same names that were returned by gen.scopeName or gen.scopeValue)
      scopeRefs(scopeName) {
        return this._extScope.scopeRefs(scopeName, this._values);
      }
      scopeCode() {
        return this._extScope.scopeCode(this._values);
      }
      _def(varKind, nameOrPrefix, rhs, constant) {
        const name = this._scope.toName(nameOrPrefix);
        if (rhs !== void 0 && constant)
          this._constants[name.str] = rhs;
        this._leafNode(new Def(varKind, name, rhs));
        return name;
      }
      // `const` declaration (`var` in es5 mode)
      const(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
      }
      // `let` declaration with optional assignment (`var` in es5 mode)
      let(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
      }
      // `var` declaration with optional assignment
      var(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
      }
      // assignment code
      assign(lhs, rhs, sideEffects) {
        return this._leafNode(new Assign(lhs, rhs, sideEffects));
      }
      // `+=` code
      add(lhs, rhs) {
        return this._leafNode(new AssignOp(lhs, exports2.operators.ADD, rhs));
      }
      // appends passed SafeExpr to code or executes Block
      code(c) {
        if (typeof c == "function")
          c();
        else if (c !== code_1.nil)
          this._leafNode(new AnyCode(c));
        return this;
      }
      // returns code for object literal for the passed argument list of key-value pairs
      object(...keyValues) {
        const code = ["{"];
        for (const [key, value] of keyValues) {
          if (code.length > 1)
            code.push(",");
          code.push(key);
          if (key !== value || this.opts.es5) {
            code.push(":");
            (0, code_1.addCodeArg)(code, value);
          }
        }
        code.push("}");
        return new code_1._Code(code);
      }
      // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
      if(condition, thenBody, elseBody) {
        this._blockNode(new If(condition));
        if (thenBody && elseBody) {
          this.code(thenBody).else().code(elseBody).endIf();
        } else if (thenBody) {
          this.code(thenBody).endIf();
        } else if (elseBody) {
          throw new Error('CodeGen: "else" body without "then" body');
        }
        return this;
      }
      // `else if` clause - invalid without `if` or after `else` clauses
      elseIf(condition) {
        return this._elseNode(new If(condition));
      }
      // `else` clause - only valid after `if` or `else if` clauses
      else() {
        return this._elseNode(new Else());
      }
      // end `if` statement (needed if gen.if was used only with condition)
      endIf() {
        return this._endBlockNode(If, Else);
      }
      _for(node, forBody) {
        this._blockNode(node);
        if (forBody)
          this.code(forBody).endFor();
        return this;
      }
      // a generic `for` clause (or statement if `forBody` is passed)
      for(iteration, forBody) {
        return this._for(new ForLoop(iteration), forBody);
      }
      // `for` statement for a range of values
      forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
        const name = this._scope.toName(nameOrPrefix);
        return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
      }
      // `for-of` statement (in es5 mode replace with a normal for loop)
      forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
        const name = this._scope.toName(nameOrPrefix);
        if (this.opts.es5) {
          const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
          return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i2) => {
            this.var(name, (0, code_1._)`${arr}[${i2}]`);
            forBody(name);
          });
        }
        return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
      }
      // `for-in` statement.
      // With option `ownProperties` replaced with a `for-of` loop for object keys
      forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
        if (this.opts.ownProperties) {
          return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody);
        }
        const name = this._scope.toName(nameOrPrefix);
        return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
      }
      // end `for` loop
      endFor() {
        return this._endBlockNode(For);
      }
      // `label` statement
      label(label) {
        return this._leafNode(new Label(label));
      }
      // `break` statement
      break(label) {
        return this._leafNode(new Break(label));
      }
      // `return` statement
      return(value) {
        const node = new Return();
        this._blockNode(node);
        this.code(value);
        if (node.nodes.length !== 1)
          throw new Error('CodeGen: "return" should have one node');
        return this._endBlockNode(Return);
      }
      // `try` statement
      try(tryBody, catchCode, finallyCode) {
        if (!catchCode && !finallyCode)
          throw new Error('CodeGen: "try" without "catch" and "finally"');
        const node = new Try();
        this._blockNode(node);
        this.code(tryBody);
        if (catchCode) {
          const error51 = this.name("e");
          this._currNode = node.catch = new Catch(error51);
          catchCode(error51);
        }
        if (finallyCode) {
          this._currNode = node.finally = new Finally();
          this.code(finallyCode);
        }
        return this._endBlockNode(Catch, Finally);
      }
      // `throw` statement
      throw(error51) {
        return this._leafNode(new Throw(error51));
      }
      // start self-balancing block
      block(body, nodeCount) {
        this._blockStarts.push(this._nodes.length);
        if (body)
          this.code(body).endBlock(nodeCount);
        return this;
      }
      // end the current self-balancing block
      endBlock(nodeCount) {
        const len = this._blockStarts.pop();
        if (len === void 0)
          throw new Error("CodeGen: not in self-balancing block");
        const toClose = this._nodes.length - len;
        if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) {
          throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
        }
        this._nodes.length = len;
        return this;
      }
      // `function` heading (or definition if funcBody is passed)
      func(name, args = code_1.nil, async, funcBody) {
        this._blockNode(new Func(name, args, async));
        if (funcBody)
          this.code(funcBody).endFunc();
        return this;
      }
      // end function definition
      endFunc() {
        return this._endBlockNode(Func);
      }
      optimize(n = 1) {
        while (n-- > 0) {
          this._root.optimizeNodes();
          this._root.optimizeNames(this._root.names, this._constants);
        }
      }
      _leafNode(node) {
        this._currNode.nodes.push(node);
        return this;
      }
      _blockNode(node) {
        this._currNode.nodes.push(node);
        this._nodes.push(node);
      }
      _endBlockNode(N1, N2) {
        const n = this._currNode;
        if (n instanceof N1 || N2 && n instanceof N2) {
          this._nodes.pop();
          return this;
        }
        throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
      }
      _elseNode(node) {
        const n = this._currNode;
        if (!(n instanceof If)) {
          throw new Error('CodeGen: "else" without "if"');
        }
        this._currNode = n.else = node;
        return this;
      }
      get _root() {
        return this._nodes[0];
      }
      get _currNode() {
        const ns = this._nodes;
        return ns[ns.length - 1];
      }
      set _currNode(node) {
        const ns = this._nodes;
        ns[ns.length - 1] = node;
      }
    };
    exports2.CodeGen = CodeGen;
    function addNames(names, from) {
      for (const n in from)
        names[n] = (names[n] || 0) + (from[n] || 0);
      return names;
    }
    function addExprNames(names, from) {
      return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
    }
    function optimizeExpr(expr, names, constants) {
      if (expr instanceof code_1.Name)
        return replaceName(expr);
      if (!canOptimize(expr))
        return expr;
      return new code_1._Code(expr._items.reduce((items, c) => {
        if (c instanceof code_1.Name)
          c = replaceName(c);
        if (c instanceof code_1._Code)
          items.push(...c._items);
        else
          items.push(c);
        return items;
      }, []));
      function replaceName(n) {
        const c = constants[n.str];
        if (c === void 0 || names[n.str] !== 1)
          return n;
        delete names[n.str];
        return c;
      }
      function canOptimize(e2) {
        return e2 instanceof code_1._Code && e2._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0);
      }
    }
    function subtractNames(names, from) {
      for (const n in from)
        names[n] = (names[n] || 0) - (from[n] || 0);
    }
    function not(x2) {
      return typeof x2 == "boolean" || typeof x2 == "number" || x2 === null ? !x2 : (0, code_1._)`!${par(x2)}`;
    }
    exports2.not = not;
    var andCode = mappend(exports2.operators.AND);
    function and(...args) {
      return args.reduce(andCode);
    }
    exports2.and = and;
    var orCode = mappend(exports2.operators.OR);
    function or(...args) {
      return args.reduce(orCode);
    }
    exports2.or = or;
    function mappend(op) {
      return (x2, y) => x2 === code_1.nil ? y : y === code_1.nil ? x2 : (0, code_1._)`${par(x2)} ${op} ${par(y)}`;
    }
    function par(x2) {
      return x2 instanceof code_1.Name ? x2 : (0, code_1._)`(${x2})`;
    }
  }
});

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

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

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

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

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

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

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

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

// node_modules/ajv/dist/vocabularies/code.js
var require_code2 = __commonJS({
  "node_modules/ajv/dist/vocabularies/code.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateUnion = exports2.validateArray = exports2.usePattern = exports2.callValidateCode = exports2.schemaProperties = exports2.allSchemaProperties = exports2.noPropertyInData = exports2.propertyInData = exports2.isOwnProperty = exports2.hasPropFunc = exports2.reportMissingProp = exports2.checkMissingProp = exports2.checkReportMissingProp = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util5();
    var names_1 = require_names();
    var util_2 = require_util5();
    function checkReportMissingProp(cxt, prop) {
      const { gen, data, it } = cxt;
      gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
        cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true);
        cxt.error();
      });
    }
    exports2.checkReportMissingProp = checkReportMissingProp;
    function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
      return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`)));
    }
    exports2.checkMissingProp = checkMissingProp;
    function reportMissingProp(cxt, missing) {
      cxt.setParams({ missingProperty: missing }, true);
      cxt.error();
    }
    exports2.reportMissingProp = reportMissingProp;
    function hasPropFunc(gen) {
      return gen.scopeValue("func", {
        // eslint-disable-next-line @typescript-eslint/unbound-method
        ref: Object.prototype.hasOwnProperty,
        code: (0, codegen_1._)`Object.prototype.hasOwnProperty`
      });
    }
    exports2.hasPropFunc = hasPropFunc;
    function isOwnProperty(gen, data, property) {
      return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`;
    }
    exports2.isOwnProperty = isOwnProperty;
    function propertyInData(gen, data, property, ownProperties) {
      const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`;
      return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond;
    }
    exports2.propertyInData = propertyInData;
    function noPropertyInData(gen, data, property, ownProperties) {
      const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`;
      return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;
    }
    exports2.noPropertyInData = noPropertyInData;
    function allSchemaProperties(schemaMap) {
      return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
    }
    exports2.allSchemaProperties = allSchemaProperties;
    function schemaProperties(it, schemaMap) {
      return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
    }
    exports2.schemaProperties = schemaProperties;
    function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
      const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
      const valCxt = [
        [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
        [names_1.default.parentData, it.parentData],
        [names_1.default.parentDataProperty, it.parentDataProperty],
        [names_1.default.rootData, names_1.default.rootData]
      ];
      if (it.opts.dynamicRef)
        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
      const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
      return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`;
    }
    exports2.callValidateCode = callValidateCode;
    var newRegExp = (0, codegen_1._)`new RegExp`;
    function usePattern({ gen, it: { opts } }, pattern) {
      const u = opts.unicodeRegExp ? "u" : "";
      const { regExp } = opts.code;
      const rx = regExp(pattern, u);
      return gen.scopeValue("pattern", {
        key: rx.toString(),
        ref: rx,
        code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`
      });
    }
    exports2.usePattern = usePattern;
    function validateArray(cxt) {
      const { gen, data, keyword, it } = cxt;
      const valid = gen.name("valid");
      if (it.allErrors) {
        const validArr = gen.let("valid", true);
        validateItems(() => gen.assign(validArr, false));
        return validArr;
      }
      gen.var(valid, true);
      validateItems(() => gen.break());
      return valid;
      function validateItems(notValid) {
        const len = gen.const("len", (0, codegen_1._)`${data}.length`);
        gen.forRange("i", 0, len, (i2) => {
          cxt.subschema({
            keyword,
            dataProp: i2,
            dataPropType: util_1.Type.Num
          }, valid);
          gen.if((0, codegen_1.not)(valid), notValid);
        });
      }
    }
    exports2.validateArray = validateArray;
    function validateUnion(cxt) {
      const { gen, schema, keyword, it } = cxt;
      if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
      const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));
      if (alwaysValid && !it.opts.unevaluated)
        return;
      const valid = gen.let("valid", false);
      const schValid = gen.name("_valid");
      gen.block(() => schema.forEach((_sch, i2) => {
        const schCxt = cxt.subschema({
          keyword,
          schemaProp: i2,
          compositeRule: true
        }, schValid);
        gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`);
        const merged = cxt.mergeValidEvaluated(schCxt, schValid);
        if (!merged)
          gen.if((0, codegen_1.not)(valid));
      }));
      cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
    }
    exports2.validateUnion = validateUnion;
  }
});

// node_modules/ajv/dist/compile/validate/keyword.js
var require_keyword = __commonJS({
  "node_modules/ajv/dist/compile/validate/keyword.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateKeywordUsage = exports2.validSchemaType = exports2.funcKeywordCode = exports2.macroKeywordCode = void 0;
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var code_1 = require_code2();
    var errors_1 = require_errors3();
    function macroKeywordCode(cxt, def) {
      const { gen, keyword, schema, parentSchema, it } = cxt;
      const macroSchema = def.macro.call(it.self, schema, parentSchema, it);
      const schemaRef = useKeyword(gen, keyword, macroSchema);
      if (it.opts.validateSchema !== false)
        it.self.validateSchema(macroSchema, true);
      const valid = gen.name("valid");
      cxt.subschema({
        schema: macroSchema,
        schemaPath: codegen_1.nil,
        errSchemaPath: `${it.errSchemaPath}/${keyword}`,
        topSchemaRef: schemaRef,
        compositeRule: true
      }, valid);
      cxt.pass(valid, () => cxt.error(true));
    }
    exports2.macroKeywordCode = macroKeywordCode;
    function funcKeywordCode(cxt, def) {
      var _a3;
      const { gen, keyword, schema, parentSchema, $data, it } = cxt;
      checkAsyncKeyword(it, def);
      const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
      const validateRef = useKeyword(gen, keyword, validate);
      const valid = gen.let("valid");
      cxt.block$data(valid, validateKeyword);
      cxt.ok((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid);
      function validateKeyword() {
        if (def.errors === false) {
          assignValid();
          if (def.modifying)
            modifyData(cxt);
          reportErrs(() => cxt.error());
        } else {
          const ruleErrs = def.async ? validateAsync() : validateSync();
          if (def.modifying)
            modifyData(cxt);
          reportErrs(() => addErrs(cxt, ruleErrs));
        }
      }
      function validateAsync() {
        const ruleErrs = gen.let("ruleErrs", null);
        gen.try(() => assignValid((0, codegen_1._)`await `), (e2) => gen.assign(valid, false).if((0, codegen_1._)`${e2} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e2}.errors`), () => gen.throw(e2)));
        return ruleErrs;
      }
      function validateSync() {
        const validateErrs = (0, codegen_1._)`${validateRef}.errors`;
        gen.assign(validateErrs, null);
        assignValid(codegen_1.nil);
        return validateErrs;
      }
      function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) {
        const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
        const passSchema = !("compile" in def && !$data || def.schema === false);
        gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
      }
      function reportErrs(errors) {
        var _a4;
        gen.if((0, codegen_1.not)((_a4 = def.valid) !== null && _a4 !== void 0 ? _a4 : valid), errors);
      }
    }
    exports2.funcKeywordCode = funcKeywordCode;
    function modifyData(cxt) {
      const { gen, data, it } = cxt;
      gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`));
    }
    function addErrs(cxt, errs) {
      const { gen } = cxt;
      gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => {
        gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
        (0, errors_1.extendErrors)(cxt);
      }, () => cxt.error());
    }
    function checkAsyncKeyword({ schemaEnv }, def) {
      if (def.async && !schemaEnv.$async)
        throw new Error("async keyword in sync schema");
    }
    function useKeyword(gen, keyword, result) {
      if (result === void 0)
        throw new Error(`keyword "${keyword}" failed to compile`);
      return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
    }
    function validSchemaType(schema, schemaType, allowUndefined = false) {
      return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined");
    }
    exports2.validSchemaType = validSchemaType;
    function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def, keyword) {
      if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
        throw new Error("ajv implementation error");
      }
      const deps = def.dependencies;
      if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
        throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);
      }
      if (def.validateSchema) {
        const valid = def.validateSchema(schema[keyword]);
        if (!valid) {
          const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def.validateSchema.errors);
          if (opts.validateSchema === "log")
            self2.logger.error(msg);
          else
            throw new Error(msg);
        }
      }
    }
    exports2.validateKeywordUsage = validateKeywordUsage;
  }
});

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

// node_modules/fast-deep-equal/index.js
var require_fast_deep_equal = __commonJS({
  "node_modules/fast-deep-equal/index.js"(exports2, module2) {
    "use strict";
    module2.exports = function equal(a, b) {
      if (a === b) return true;
      if (a && b && typeof a == "object" && typeof b == "object") {
        if (a.constructor !== b.constructor) return false;
        var length, i2, keys;
        if (Array.isArray(a)) {
          length = a.length;
          if (length != b.length) return false;
          for (i2 = length; i2-- !== 0; )
            if (!equal(a[i2], b[i2])) return false;
          return true;
        }
        if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
        if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
        if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
        keys = Object.keys(a);
        length = keys.length;
        if (length !== Object.keys(b).length) return false;
        for (i2 = length; i2-- !== 0; )
          if (!Object.prototype.hasOwnProperty.call(b, keys[i2])) return false;
        for (i2 = length; i2-- !== 0; ) {
          var key = keys[i2];
          if (!equal(a[key], b[key])) return false;
        }
        return true;
      }
      return a !== a && b !== b;
    };
  }
});

// node_modules/json-schema-traverse/index.js
var require_json_schema_traverse = __commonJS({
  "node_modules/json-schema-traverse/index.js"(exports2, module2) {
    "use strict";
    var traverse = module2.exports = function(schema, opts, cb) {
      if (typeof opts == "function") {
        cb = opts;
        opts = {};
      }
      cb = opts.cb || cb;
      var pre = typeof cb == "function" ? cb : cb.pre || function() {
      };
      var post = cb.post || function() {
      };
      _traverse(opts, pre, post, schema, "", schema);
    };
    traverse.keywords = {
      additionalItems: true,
      items: true,
      contains: true,
      additionalProperties: true,
      propertyNames: true,
      not: true,
      if: true,
      then: true,
      else: true
    };
    traverse.arrayKeywords = {
      items: true,
      allOf: true,
      anyOf: true,
      oneOf: true
    };
    traverse.propsKeywords = {
      $defs: true,
      definitions: true,
      properties: true,
      patternProperties: true,
      dependencies: true
    };
    traverse.skipKeywords = {
      default: true,
      enum: true,
      const: true,
      required: true,
      maximum: true,
      minimum: true,
      exclusiveMaximum: true,
      exclusiveMinimum: true,
      multipleOf: true,
      maxLength: true,
      minLength: true,
      pattern: true,
      format: true,
      maxItems: true,
      minItems: true,
      uniqueItems: true,
      maxProperties: true,
      minProperties: true
    };
    function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
      if (schema && typeof schema == "object" && !Array.isArray(schema)) {
        pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
        for (var key in schema) {
          var sch = schema[key];
          if (Array.isArray(sch)) {
            if (key in traverse.arrayKeywords) {
              for (var i2 = 0; i2 < sch.length; i2++)
                _traverse(opts, pre, post, sch[i2], jsonPtr + "/" + key + "/" + i2, rootSchema, jsonPtr, key, schema, i2);
            }
          } else if (key in traverse.propsKeywords) {
            if (sch && typeof sch == "object") {
              for (var prop in sch)
                _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
            }
          } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) {
            _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
          }
        }
        post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
      }
    }
    function escapeJsonPtr(str) {
      return str.replace(/~/g, "~0").replace(/\//g, "~1");
    }
  }
});

// node_modules/ajv/dist/compile/resolve.js
var require_resolve = __commonJS({
  "node_modules/ajv/dist/compile/resolve.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getSchemaRefs = exports2.resolveUrl = exports2.normalizeId = exports2._getFullPath = exports2.getFullPath = exports2.inlineRef = void 0;
    var util_1 = require_util5();
    var equal = require_fast_deep_equal();
    var traverse = require_json_schema_traverse();
    var SIMPLE_INLINED = /* @__PURE__ */ new Set([
      "type",
      "format",
      "pattern",
      "maxLength",
      "minLength",
      "maxProperties",
      "minProperties",
      "maxItems",
      "minItems",
      "maximum",
      "minimum",
      "uniqueItems",
      "multipleOf",
      "required",
      "enum",
      "const"
    ]);
    function inlineRef(schema, limit = true) {
      if (typeof schema == "boolean")
        return true;
      if (limit === true)
        return !hasRef(schema);
      if (!limit)
        return false;
      return countKeys(schema) <= limit;
    }
    exports2.inlineRef = inlineRef;
    var REF_KEYWORDS = /* @__PURE__ */ new Set([
      "$ref",
      "$recursiveRef",
      "$recursiveAnchor",
      "$dynamicRef",
      "$dynamicAnchor"
    ]);
    function hasRef(schema) {
      for (const key in schema) {
        if (REF_KEYWORDS.has(key))
          return true;
        const sch = schema[key];
        if (Array.isArray(sch) && sch.some(hasRef))
          return true;
        if (typeof sch == "object" && hasRef(sch))
          return true;
      }
      return false;
    }
    function countKeys(schema) {
      let count = 0;
      for (const key in schema) {
        if (key === "$ref")
          return Infinity;
        count++;
        if (SIMPLE_INLINED.has(key))
          continue;
        if (typeof schema[key] == "object") {
          (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch));
        }
        if (count === Infinity)
          return Infinity;
      }
      return count;
    }
    function getFullPath(resolver, id = "", normalize) {
      if (normalize !== false)
        id = normalizeId(id);
      const p = resolver.parse(id);
      return _getFullPath(resolver, p);
    }
    exports2.getFullPath = getFullPath;
    function _getFullPath(resolver, p) {
      const serialized = resolver.serialize(p);
      return serialized.split("#")[0] + "#";
    }
    exports2._getFullPath = _getFullPath;
    var TRAILING_SLASH_HASH = /#\/?$/;
    function normalizeId(id) {
      return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
    }
    exports2.normalizeId = normalizeId;
    function resolveUrl(resolver, baseId, id) {
      id = normalizeId(id);
      return resolver.resolve(baseId, id);
    }
    exports2.resolveUrl = resolveUrl;
    var ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
    function getSchemaRefs(schema, baseId) {
      if (typeof schema == "boolean")
        return {};
      const { schemaId, uriResolver } = this.opts;
      const schId = normalizeId(schema[schemaId] || baseId);
      const baseIds = { "": schId };
      const pathPrefix = getFullPath(uriResolver, schId, false);
      const localRefs = {};
      const schemaRefs = /* @__PURE__ */ new Set();
      traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {
        if (parentJsonPtr === void 0)
          return;
        const fullPath = pathPrefix + jsonPtr;
        let innerBaseId = baseIds[parentJsonPtr];
        if (typeof sch[schemaId] == "string")
          innerBaseId = addRef.call(this, sch[schemaId]);
        addAnchor.call(this, sch.$anchor);
        addAnchor.call(this, sch.$dynamicAnchor);
        baseIds[jsonPtr] = innerBaseId;
        function addRef(ref) {
          const _resolve = this.opts.uriResolver.resolve;
          ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);
          if (schemaRefs.has(ref))
            throw ambiguos(ref);
          schemaRefs.add(ref);
          let schOrRef = this.refs[ref];
          if (typeof schOrRef == "string")
            schOrRef = this.refs[schOrRef];
          if (typeof schOrRef == "object") {
            checkAmbiguosRef(sch, schOrRef.schema, ref);
          } else if (ref !== normalizeId(fullPath)) {
            if (ref[0] === "#") {
              checkAmbiguosRef(sch, localRefs[ref], ref);
              localRefs[ref] = sch;
            } else {
              this.refs[ref] = fullPath;
            }
          }
          return ref;
        }
        function addAnchor(anchor) {
          if (typeof anchor == "string") {
            if (!ANCHOR.test(anchor))
              throw new Error(`invalid anchor "${anchor}"`);
            addRef.call(this, `#${anchor}`);
          }
        }
      });
      return localRefs;
      function checkAmbiguosRef(sch1, sch2, ref) {
        if (sch2 !== void 0 && !equal(sch1, sch2))
          throw ambiguos(ref);
      }
      function ambiguos(ref) {
        return new Error(`reference "${ref}" resolves to more than one schema`);
      }
    }
    exports2.getSchemaRefs = getSchemaRefs;
  }
});

// node_modules/ajv/dist/compile/validate/index.js
var require_validate = __commonJS({
  "node_modules/ajv/dist/compile/validate/index.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getData = exports2.KeywordCxt = exports2.validateFunctionCode = void 0;
    var boolSchema_1 = require_boolSchema();
    var dataType_1 = require_dataType();
    var applicability_1 = require_applicability();
    var dataType_2 = require_dataType();
    var defaults_1 = require_defaults();
    var keyword_1 = require_keyword();
    var subschema_1 = require_subschema();
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var resolve_1 = require_resolve();
    var util_1 = require_util5();
    var errors_1 = require_errors3();
    function validateFunctionCode(it) {
      if (isSchemaObj(it)) {
        checkKeywords(it);
        if (schemaCxtHasRules(it)) {
          topSchemaObjCode(it);
          return;
        }
      }
      validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
    }
    exports2.validateFunctionCode = validateFunctionCode;
    function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
      if (opts.code.es5) {
        gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
          gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`);
          destructureValCxtES5(gen, opts);
          gen.code(body);
        });
      } else {
        gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
      }
    }
    function destructureValCxt(opts) {
      return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
    }
    function destructureValCxtES5(gen, opts) {
      gen.if(names_1.default.valCxt, () => {
        gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`);
        gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`);
        gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
        gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`);
        if (opts.dynamicRef)
          gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
      }, () => {
        gen.var(names_1.default.instancePath, (0, codegen_1._)`""`);
        gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`);
        gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`);
        gen.var(names_1.default.rootData, names_1.default.data);
        if (opts.dynamicRef)
          gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`);
      });
    }
    function topSchemaObjCode(it) {
      const { schema, opts, gen } = it;
      validateFunction(it, () => {
        if (opts.$comment && schema.$comment)
          commentKeyword(it);
        checkNoDefault(it);
        gen.let(names_1.default.vErrors, null);
        gen.let(names_1.default.errors, 0);
        if (opts.unevaluated)
          resetEvaluated(it);
        typeAndKeywords(it);
        returnResults(it);
      });
      return;
    }
    function resetEvaluated(it) {
      const { gen, validateName } = it;
      it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`);
      gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`));
      gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`));
    }
    function funcSourceUrl(schema, opts) {
      const schId = typeof schema == "object" && schema[opts.schemaId];
      return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil;
    }
    function subschemaCode(it, valid) {
      if (isSchemaObj(it)) {
        checkKeywords(it);
        if (schemaCxtHasRules(it)) {
          subSchemaObjCode(it, valid);
          return;
        }
      }
      (0, boolSchema_1.boolOrEmptySchema)(it, valid);
    }
    function schemaCxtHasRules({ schema, self: self2 }) {
      if (typeof schema == "boolean")
        return !schema;
      for (const key in schema)
        if (self2.RULES.all[key])
          return true;
      return false;
    }
    function isSchemaObj(it) {
      return typeof it.schema != "boolean";
    }
    function subSchemaObjCode(it, valid) {
      const { schema, gen, opts } = it;
      if (opts.$comment && schema.$comment)
        commentKeyword(it);
      updateContext(it);
      checkAsyncSchema(it);
      const errsCount = gen.const("_errs", names_1.default.errors);
      typeAndKeywords(it, errsCount);
      gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
    }
    function checkKeywords(it) {
      (0, util_1.checkUnknownRules)(it);
      checkRefsAndKeywords(it);
    }
    function typeAndKeywords(it, errsCount) {
      if (it.opts.jtd)
        return schemaKeywords(it, [], false, errsCount);
      const types3 = (0, dataType_1.getSchemaTypes)(it.schema);
      const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types3);
      schemaKeywords(it, types3, !checkedTypes, errsCount);
    }
    function checkRefsAndKeywords(it) {
      const { schema, errSchemaPath, opts, self: self2 } = it;
      if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) {
        self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
      }
    }
    function checkNoDefault(it) {
      const { schema, opts } = it;
      if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {
        (0, util_1.checkStrictMode)(it, "default is ignored in the schema root");
      }
    }
    function updateContext(it) {
      const schId = it.schema[it.opts.schemaId];
      if (schId)
        it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
    }
    function checkAsyncSchema(it) {
      if (it.schema.$async && !it.schemaEnv.$async)
        throw new Error("async schema in sync schema");
    }
    function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
      const msg = schema.$comment;
      if (opts.$comment === true) {
        gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`);
      } else if (typeof opts.$comment == "function") {
        const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`;
        const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
        gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
      }
    }
    function returnResults(it) {
      const { gen, schemaEnv, validateName, ValidationError, opts } = it;
      if (schemaEnv.$async) {
        gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`));
      } else {
        gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors);
        if (opts.unevaluated)
          assignEvaluated(it);
        gen.return((0, codegen_1._)`${names_1.default.errors} === 0`);
      }
    }
    function assignEvaluated({ gen, evaluated, props, items }) {
      if (props instanceof codegen_1.Name)
        gen.assign((0, codegen_1._)`${evaluated}.props`, props);
      if (items instanceof codegen_1.Name)
        gen.assign((0, codegen_1._)`${evaluated}.items`, items);
    }
    function schemaKeywords(it, types3, typeErrors, errsCount) {
      const { gen, schema, data, allErrors, opts, self: self2 } = it;
      const { RULES } = self2;
      if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
        gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition));
        return;
      }
      if (!opts.jtd)
        checkStrictTypes(it, types3);
      gen.block(() => {
        for (const group of RULES.rules)
          groupKeywords(group);
        groupKeywords(RULES.post);
      });
      function groupKeywords(group) {
        if (!(0, applicability_1.shouldUseGroup)(schema, group))
          return;
        if (group.type) {
          gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
          iterateKeywords(it, group);
          if (types3.length === 1 && types3[0] === group.type && typeErrors) {
            gen.else();
            (0, dataType_2.reportTypeError)(it);
          }
          gen.endIf();
        } else {
          iterateKeywords(it, group);
        }
        if (!allErrors)
          gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);
      }
    }
    function iterateKeywords(it, group) {
      const { gen, schema, opts: { useDefaults } } = it;
      if (useDefaults)
        (0, defaults_1.assignDefaults)(it, group.type);
      gen.block(() => {
        for (const rule of group.rules) {
          if ((0, applicability_1.shouldUseRule)(schema, rule)) {
            keywordCode(it, rule.keyword, rule.definition, group.type);
          }
        }
      });
    }
    function checkStrictTypes(it, types3) {
      if (it.schemaEnv.meta || !it.opts.strictTypes)
        return;
      checkContextTypes(it, types3);
      if (!it.opts.allowUnionTypes)
        checkMultipleTypes(it, types3);
      checkKeywordTypes(it, it.dataTypes);
    }
    function checkContextTypes(it, types3) {
      if (!types3.length)
        return;
      if (!it.dataTypes.length) {
        it.dataTypes = types3;
        return;
      }
      types3.forEach((t2) => {
        if (!includesType(it.dataTypes, t2)) {
          strictTypesError(it, `type "${t2}" not allowed by context "${it.dataTypes.join(",")}"`);
        }
      });
      narrowSchemaTypes(it, types3);
    }
    function checkMultipleTypes(it, ts) {
      if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
        strictTypesError(it, "use allowUnionTypes to allow union type keyword");
      }
    }
    function checkKeywordTypes(it, ts) {
      const rules = it.self.RULES.all;
      for (const keyword in rules) {
        const rule = rules[keyword];
        if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
          const { type } = rule.definition;
          if (type.length && !type.some((t2) => hasApplicableType(ts, t2))) {
            strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
          }
        }
      }
    }
    function hasApplicableType(schTs, kwdT) {
      return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer");
    }
    function includesType(ts, t2) {
      return ts.includes(t2) || t2 === "integer" && ts.includes("number");
    }
    function narrowSchemaTypes(it, withTypes) {
      const ts = [];
      for (const t2 of it.dataTypes) {
        if (includesType(withTypes, t2))
          ts.push(t2);
        else if (withTypes.includes("integer") && t2 === "number")
          ts.push("integer");
      }
      it.dataTypes = ts;
    }
    function strictTypesError(it, msg) {
      const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
      msg += ` at "${schemaPath}" (strictTypes)`;
      (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);
    }
    var KeywordCxt = class {
      constructor(it, def, keyword) {
        (0, keyword_1.validateKeywordUsage)(it, def, keyword);
        this.gen = it.gen;
        this.allErrors = it.allErrors;
        this.keyword = keyword;
        this.data = it.data;
        this.schema = it.schema[keyword];
        this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;
        this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);
        this.schemaType = def.schemaType;
        this.parentSchema = it.schema;
        this.params = {};
        this.it = it;
        this.def = def;
        if (this.$data) {
          this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
        } else {
          this.schemaCode = this.schemaValue;
          if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {
            throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);
          }
        }
        if ("code" in def ? def.trackErrors : def.errors !== false) {
          this.errsCount = it.gen.const("_errs", names_1.default.errors);
        }
      }
      result(condition, successAction, failAction) {
        this.failResult((0, codegen_1.not)(condition), successAction, failAction);
      }
      failResult(condition, successAction, failAction) {
        this.gen.if(condition);
        if (failAction)
          failAction();
        else
          this.error();
        if (successAction) {
          this.gen.else();
          successAction();
          if (this.allErrors)
            this.gen.endIf();
        } else {
          if (this.allErrors)
            this.gen.endIf();
          else
            this.gen.else();
        }
      }
      pass(condition, failAction) {
        this.failResult((0, codegen_1.not)(condition), void 0, failAction);
      }
      fail(condition) {
        if (condition === void 0) {
          this.error();
          if (!this.allErrors)
            this.gen.if(false);
          return;
        }
        this.gen.if(condition);
        this.error();
        if (this.allErrors)
          this.gen.endIf();
        else
          this.gen.else();
      }
      fail$data(condition) {
        if (!this.$data)
          return this.fail(condition);
        const { schemaCode } = this;
        this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
      }
      error(append, errorParams, errorPaths) {
        if (errorParams) {
          this.setParams(errorParams);
          this._error(append, errorPaths);
          this.setParams({});
          return;
        }
        this._error(append, errorPaths);
      }
      _error(append, errorPaths) {
        ;
        (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
      }
      $dataError() {
        (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
      }
      reset() {
        if (this.errsCount === void 0)
          throw new Error('add "trackErrors" to keyword definition');
        (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
      }
      ok(cond) {
        if (!this.allErrors)
          this.gen.if(cond);
      }
      setParams(obj, assign) {
        if (assign)
          Object.assign(this.params, obj);
        else
          this.params = obj;
      }
      block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
        this.gen.block(() => {
          this.check$data(valid, $dataValid);
          codeBlock();
        });
      }
      check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
        if (!this.$data)
          return;
        const { gen, schemaCode, schemaType, def } = this;
        gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid));
        if (valid !== codegen_1.nil)
          gen.assign(valid, true);
        if (schemaType.length || def.validateSchema) {
          gen.elseIf(this.invalid$data());
          this.$dataError();
          if (valid !== codegen_1.nil)
            gen.assign(valid, false);
        }
        gen.else();
      }
      invalid$data() {
        const { gen, schemaCode, schemaType, def, it } = this;
        return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
        function wrong$DataType() {
          if (schemaType.length) {
            if (!(schemaCode instanceof codegen_1.Name))
              throw new Error("ajv implementation error");
            const st = Array.isArray(schemaType) ? schemaType : [schemaType];
            return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
          }
          return codegen_1.nil;
        }
        function invalid$DataSchema() {
          if (def.validateSchema) {
            const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema });
            return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`;
          }
          return codegen_1.nil;
        }
      }
      subschema(appl, valid) {
        const subschema = (0, subschema_1.getSubschema)(this.it, appl);
        (0, subschema_1.extendSubschemaData)(subschema, this.it, appl);
        (0, subschema_1.extendSubschemaMode)(subschema, appl);
        const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 };
        subschemaCode(nextContext, valid);
        return nextContext;
      }
      mergeEvaluated(schemaCxt, toName) {
        const { it, gen } = this;
        if (!it.opts.unevaluated)
          return;
        if (it.props !== true && schemaCxt.props !== void 0) {
          it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
        }
        if (it.items !== true && schemaCxt.items !== void 0) {
          it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
        }
      }
      mergeValidEvaluated(schemaCxt, valid) {
        const { it, gen } = this;
        if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
          gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
          return true;
        }
      }
    };
    exports2.KeywordCxt = KeywordCxt;
    function keywordCode(it, keyword, def, ruleType) {
      const cxt = new KeywordCxt(it, def, keyword);
      if ("code" in def) {
        def.code(cxt, ruleType);
      } else if (cxt.$data && def.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def);
      } else if ("macro" in def) {
        (0, keyword_1.macroKeywordCode)(cxt, def);
      } else if (def.compile || def.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def);
      }
    }
    var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
    var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
    function getData($data, { dataLevel, dataNames, dataPathArr }) {
      let jsonPointer;
      let data;
      if ($data === "")
        return names_1.default.rootData;
      if ($data[0] === "/") {
        if (!JSON_POINTER.test($data))
          throw new Error(`Invalid JSON-pointer: ${$data}`);
        jsonPointer = $data;
        data = names_1.default.rootData;
      } else {
        const matches = RELATIVE_JSON_POINTER.exec($data);
        if (!matches)
          throw new Error(`Invalid JSON-pointer: ${$data}`);
        const up = +matches[1];
        jsonPointer = matches[2];
        if (jsonPointer === "#") {
          if (up >= dataLevel)
            throw new Error(errorMsg("property/index", up));
          return dataPathArr[dataLevel - up];
        }
        if (up > dataLevel)
          throw new Error(errorMsg("data", up));
        data = dataNames[dataLevel - up];
        if (!jsonPointer)
          return data;
      }
      let expr = data;
      const segments = jsonPointer.split("/");
      for (const segment of segments) {
        if (segment) {
          data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
          expr = (0, codegen_1._)`${expr} && ${data}`;
        }
      }
      return expr;
      function errorMsg(pointerType, up) {
        return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
      }
    }
    exports2.getData = getData;
  }
});

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

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

// node_modules/ajv/dist/compile/index.js
var require_compile = __commonJS({
  "node_modules/ajv/dist/compile/index.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.resolveSchema = exports2.getCompilingSchema = exports2.resolveRef = exports2.compileSchema = exports2.SchemaEnv = void 0;
    var codegen_1 = require_codegen();
    var validation_error_1 = require_validation_error();
    var names_1 = require_names();
    var resolve_1 = require_resolve();
    var util_1 = require_util5();
    var validate_1 = require_validate();
    var SchemaEnv = class {
      constructor(env) {
        var _a3;
        this.refs = {};
        this.dynamicAnchors = {};
        let schema;
        if (typeof env.schema == "object")
          schema = env.schema;
        this.schema = env.schema;
        this.schemaId = env.schemaId;
        this.root = env.root || this;
        this.baseId = (_a3 = env.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
        this.schemaPath = env.schemaPath;
        this.localRefs = env.localRefs;
        this.meta = env.meta;
        this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
        this.refs = {};
      }
    };
    exports2.SchemaEnv = SchemaEnv;
    function compileSchema(sch) {
      const _sch = getCompilingSchema.call(this, sch);
      if (_sch)
        return _sch;
      const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId);
      const { es5, lines } = this.opts.code;
      const { ownProperties } = this.opts;
      const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
      let _ValidationError;
      if (sch.$async) {
        _ValidationError = gen.scopeValue("Error", {
          ref: validation_error_1.default,
          code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default`
        });
      }
      const validateName = gen.scopeName("validate");
      sch.validateName = validateName;
      const schemaCxt = {
        gen,
        allErrors: this.opts.allErrors,
        data: names_1.default.data,
        parentData: names_1.default.parentData,
        parentDataProperty: names_1.default.parentDataProperty,
        dataNames: [names_1.default.data],
        dataPathArr: [codegen_1.nil],
        // TODO can its length be used as dataLevel if nil is removed?
        dataLevel: 0,
        dataTypes: [],
        definedProperties: /* @__PURE__ */ new Set(),
        topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }),
        validateName,
        ValidationError: _ValidationError,
        schema: sch.schema,
        schemaEnv: sch,
        rootId,
        baseId: sch.baseId || rootId,
        schemaPath: codegen_1.nil,
        errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
        errorPath: (0, codegen_1._)`""`,
        opts: this.opts,
        self: this
      };
      let sourceCode;
      try {
        this._compilations.add(sch);
        (0, validate_1.validateFunctionCode)(schemaCxt);
        gen.optimize(this.opts.code.optimize);
        const validateCode = gen.toString();
        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
        if (this.opts.code.process)
          sourceCode = this.opts.code.process(sourceCode, sch);
        const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
        const validate = makeValidate(this, this.scope.get());
        this.scope.value(validateName, { ref: validate });
        validate.errors = null;
        validate.schema = sch.schema;
        validate.schemaEnv = sch;
        if (sch.$async)
          validate.$async = true;
        if (this.opts.code.source === true) {
          validate.source = { validateName, validateCode, scopeValues: gen._values };
        }
        if (this.opts.unevaluated) {
          const { props, items } = schemaCxt;
          validate.evaluated = {
            props: props instanceof codegen_1.Name ? void 0 : props,
            items: items instanceof codegen_1.Name ? void 0 : items,
            dynamicProps: props instanceof codegen_1.Name,
            dynamicItems: items instanceof codegen_1.Name
          };
          if (validate.source)
            validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);
        }
        sch.validate = validate;
        return sch;
      } catch (e2) {
        delete sch.validate;
        delete sch.validateName;
        if (sourceCode)
          this.logger.error("Error compiling schema, function code:", sourceCode);
        throw e2;
      } finally {
        this._compilations.delete(sch);
      }
    }
    exports2.compileSchema = compileSchema;
    function resolveRef2(root, baseId, ref) {
      var _a3;
      ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
      const schOrFunc = root.refs[ref];
      if (schOrFunc)
        return schOrFunc;
      let _sch = resolve2.call(this, root, ref);
      if (_sch === void 0) {
        const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref];
        const { schemaId } = this.opts;
        if (schema)
          _sch = new SchemaEnv({ schema, schemaId, root, baseId });
      }
      if (_sch === void 0)
        return;
      return root.refs[ref] = inlineOrCompile.call(this, _sch);
    }
    exports2.resolveRef = resolveRef2;
    function inlineOrCompile(sch) {
      if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
        return sch.schema;
      return sch.validate ? sch : compileSchema.call(this, sch);
    }
    function getCompilingSchema(schEnv) {
      for (const sch of this._compilations) {
        if (sameSchemaEnv(sch, schEnv))
          return sch;
      }
    }
    exports2.getCompilingSchema = getCompilingSchema;
    function sameSchemaEnv(s1, s2) {
      return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
    }
    function resolve2(root, ref) {
      let sch;
      while (typeof (sch = this.refs[ref]) == "string")
        ref = sch;
      return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
    }
    function resolveSchema(root, ref) {
      const p = this.opts.uriResolver.parse(ref);
      const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
      let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0);
      if (Object.keys(root.schema).length > 0 && refPath === baseId) {
        return getJsonPointer.call(this, p, root);
      }
      const id = (0, resolve_1.normalizeId)(refPath);
      const schOrRef = this.refs[id] || this.schemas[id];
      if (typeof schOrRef == "string") {
        const sch = resolveSchema.call(this, root, schOrRef);
        if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
          return;
        return getJsonPointer.call(this, p, sch);
      }
      if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
        return;
      if (!schOrRef.validate)
        compileSchema.call(this, schOrRef);
      if (id === (0, resolve_1.normalizeId)(ref)) {
        const { schema } = schOrRef;
        const { schemaId } = this.opts;
        const schId = schema[schemaId];
        if (schId)
          baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
        return new SchemaEnv({ schema, schemaId, root, baseId });
      }
      return getJsonPointer.call(this, p, schOrRef);
    }
    exports2.resolveSchema = resolveSchema;
    var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([
      "properties",
      "patternProperties",
      "enum",
      "dependencies",
      "definitions"
    ]);
    function getJsonPointer(parsedRef, { baseId, schema, root }) {
      var _a3;
      if (((_a3 = parsedRef.fragment) === null || _a3 === void 0 ? void 0 : _a3[0]) !== "/")
        return;
      for (const part of parsedRef.fragment.slice(1).split("/")) {
        if (typeof schema === "boolean")
          return;
        const partSchema = schema[(0, util_1.unescapeFragment)(part)];
        if (partSchema === void 0)
          return;
        schema = partSchema;
        const schId = typeof schema === "object" && schema[this.opts.schemaId];
        if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
          baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
        }
      }
      let env;
      if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
        const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
        env = resolveSchema.call(this, root, $ref);
      }
      const { schemaId } = this.opts;
      env = env || new SchemaEnv({ schema, schemaId, root, baseId });
      if (env.schema !== env.root.schema)
        return env;
      return void 0;
    }
  }
});

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

// node_modules/fast-uri/lib/utils.js
var require_utils4 = __commonJS({
  "node_modules/fast-uri/lib/utils.js"(exports2, module2) {
    "use strict";
    var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);
    var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);
    var isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu);
    var isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu);
    var isPathCharacter = RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);
    function stringArrayToHexStripped(input) {
      let acc = "";
      let code = 0;
      let i2 = 0;
      for (i2 = 0; i2 < input.length; i2++) {
        code = input[i2].charCodeAt(0);
        if (code === 48) {
          continue;
        }
        if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) {
          return "";
        }
        acc += input[i2];
        break;
      }
      for (i2 += 1; i2 < input.length; i2++) {
        code = input[i2].charCodeAt(0);
        if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) {
          return "";
        }
        acc += input[i2];
      }
      return acc;
    }
    var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);
    function consumeIsZone(buffer) {
      buffer.length = 0;
      return true;
    }
    function consumeHextets(buffer, address, output) {
      if (buffer.length) {
        const hex3 = stringArrayToHexStripped(buffer);
        if (hex3 !== "") {
          address.push(hex3);
        } else {
          output.error = true;
          return false;
        }
        buffer.length = 0;
      }
      return true;
    }
    function getIPV6(input) {
      let tokenCount = 0;
      const output = { error: false, address: "", zone: "" };
      const address = [];
      const buffer = [];
      let endipv6Encountered = false;
      let endIpv6 = false;
      let consume = consumeHextets;
      for (let i2 = 0; i2 < input.length; i2++) {
        const cursor = input[i2];
        if (cursor === "[" || cursor === "]") {
          continue;
        }
        if (cursor === ":") {
          if (endipv6Encountered === true) {
            endIpv6 = true;
          }
          if (!consume(buffer, address, output)) {
            break;
          }
          if (++tokenCount > 7) {
            output.error = true;
            break;
          }
          if (i2 > 0 && input[i2 - 1] === ":") {
            endipv6Encountered = true;
          }
          address.push(":");
          continue;
        } else if (cursor === "%") {
          if (!consume(buffer, address, output)) {
            break;
          }
          consume = consumeIsZone;
        } else {
          buffer.push(cursor);
          continue;
        }
      }
      if (buffer.length) {
        if (consume === consumeIsZone) {
          output.zone = buffer.join("");
        } else if (endIpv6) {
          address.push(buffer.join(""));
        } else {
          address.push(stringArrayToHexStripped(buffer));
        }
      }
      output.address = address.join("");
      return output;
    }
    function normalizeIPv6(host) {
      if (findToken(host, ":") < 2) {
        return { host, isIPV6: false };
      }
      const ipv63 = getIPV6(host);
      if (!ipv63.error) {
        let newHost = ipv63.address;
        let escapedHost = ipv63.address;
        if (ipv63.zone) {
          newHost += "%" + ipv63.zone;
          escapedHost += "%25" + ipv63.zone;
        }
        return { host: newHost, isIPV6: true, escapedHost };
      } else {
        return { host, isIPV6: false };
      }
    }
    function findToken(str, token) {
      let ind = 0;
      for (let i2 = 0; i2 < str.length; i2++) {
        if (str[i2] === token) ind++;
      }
      return ind;
    }
    function removeDotSegments(path) {
      let input = path;
      const output = [];
      let nextSlash = -1;
      let len = 0;
      while (len = input.length) {
        if (len === 1) {
          if (input === ".") {
            break;
          } else if (input === "/") {
            output.push("/");
            break;
          } else {
            output.push(input);
            break;
          }
        } else if (len === 2) {
          if (input[0] === ".") {
            if (input[1] === ".") {
              break;
            } else if (input[1] === "/") {
              input = input.slice(2);
              continue;
            }
          } else if (input[0] === "/") {
            if (input[1] === "." || input[1] === "/") {
              output.push("/");
              break;
            }
          }
        } else if (len === 3) {
          if (input === "/..") {
            if (output.length !== 0) {
              output.pop();
            }
            output.push("/");
            break;
          }
        }
        if (input[0] === ".") {
          if (input[1] === ".") {
            if (input[2] === "/") {
              input = input.slice(3);
              continue;
            }
          } else if (input[1] === "/") {
            input = input.slice(2);
            continue;
          }
        } else if (input[0] === "/") {
          if (input[1] === ".") {
            if (input[2] === "/") {
              input = input.slice(2);
              continue;
            } else if (input[2] === ".") {
              if (input[3] === "/") {
                input = input.slice(3);
                if (output.length !== 0) {
                  output.pop();
                }
                continue;
              }
            }
          }
        }
        if ((nextSlash = input.indexOf("/", 1)) === -1) {
          output.push(input);
          break;
        } else {
          output.push(input.slice(0, nextSlash));
          input = input.slice(nextSlash);
        }
      }
      return output.join("");
    }
    var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" };
    var HOST_DELIM_RE = /[@/?#:]/g;
    var HOST_DELIM_NO_COLON_RE = /[@/?#]/g;
    function reescapeHostDelimiters(host, isIP2) {
      const re = isIP2 ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE;
      re.lastIndex = 0;
      return host.replace(re, (ch) => HOST_DELIMS[ch]);
    }
    function normalizePercentEncoding(input, decodeUnreserved = false) {
      if (input.indexOf("%") === -1) {
        return input;
      }
      let output = "";
      for (let i2 = 0; i2 < input.length; i2++) {
        if (input[i2] === "%" && i2 + 2 < input.length) {
          const hex3 = input.slice(i2 + 1, i2 + 3);
          if (isHexPair(hex3)) {
            const normalizedHex = hex3.toUpperCase();
            const decoded = String.fromCharCode(parseInt(normalizedHex, 16));
            if (decodeUnreserved && isUnreserved(decoded)) {
              output += decoded;
            } else {
              output += "%" + normalizedHex;
            }
            i2 += 2;
            continue;
          }
        }
        output += input[i2];
      }
      return output;
    }
    function normalizePathEncoding(input) {
      let output = "";
      for (let i2 = 0; i2 < input.length; i2++) {
        if (input[i2] === "%" && i2 + 2 < input.length) {
          const hex3 = input.slice(i2 + 1, i2 + 3);
          if (isHexPair(hex3)) {
            const normalizedHex = hex3.toUpperCase();
            const decoded = String.fromCharCode(parseInt(normalizedHex, 16));
            if (decoded !== "." && isUnreserved(decoded)) {
              output += decoded;
            } else {
              output += "%" + normalizedHex;
            }
            i2 += 2;
            continue;
          }
        }
        if (isPathCharacter(input[i2])) {
          output += input[i2];
        } else {
          output += escape(input[i2]);
        }
      }
      return output;
    }
    function escapePreservingEscapes(input) {
      let output = "";
      for (let i2 = 0; i2 < input.length; i2++) {
        if (input[i2] === "%" && i2 + 2 < input.length) {
          const hex3 = input.slice(i2 + 1, i2 + 3);
          if (isHexPair(hex3)) {
            output += "%" + hex3.toUpperCase();
            i2 += 2;
            continue;
          }
        }
        output += escape(input[i2]);
      }
      return output;
    }
    function recomposeAuthority(component) {
      const uriTokens = [];
      if (component.userinfo !== void 0) {
        uriTokens.push(component.userinfo);
        uriTokens.push("@");
      }
      if (component.host !== void 0) {
        let host = unescape(component.host);
        if (!isIPv4(host)) {
          const ipV6res = normalizeIPv6(host);
          if (ipV6res.isIPV6 === true) {
            host = `[${ipV6res.escapedHost}]`;
          } else {
            host = reescapeHostDelimiters(host, false);
          }
        }
        uriTokens.push(host);
      }
      if (typeof component.port === "number" || typeof component.port === "string") {
        uriTokens.push(":");
        uriTokens.push(String(component.port));
      }
      return uriTokens.length ? uriTokens.join("") : void 0;
    }
    module2.exports = {
      nonSimpleDomain,
      recomposeAuthority,
      reescapeHostDelimiters,
      normalizePercentEncoding,
      normalizePathEncoding,
      escapePreservingEscapes,
      removeDotSegments,
      isIPv4,
      isUUID,
      normalizeIPv6,
      stringArrayToHexStripped
    };
  }
});

// node_modules/fast-uri/lib/schemes.js
var require_schemes = __commonJS({
  "node_modules/fast-uri/lib/schemes.js"(exports2, module2) {
    "use strict";
    var { isUUID } = require_utils4();
    var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;
    var supportedSchemeNames = (
      /** @type {const} */
      [
        "http",
        "https",
        "ws",
        "wss",
        "urn",
        "urn:uuid"
      ]
    );
    function isValidSchemeName(name) {
      return supportedSchemeNames.indexOf(
        /** @type {*} */
        name
      ) !== -1;
    }
    function wsIsSecure(wsComponent) {
      if (wsComponent.secure === true) {
        return true;
      } else if (wsComponent.secure === false) {
        return false;
      } else if (wsComponent.scheme) {
        return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S");
      } else {
        return false;
      }
    }
    function httpParse(component) {
      if (!component.host) {
        component.error = component.error || "HTTP URIs must have a host.";
      }
      return component;
    }
    function httpSerialize(component) {
      const secure = String(component.scheme).toLowerCase() === "https";
      if (component.port === (secure ? 443 : 80) || component.port === "") {
        component.port = void 0;
      }
      if (!component.path) {
        component.path = "/";
      }
      return component;
    }
    function wsParse(wsComponent) {
      wsComponent.secure = wsIsSecure(wsComponent);
      wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : "");
      wsComponent.path = void 0;
      wsComponent.query = void 0;
      return wsComponent;
    }
    function wsSerialize(wsComponent) {
      if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") {
        wsComponent.port = void 0;
      }
      if (typeof wsComponent.secure === "boolean") {
        wsComponent.scheme = wsComponent.secure ? "wss" : "ws";
        wsComponent.secure = void 0;
      }
      if (wsComponent.resourceName) {
        const [path, query] = wsComponent.resourceName.split("?");
        wsComponent.path = path && path !== "/" ? path : void 0;
        wsComponent.query = query;
        wsComponent.resourceName = void 0;
      }
      wsComponent.fragment = void 0;
      return wsComponent;
    }
    function urnParse(urnComponent, options) {
      if (!urnComponent.path) {
        urnComponent.error = "URN can not be parsed";
        return urnComponent;
      }
      const matches = urnComponent.path.match(URN_REG);
      if (matches) {
        const scheme = options.scheme || urnComponent.scheme || "urn";
        urnComponent.nid = matches[1].toLowerCase();
        urnComponent.nss = matches[2];
        const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`;
        const schemeHandler = getSchemeHandler(urnScheme);
        urnComponent.path = void 0;
        if (schemeHandler) {
          urnComponent = schemeHandler.parse(urnComponent, options);
        }
      } else {
        urnComponent.error = urnComponent.error || "URN can not be parsed.";
      }
      return urnComponent;
    }
    function urnSerialize(urnComponent, options) {
      if (urnComponent.nid === void 0) {
        throw new Error("URN without nid cannot be serialized");
      }
      const scheme = options.scheme || urnComponent.scheme || "urn";
      const nid = urnComponent.nid.toLowerCase();
      const urnScheme = `${scheme}:${options.nid || nid}`;
      const schemeHandler = getSchemeHandler(urnScheme);
      if (schemeHandler) {
        urnComponent = schemeHandler.serialize(urnComponent, options);
      }
      const uriComponent = urnComponent;
      const nss = urnComponent.nss;
      uriComponent.path = `${nid || options.nid}:${nss}`;
      options.skipEscape = true;
      return uriComponent;
    }
    function urnuuidParse(urnComponent, options) {
      const uuidComponent = urnComponent;
      uuidComponent.uuid = uuidComponent.nss;
      uuidComponent.nss = void 0;
      if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) {
        uuidComponent.error = uuidComponent.error || "UUID is not valid.";
      }
      return uuidComponent;
    }
    function urnuuidSerialize(uuidComponent) {
      const urnComponent = uuidComponent;
      urnComponent.nss = (uuidComponent.uuid || "").toLowerCase();
      return urnComponent;
    }
    var http3 = (
      /** @type {SchemeHandler} */
      {
        scheme: "http",
        domainHost: true,
        parse: httpParse,
        serialize: httpSerialize
      }
    );
    var https2 = (
      /** @type {SchemeHandler} */
      {
        scheme: "https",
        domainHost: http3.domainHost,
        parse: httpParse,
        serialize: httpSerialize
      }
    );
    var ws = (
      /** @type {SchemeHandler} */
      {
        scheme: "ws",
        domainHost: true,
        parse: wsParse,
        serialize: wsSerialize
      }
    );
    var wss = (
      /** @type {SchemeHandler} */
      {
        scheme: "wss",
        domainHost: ws.domainHost,
        parse: ws.parse,
        serialize: ws.serialize
      }
    );
    var urn = (
      /** @type {SchemeHandler} */
      {
        scheme: "urn",
        parse: urnParse,
        serialize: urnSerialize,
        skipNormalize: true
      }
    );
    var urnuuid = (
      /** @type {SchemeHandler} */
      {
        scheme: "urn:uuid",
        parse: urnuuidParse,
        serialize: urnuuidSerialize,
        skipNormalize: true
      }
    );
    var SCHEMES = (
      /** @type {Record<SchemeName, SchemeHandler>} */
      {
        http: http3,
        https: https2,
        ws,
        wss,
        urn,
        "urn:uuid": urnuuid
      }
    );
    Object.setPrototypeOf(SCHEMES, null);
    function getSchemeHandler(scheme) {
      return scheme && (SCHEMES[
        /** @type {SchemeName} */
        scheme
      ] || SCHEMES[
        /** @type {SchemeName} */
        scheme.toLowerCase()
      ]) || void 0;
    }
    module2.exports = {
      wsIsSecure,
      SCHEMES,
      isValidSchemeName,
      getSchemeHandler
    };
  }
});

// node_modules/fast-uri/index.js
var require_fast_uri = __commonJS({
  "node_modules/fast-uri/index.js"(exports2, module2) {
    "use strict";
    var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, escapePreservingEscapes, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils4();
    var { SCHEMES, getSchemeHandler } = require_schemes();
    function normalize(uri, options) {
      if (typeof uri === "string") {
        uri = /** @type {T} */
        normalizeString(uri, options);
      } else if (typeof uri === "object") {
        uri = /** @type {T} */
        parse3(serialize(uri, options), options);
      }
      return uri;
    }
    function resolve2(baseURI, relativeURI, options) {
      const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
      const { parsed: baseParsed, malformedAuthorityOrPort: baseMalformed } = parseWithStatus(baseURI, schemelessOptions);
      const { parsed: relativeParsed, malformedAuthorityOrPort: relativeMalformed } = parseWithStatus(relativeURI, schemelessOptions);
      if (baseMalformed || relativeMalformed) {
        throw new Error(baseParsed.error || relativeParsed.error || "URI is malformed.");
      }
      const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true);
      schemelessOptions.skipEscape = true;
      return serialize(resolved, schemelessOptions);
    }
    function resolveComponent(base, relative, options, skipNormalization) {
      const target = {};
      if (!skipNormalization) {
        base = parse3(serialize(base, options), options);
        relative = parse3(serialize(relative, options), options);
      }
      options = options || {};
      if (!options.tolerant && relative.scheme) {
        target.scheme = relative.scheme;
        target.userinfo = relative.userinfo;
        target.host = relative.host;
        target.port = relative.port;
        target.path = removeDotSegments(relative.path || "");
        target.query = relative.query;
      } else {
        if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) {
          target.userinfo = relative.userinfo;
          target.host = relative.host;
          target.port = relative.port;
          target.path = removeDotSegments(relative.path || "");
          target.query = relative.query;
        } else {
          if (!relative.path) {
            target.path = base.path;
            if (relative.query !== void 0) {
              target.query = relative.query;
            } else {
              target.query = base.query;
            }
          } else {
            if (relative.path[0] === "/") {
              target.path = removeDotSegments(relative.path);
            } else {
              if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) {
                target.path = "/" + relative.path;
              } else if (!base.path) {
                target.path = relative.path;
              } else {
                target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
              }
              target.path = removeDotSegments(target.path);
            }
            target.query = relative.query;
          }
          target.userinfo = base.userinfo;
          target.host = base.host;
          target.port = base.port;
        }
        target.scheme = base.scheme;
      }
      target.fragment = relative.fragment;
      return target;
    }
    function equal(uriA, uriB, options) {
      const normalizedA = normalizeComparableURI(uriA, options);
      const normalizedB = normalizeComparableURI(uriB, options);
      return normalizedA !== void 0 && normalizedB !== void 0 && normalizedA.toLowerCase() === normalizedB.toLowerCase();
    }
    function serialize(cmpts, opts) {
      const component = {
        host: cmpts.host,
        scheme: cmpts.scheme,
        userinfo: cmpts.userinfo,
        port: cmpts.port,
        path: cmpts.path,
        query: cmpts.query,
        nid: cmpts.nid,
        nss: cmpts.nss,
        uuid: cmpts.uuid,
        fragment: cmpts.fragment,
        reference: cmpts.reference,
        resourceName: cmpts.resourceName,
        secure: cmpts.secure,
        error: ""
      };
      const options = Object.assign({}, opts);
      const uriTokens = [];
      const schemeHandler = getSchemeHandler(options.scheme || component.scheme);
      if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options);
      if (component.path !== void 0) {
        if (!options.skipEscape) {
          component.path = escapePreservingEscapes(component.path);
          if (component.scheme !== void 0) {
            component.path = component.path.split("%3A").join(":");
          }
        } else {
          component.path = normalizePercentEncoding(component.path);
        }
      }
      if (options.reference !== "suffix" && component.scheme) {
        uriTokens.push(component.scheme, ":");
      }
      const authority = recomposeAuthority(component);
      if (authority !== void 0) {
        if (options.reference !== "suffix") {
          uriTokens.push("//");
        }
        uriTokens.push(authority);
        if (component.path && component.path[0] !== "/") {
          uriTokens.push("/");
        }
      }
      if (component.path !== void 0) {
        let s2 = component.path;
        if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
          s2 = removeDotSegments(s2);
        }
        if (authority === void 0 && s2[0] === "/" && s2[1] === "/") {
          s2 = "/%2F" + s2.slice(2);
        }
        uriTokens.push(s2);
      }
      if (component.query !== void 0) {
        uriTokens.push("?", component.query);
      }
      if (component.fragment !== void 0) {
        uriTokens.push("#", component.fragment);
      }
      return uriTokens.join("");
    }
    var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
    var AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/;
    var AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;
    function getParseError(parsed, matches) {
      if (matches[2] !== void 0 && parsed.path && parsed.path[0] !== "/") {
        return 'URI path must start with "/" when authority is present.';
      }
      if (typeof parsed.port === "number" && (parsed.port < 0 || parsed.port > 65535)) {
        return "URI port is malformed.";
      }
      return void 0;
    }
    function parseWithStatus(uri, opts) {
      const options = Object.assign({}, opts);
      const parsed = {
        scheme: void 0,
        userinfo: void 0,
        host: "",
        port: void 0,
        path: "",
        query: void 0,
        fragment: void 0
      };
      let malformedAuthorityOrPort = false;
      let isIP2 = false;
      if (options.reference === "suffix") {
        if (options.scheme) {
          uri = options.scheme + ":" + uri;
        } else {
          uri = "//" + uri;
        }
      }
      const authorityMatch = uri.match(AUTHORITY_PREFIX);
      if (authorityMatch !== null && authorityMatch[1].indexOf("\\") !== -1) {
        parsed.error = "URI authority must not contain a literal backslash.";
        malformedAuthorityOrPort = true;
      }
      const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION);
      if (introducerMatch !== null) {
        const region = introducerMatch[1];
        const normalizedRegion = region.replace(/[\t\n\r]/g, "");
        if (normalizedRegion.length >= 2) {
          if (normalizedRegion.slice(0, 2) !== "//") {
            parsed.error = parsed.error || "URI authority must not contain a literal backslash.";
            malformedAuthorityOrPort = true;
          } else if (region.length !== normalizedRegion.length) {
            parsed.error = parsed.error || "URI authority introducer must not contain whitespace.";
            malformedAuthorityOrPort = true;
          }
        }
      }
      const matches = uri.match(URI_PARSE);
      if (matches) {
        parsed.scheme = matches[1];
        parsed.userinfo = matches[3];
        parsed.host = matches[4];
        parsed.port = parseInt(matches[5], 10);
        parsed.path = matches[6] || "";
        parsed.query = matches[7];
        parsed.fragment = matches[8];
        if (isNaN(parsed.port)) {
          parsed.port = matches[5];
        }
        const parseError = getParseError(parsed, matches);
        if (parseError !== void 0) {
          parsed.error = parsed.error || parseError;
          malformedAuthorityOrPort = true;
        }
        if (parsed.host) {
          const ipv4result = isIPv4(parsed.host);
          if (ipv4result === false) {
            const ipv6result = normalizeIPv6(parsed.host);
            parsed.host = ipv6result.host.toLowerCase();
            isIP2 = ipv6result.isIPV6;
          } else {
            isIP2 = true;
          }
        }
        if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) {
          parsed.reference = "same-document";
        } else if (parsed.scheme === void 0) {
          parsed.reference = "relative";
        } else if (parsed.fragment === void 0) {
          parsed.reference = "absolute";
        } else {
          parsed.reference = "uri";
        }
        if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) {
          parsed.error = parsed.error || "URI is not a " + options.reference + " reference.";
        }
        const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);
        if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
          if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP2 === false && nonSimpleDomain(parsed.host)) {
            try {
              parsed.host = new URL("http://" + parsed.host).hostname;
            } catch (e2) {
              parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e2;
            }
          }
        }
        if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
          if (uri.indexOf("%") !== -1) {
            if (parsed.scheme !== void 0) {
              parsed.scheme = unescape(parsed.scheme);
            }
            if (parsed.host !== void 0) {
              parsed.host = reescapeHostDelimiters(unescape(parsed.host), isIP2);
            }
          }
          if (parsed.path) {
            parsed.path = normalizePathEncoding(parsed.path);
          }
          if (parsed.fragment) {
            try {
              parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment));
            } catch {
              parsed.error = parsed.error || "URI malformed";
            }
          }
        }
        if (schemeHandler && schemeHandler.parse) {
          schemeHandler.parse(parsed, options);
        }
      } else {
        parsed.error = parsed.error || "URI can not be parsed.";
      }
      return { parsed, malformedAuthorityOrPort };
    }
    function parse3(uri, opts) {
      return parseWithStatus(uri, opts).parsed;
    }
    function normalizeString(uri, opts) {
      return normalizeStringWithStatus(uri, opts).normalized;
    }
    function normalizeStringWithStatus(uri, opts) {
      const { parsed, malformedAuthorityOrPort } = parseWithStatus(uri, opts);
      return {
        normalized: malformedAuthorityOrPort ? uri : serialize(parsed, opts),
        malformedAuthorityOrPort
      };
    }
    function normalizeComparableURI(uri, opts) {
      if (typeof uri === "string") {
        const { normalized, malformedAuthorityOrPort } = normalizeStringWithStatus(uri, opts);
        return malformedAuthorityOrPort ? void 0 : normalized;
      }
      if (typeof uri === "object") {
        return serialize(uri, opts);
      }
    }
    var fastUri = {
      SCHEMES,
      normalize,
      resolve: resolve2,
      resolveComponent,
      equal,
      serialize,
      parse: parse3
    };
    module2.exports = fastUri;
    module2.exports.default = fastUri;
    module2.exports.fastUri = fastUri;
  }
});

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

// node_modules/ajv/dist/core.js
var require_core = __commonJS({
  "node_modules/ajv/dist/core.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CodeGen = exports2.Name = exports2.nil = exports2.stringify = exports2.str = exports2._ = exports2.KeywordCxt = void 0;
    var validate_1 = require_validate();
    Object.defineProperty(exports2, "KeywordCxt", { enumerable: true, get: function() {
      return validate_1.KeywordCxt;
    } });
    var codegen_1 = require_codegen();
    Object.defineProperty(exports2, "_", { enumerable: true, get: function() {
      return codegen_1._;
    } });
    Object.defineProperty(exports2, "str", { enumerable: true, get: function() {
      return codegen_1.str;
    } });
    Object.defineProperty(exports2, "stringify", { enumerable: true, get: function() {
      return codegen_1.stringify;
    } });
    Object.defineProperty(exports2, "nil", { enumerable: true, get: function() {
      return codegen_1.nil;
    } });
    Object.defineProperty(exports2, "Name", { enumerable: true, get: function() {
      return codegen_1.Name;
    } });
    Object.defineProperty(exports2, "CodeGen", { enumerable: true, get: function() {
      return codegen_1.CodeGen;
    } });
    var validation_error_1 = require_validation_error();
    var ref_error_1 = require_ref_error();
    var rules_1 = require_rules();
    var compile_1 = require_compile();
    var codegen_2 = require_codegen();
    var resolve_1 = require_resolve();
    var dataType_1 = require_dataType();
    var util_1 = require_util5();
    var $dataRefSchema = require_data();
    var uri_1 = require_uri2();
    var defaultRegExp = (str, flags) => new RegExp(str, flags);
    defaultRegExp.code = "new RegExp";
    var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
    var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([
      "validate",
      "serialize",
      "parse",
      "wrapper",
      "root",
      "schema",
      "keyword",
      "pattern",
      "formats",
      "validate$data",
      "func",
      "obj",
      "Error"
    ]);
    var removedOptions = {
      errorDataPath: "",
      format: "`validateFormats: false` can be used instead.",
      nullable: '"nullable" keyword is supported by default.',
      jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
      extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
      missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
      processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
      sourceCode: "Use option `code: {source: true}`",
      strictDefaults: "It is default now, see option `strict`.",
      strictKeywords: "It is default now, see option `strict`.",
      uniqueItems: '"uniqueItems" keyword is always validated.',
      unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
      cache: "Map is used as cache, schema object as key.",
      serialize: "Map is used as cache, schema object as key.",
      ajvErrors: "It is default now."
    };
    var deprecatedOptions = {
      ignoreKeywordsWithRef: "",
      jsPropertySyntax: "",
      unicode: '"minLength"/"maxLength" account for unicode characters by default.'
    };
    var MAX_EXPRESSION = 200;
    function requiredOptions(o) {
      var _a3, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
      const s2 = o.strict;
      const _optz = (_a3 = o.code) === null || _a3 === void 0 ? void 0 : _a3.optimize;
      const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;
      const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
      const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
      return {
        strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s2) !== null && _f !== void 0 ? _f : true,
        strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s2) !== null && _h !== void 0 ? _h : true,
        strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s2) !== null && _k !== void 0 ? _k : "log",
        strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s2) !== null && _m !== void 0 ? _m : "log",
        strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s2) !== null && _p !== void 0 ? _p : false,
        code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
        loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
        loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
        meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
        messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
        inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
        schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
        addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
        validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
        validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
        unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
        int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
        uriResolver
      };
    }
    var Ajv2 = class {
      constructor(opts = {}) {
        this.schemas = {};
        this.refs = {};
        this.formats = /* @__PURE__ */ Object.create(null);
        this._compilations = /* @__PURE__ */ new Set();
        this._loading = {};
        this._cache = /* @__PURE__ */ new Map();
        opts = this.opts = { ...opts, ...requiredOptions(opts) };
        const { es5, lines } = this.opts.code;
        this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
        this.logger = getLogger(opts.logger);
        const formatOpt = opts.validateFormats;
        opts.validateFormats = false;
        this.RULES = (0, rules_1.getRules)();
        checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
        checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
        this._metaOpts = getMetaSchemaOptions.call(this);
        if (opts.formats)
          addInitialFormats.call(this);
        this._addVocabularies();
        this._addDefaultMetaSchema();
        if (opts.keywords)
          addInitialKeywords.call(this, opts.keywords);
        if (typeof opts.meta == "object")
          this.addMetaSchema(opts.meta);
        addInitialSchemas.call(this);
        opts.validateFormats = formatOpt;
      }
      _addVocabularies() {
        this.addKeyword("$async");
      }
      _addDefaultMetaSchema() {
        const { $data, meta: meta3, schemaId } = this.opts;
        let _dataRefSchema = $dataRefSchema;
        if (schemaId === "id") {
          _dataRefSchema = { ...$dataRefSchema };
          _dataRefSchema.id = _dataRefSchema.$id;
          delete _dataRefSchema.$id;
        }
        if (meta3 && $data)
          this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
      }
      defaultMeta() {
        const { meta: meta3, schemaId } = this.opts;
        return this.opts.defaultMeta = typeof meta3 == "object" ? meta3[schemaId] || meta3 : void 0;
      }
      validate(schemaKeyRef, data) {
        let v;
        if (typeof schemaKeyRef == "string") {
          v = this.getSchema(schemaKeyRef);
          if (!v)
            throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
        } else {
          v = this.compile(schemaKeyRef);
        }
        const valid = v(data);
        if (!("$async" in v))
          this.errors = v.errors;
        return valid;
      }
      compile(schema, _meta) {
        const sch = this._addSchema(schema, _meta);
        return sch.validate || this._compileSchemaEnv(sch);
      }
      compileAsync(schema, meta3) {
        if (typeof this.opts.loadSchema != "function") {
          throw new Error("options.loadSchema should be a function");
        }
        const { loadSchema } = this.opts;
        return runCompileAsync.call(this, schema, meta3);
        async function runCompileAsync(_schema, _meta) {
          await loadMetaSchema.call(this, _schema.$schema);
          const sch = this._addSchema(_schema, _meta);
          return sch.validate || _compileAsync.call(this, sch);
        }
        async function loadMetaSchema($ref) {
          if ($ref && !this.getSchema($ref)) {
            await runCompileAsync.call(this, { $ref }, true);
          }
        }
        async function _compileAsync(sch) {
          try {
            return this._compileSchemaEnv(sch);
          } catch (e2) {
            if (!(e2 instanceof ref_error_1.default))
              throw e2;
            checkLoaded.call(this, e2);
            await loadMissingSchema.call(this, e2.missingSchema);
            return _compileAsync.call(this, sch);
          }
        }
        function checkLoaded({ missingSchema: ref, missingRef }) {
          if (this.refs[ref]) {
            throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
          }
        }
        async function loadMissingSchema(ref) {
          const _schema = await _loadSchema.call(this, ref);
          if (!this.refs[ref])
            await loadMetaSchema.call(this, _schema.$schema);
          if (!this.refs[ref])
            this.addSchema(_schema, ref, meta3);
        }
        async function _loadSchema(ref) {
          const p = this._loading[ref];
          if (p)
            return p;
          try {
            return await (this._loading[ref] = loadSchema(ref));
          } finally {
            delete this._loading[ref];
          }
        }
      }
      // Adds schema to the instance
      addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) {
        if (Array.isArray(schema)) {
          for (const sch of schema)
            this.addSchema(sch, void 0, _meta, _validateSchema);
          return this;
        }
        let id;
        if (typeof schema === "object") {
          const { schemaId } = this.opts;
          id = schema[schemaId];
          if (id !== void 0 && typeof id != "string") {
            throw new Error(`schema ${schemaId} must be string`);
          }
        }
        key = (0, resolve_1.normalizeId)(key || id);
        this._checkUnique(key);
        this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
        return this;
      }
      // Add schema that will be used to validate other schemas
      // options in META_IGNORE_OPTIONS are alway set to false
      addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) {
        this.addSchema(schema, key, true, _validateSchema);
        return this;
      }
      //  Validate schema against its meta-schema
      validateSchema(schema, throwOrLogError) {
        if (typeof schema == "boolean")
          return true;
        let $schema;
        $schema = schema.$schema;
        if ($schema !== void 0 && typeof $schema != "string") {
          throw new Error("$schema must be a string");
        }
        $schema = $schema || this.opts.defaultMeta || this.defaultMeta();
        if (!$schema) {
          this.logger.warn("meta-schema not available");
          this.errors = null;
          return true;
        }
        const valid = this.validate($schema, schema);
        if (!valid && throwOrLogError) {
          const message = "schema is invalid: " + this.errorsText();
          if (this.opts.validateSchema === "log")
            this.logger.error(message);
          else
            throw new Error(message);
        }
        return valid;
      }
      // Get compiled schema by `key` or `ref`.
      // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
      getSchema(keyRef) {
        let sch;
        while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
          keyRef = sch;
        if (sch === void 0) {
          const { schemaId } = this.opts;
          const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
          sch = compile_1.resolveSchema.call(this, root, keyRef);
          if (!sch)
            return;
          this.refs[keyRef] = sch;
        }
        return sch.validate || this._compileSchemaEnv(sch);
      }
      // Remove cached schema(s).
      // If no parameter is passed all schemas but meta-schemas are removed.
      // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
      // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
      removeSchema(schemaKeyRef) {
        if (schemaKeyRef instanceof RegExp) {
          this._removeAllSchemas(this.schemas, schemaKeyRef);
          this._removeAllSchemas(this.refs, schemaKeyRef);
          return this;
        }
        switch (typeof schemaKeyRef) {
          case "undefined":
            this._removeAllSchemas(this.schemas);
            this._removeAllSchemas(this.refs);
            this._cache.clear();
            return this;
          case "string": {
            const sch = getSchEnv.call(this, schemaKeyRef);
            if (typeof sch == "object")
              this._cache.delete(sch.schema);
            delete this.schemas[schemaKeyRef];
            delete this.refs[schemaKeyRef];
            return this;
          }
          case "object": {
            const cacheKey = schemaKeyRef;
            this._cache.delete(cacheKey);
            let id = schemaKeyRef[this.opts.schemaId];
            if (id) {
              id = (0, resolve_1.normalizeId)(id);
              delete this.schemas[id];
              delete this.refs[id];
            }
            return this;
          }
          default:
            throw new Error("ajv.removeSchema: invalid parameter");
        }
      }
      // add "vocabulary" - a collection of keywords
      addVocabulary(definitions) {
        for (const def of definitions)
          this.addKeyword(def);
        return this;
      }
      addKeyword(kwdOrDef, def) {
        let keyword;
        if (typeof kwdOrDef == "string") {
          keyword = kwdOrDef;
          if (typeof def == "object") {
            this.logger.warn("these parameters are deprecated, see docs for addKeyword");
            def.keyword = keyword;
          }
        } else if (typeof kwdOrDef == "object" && def === void 0) {
          def = kwdOrDef;
          keyword = def.keyword;
          if (Array.isArray(keyword) && !keyword.length) {
            throw new Error("addKeywords: keyword must be string or non-empty array");
          }
        } else {
          throw new Error("invalid addKeywords parameters");
        }
        checkKeyword.call(this, keyword, def);
        if (!def) {
          (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
          return this;
        }
        keywordMetaschema.call(this, def);
        const definition = {
          ...def,
          type: (0, dataType_1.getJSONTypes)(def.type),
          schemaType: (0, dataType_1.getJSONTypes)(def.schemaType)
        };
        (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t2) => addRule.call(this, k, definition, t2)));
        return this;
      }
      getKeyword(keyword) {
        const rule = this.RULES.all[keyword];
        return typeof rule == "object" ? rule.definition : !!rule;
      }
      // Remove keyword
      removeKeyword(keyword) {
        const { RULES } = this;
        delete RULES.keywords[keyword];
        delete RULES.all[keyword];
        for (const group of RULES.rules) {
          const i2 = group.rules.findIndex((rule) => rule.keyword === keyword);
          if (i2 >= 0)
            group.rules.splice(i2, 1);
        }
        return this;
      }
      // Add format
      addFormat(name, format) {
        if (typeof format == "string")
          format = new RegExp(format);
        this.formats[name] = format;
        return this;
      }
      errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) {
        if (!errors || errors.length === 0)
          return "No errors";
        return errors.map((e2) => `${dataVar}${e2.instancePath} ${e2.message}`).reduce((text, msg) => text + separator + msg);
      }
      $dataMetaSchema(metaSchema, keywordsJsonPointers) {
        const rules = this.RULES.all;
        metaSchema = JSON.parse(JSON.stringify(metaSchema));
        for (const jsonPointer of keywordsJsonPointers) {
          const segments = jsonPointer.split("/").slice(1);
          let keywords = metaSchema;
          for (const seg of segments)
            keywords = keywords[seg];
          for (const key in rules) {
            const rule = rules[key];
            if (typeof rule != "object")
              continue;
            const { $data } = rule.definition;
            const schema = keywords[key];
            if ($data && schema)
              keywords[key] = schemaOrData(schema);
          }
        }
        return metaSchema;
      }
      _removeAllSchemas(schemas, regex) {
        for (const keyRef in schemas) {
          const sch = schemas[keyRef];
          if (!regex || regex.test(keyRef)) {
            if (typeof sch == "string") {
              delete schemas[keyRef];
            } else if (sch && !sch.meta) {
              this._cache.delete(sch.schema);
              delete schemas[keyRef];
            }
          }
        }
      }
      _addSchema(schema, meta3, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
        let id;
        const { schemaId } = this.opts;
        if (typeof schema == "object") {
          id = schema[schemaId];
        } else {
          if (this.opts.jtd)
            throw new Error("schema must be object");
          else if (typeof schema != "boolean")
            throw new Error("schema must be object or boolean");
        }
        let sch = this._cache.get(schema);
        if (sch !== void 0)
          return sch;
        baseId = (0, resolve_1.normalizeId)(id || baseId);
        const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
        sch = new compile_1.SchemaEnv({ schema, schemaId, meta: meta3, baseId, localRefs });
        this._cache.set(sch.schema, sch);
        if (addSchema && !baseId.startsWith("#")) {
          if (baseId)
            this._checkUnique(baseId);
          this.refs[baseId] = sch;
        }
        if (validateSchema)
          this.validateSchema(schema, true);
        return sch;
      }
      _checkUnique(id) {
        if (this.schemas[id] || this.refs[id]) {
          throw new Error(`schema with key or id "${id}" already exists`);
        }
      }
      _compileSchemaEnv(sch) {
        if (sch.meta)
          this._compileMetaSchema(sch);
        else
          compile_1.compileSchema.call(this, sch);
        if (!sch.validate)
          throw new Error("ajv implementation error");
        return sch.validate;
      }
      _compileMetaSchema(sch) {
        const currentOpts = this.opts;
        this.opts = this._metaOpts;
        try {
          compile_1.compileSchema.call(this, sch);
        } finally {
          this.opts = currentOpts;
        }
      }
    };
    Ajv2.ValidationError = validation_error_1.default;
    Ajv2.MissingRefError = ref_error_1.default;
    exports2.default = Ajv2;
    function checkOptions(checkOpts, options, msg, log = "error") {
      for (const key in checkOpts) {
        const opt = key;
        if (opt in options)
          this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
      }
    }
    function getSchEnv(keyRef) {
      keyRef = (0, resolve_1.normalizeId)(keyRef);
      return this.schemas[keyRef] || this.refs[keyRef];
    }
    function addInitialSchemas() {
      const optsSchemas = this.opts.schemas;
      if (!optsSchemas)
        return;
      if (Array.isArray(optsSchemas))
        this.addSchema(optsSchemas);
      else
        for (const key in optsSchemas)
          this.addSchema(optsSchemas[key], key);
    }
    function addInitialFormats() {
      for (const name in this.opts.formats) {
        const format = this.opts.formats[name];
        if (format)
          this.addFormat(name, format);
      }
    }
    function addInitialKeywords(defs) {
      if (Array.isArray(defs)) {
        this.addVocabulary(defs);
        return;
      }
      this.logger.warn("keywords option as map is deprecated, pass array");
      for (const keyword in defs) {
        const def = defs[keyword];
        if (!def.keyword)
          def.keyword = keyword;
        this.addKeyword(def);
      }
    }
    function getMetaSchemaOptions() {
      const metaOpts = { ...this.opts };
      for (const opt of META_IGNORE_OPTIONS)
        delete metaOpts[opt];
      return metaOpts;
    }
    var noLogs = { log() {
    }, warn() {
    }, error() {
    } };
    function getLogger(logger) {
      if (logger === false)
        return noLogs;
      if (logger === void 0)
        return console;
      if (logger.log && logger.warn && logger.error)
        return logger;
      throw new Error("logger must implement log, warn and error methods");
    }
    var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
    function checkKeyword(keyword, def) {
      const { RULES } = this;
      (0, util_1.eachItem)(keyword, (kwd) => {
        if (RULES.keywords[kwd])
          throw new Error(`Keyword ${kwd} is already defined`);
        if (!KEYWORD_NAME.test(kwd))
          throw new Error(`Keyword ${kwd} has invalid name`);
      });
      if (!def)
        return;
      if (def.$data && !("code" in def || "validate" in def)) {
        throw new Error('$data keyword must have "code" or "validate" function');
      }
    }
    function addRule(keyword, definition, dataType) {
      var _a3;
      const post = definition === null || definition === void 0 ? void 0 : definition.post;
      if (dataType && post)
        throw new Error('keyword with "post" flag cannot have "type"');
      const { RULES } = this;
      let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t2 }) => t2 === dataType);
      if (!ruleGroup) {
        ruleGroup = { type: dataType, rules: [] };
        RULES.rules.push(ruleGroup);
      }
      RULES.keywords[keyword] = true;
      if (!definition)
        return;
      const rule = {
        keyword,
        definition: {
          ...definition,
          type: (0, dataType_1.getJSONTypes)(definition.type),
          schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType)
        }
      };
      if (definition.before)
        addBeforeRule.call(this, ruleGroup, rule, definition.before);
      else
        ruleGroup.rules.push(rule);
      RULES.all[keyword] = rule;
      (_a3 = definition.implements) === null || _a3 === void 0 ? void 0 : _a3.forEach((kwd) => this.addKeyword(kwd));
    }
    function addBeforeRule(ruleGroup, rule, before) {
      const i2 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
      if (i2 >= 0) {
        ruleGroup.rules.splice(i2, 0, rule);
      } else {
        ruleGroup.rules.push(rule);
        this.logger.warn(`rule ${before} is not defined`);
      }
    }
    function keywordMetaschema(def) {
      let { metaSchema } = def;
      if (metaSchema === void 0)
        return;
      if (def.$data && this.opts.$data)
        metaSchema = schemaOrData(metaSchema);
      def.validateSchema = this.compile(metaSchema, true);
    }
    var $dataRef = {
      $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"
    };
    function schemaOrData(schema) {
      return { anyOf: [schema, $dataRef] };
    }
  }
});

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

// node_modules/ajv/dist/vocabularies/core/ref.js
var require_ref2 = __commonJS({
  "node_modules/ajv/dist/vocabularies/core/ref.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.callRef = exports2.getValidate = void 0;
    var ref_error_1 = require_ref_error();
    var code_1 = require_code2();
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var compile_1 = require_compile();
    var util_1 = require_util5();
    var def = {
      keyword: "$ref",
      schemaType: "string",
      code(cxt) {
        const { gen, schema: $ref, it } = cxt;
        const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it;
        const { root } = env;
        if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
          return callRootRef();
        const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref);
        if (schOrEnv === void 0)
          throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);
        if (schOrEnv instanceof compile_1.SchemaEnv)
          return callValidate(schOrEnv);
        return inlineRefSchema(schOrEnv);
        function callRootRef() {
          if (env === root)
            return callRef(cxt, validateName, env, env.$async);
          const rootName = gen.scopeValue("root", { ref: root });
          return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async);
        }
        function callValidate(sch) {
          const v = getValidate(cxt, sch);
          callRef(cxt, v, sch, sch.$async);
        }
        function inlineRefSchema(sch) {
          const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
          const valid = gen.name("valid");
          const schCxt = cxt.subschema({
            schema: sch,
            dataTypes: [],
            schemaPath: codegen_1.nil,
            topSchemaRef: schName,
            errSchemaPath: $ref
          }, valid);
          cxt.mergeEvaluated(schCxt);
          cxt.ok(valid);
        }
      }
    };
    function getValidate(cxt, sch) {
      const { gen } = cxt;
      return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`;
    }
    exports2.getValidate = getValidate;
    function callRef(cxt, v, sch, $async) {
      const { gen, it } = cxt;
      const { allErrors, schemaEnv: env, opts } = it;
      const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
      if ($async)
        callAsyncRef();
      else
        callSyncRef();
      function callAsyncRef() {
        if (!env.$async)
          throw new Error("async schema referenced by sync schema");
        const valid = gen.let("valid");
        gen.try(() => {
          gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);
          addEvaluatedFrom(v);
          if (!allErrors)
            gen.assign(valid, true);
        }, (e2) => {
          gen.if((0, codegen_1._)`!(${e2} instanceof ${it.ValidationError})`, () => gen.throw(e2));
          addErrorsFrom(e2);
          if (!allErrors)
            gen.assign(valid, false);
        });
        cxt.ok(valid);
      }
      function callSyncRef() {
        cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
      }
      function addErrorsFrom(source) {
        const errs = (0, codegen_1._)`${source}.errors`;
        gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`);
        gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
      }
      function addEvaluatedFrom(source) {
        var _a3;
        if (!it.opts.unevaluated)
          return;
        const schEvaluated = (_a3 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a3 === void 0 ? void 0 : _a3.evaluated;
        if (it.props !== true) {
          if (schEvaluated && !schEvaluated.dynamicProps) {
            if (schEvaluated.props !== void 0) {
              it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);
            }
          } else {
            const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`);
            it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);
          }
        }
        if (it.items !== true) {
          if (schEvaluated && !schEvaluated.dynamicItems) {
            if (schEvaluated.items !== void 0) {
              it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);
            }
          } else {
            const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`);
            it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);
          }
        }
      }
    }
    exports2.callRef = callRef;
    exports2.default = def;
  }
});

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

// node_modules/ajv/dist/vocabularies/validation/limitNumber.js
var require_limitNumber = __commonJS({
  "node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var ops = codegen_1.operators;
    var KWDs = {
      maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
      minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
      exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
      exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }
    };
    var error51 = {
      message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`,
      params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`
    };
    var def = {
      keyword: Object.keys(KWDs),
      type: "number",
      schemaType: "number",
      $data: true,
      error: error51,
      code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
      }
    };
    exports2.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/validation/multipleOf.js
var require_multipleOf = __commonJS({
  "node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var error51 = {
      message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`,
      params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}`
    };
    var def = {
      keyword: "multipleOf",
      type: "number",
      schemaType: "number",
      $data: true,
      error: error51,
      code(cxt) {
        const { gen, data, schemaCode, it } = cxt;
        const prec = it.opts.multipleOfPrecision;
        const res = gen.let("res");
        const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
        cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
      }
    };
    exports2.default = def;
  }
});

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

// node_modules/ajv/dist/vocabularies/validation/limitLength.js
var require_limitLength = __commonJS({
  "node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util5();
    var ucs2length_1 = require_ucs2length();
    var error51 = {
      message({ keyword, schemaCode }) {
        const comp = keyword === "maxLength" ? "more" : "fewer";
        return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`;
      },
      params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
    };
    var def = {
      keyword: ["maxLength", "minLength"],
      type: "string",
      schemaType: "number",
      $data: true,
      error: error51,
      code(cxt) {
        const { keyword, data, schemaCode, it } = cxt;
        const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
        const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
        cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`);
      }
    };
    exports2.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/validation/pattern.js
var require_pattern = __commonJS({
  "node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code2();
    var util_1 = require_util5();
    var codegen_1 = require_codegen();
    var error51 = {
      message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`,
      params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}`
    };
    var def = {
      keyword: "pattern",
      type: "string",
      schemaType: "string",
      $data: true,
      error: error51,
      code(cxt) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        const u = it.opts.unicodeRegExp ? "u" : "";
        if ($data) {
          const { regExp } = it.opts.code;
          const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp);
          const valid = gen.let("valid");
          gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false));
          cxt.fail$data((0, codegen_1._)`!${valid}`);
        } else {
          const regExp = (0, code_1.usePattern)(cxt, schema);
          cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`);
        }
      }
    };
    exports2.default = def;
  }
});

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

// node_modules/ajv/dist/vocabularies/validation/required.js
var require_required = __commonJS({
  "node_modules/ajv/dist/vocabularies/validation/required.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code2();
    var codegen_1 = require_codegen();
    var util_1 = require_util5();
    var error51 = {
      message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`,
      params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}`
    };
    var def = {
      keyword: "required",
      type: "object",
      schemaType: "array",
      $data: true,
      error: error51,
      code(cxt) {
        const { gen, schema, schemaCode, data, $data, it } = cxt;
        const { opts } = it;
        if (!$data && schema.length === 0)
          return;
        const useLoop = schema.length >= opts.loopRequired;
        if (it.allErrors)
          allErrorsMode();
        else
          exitOnErrorMode();
        if (opts.strictRequired) {
          const props = cxt.parentSchema.properties;
          const { definedProperties } = cxt.it;
          for (const requiredKey of schema) {
            if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) {
              const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
              const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
              (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);
            }
          }
        }
        function allErrorsMode() {
          if (useLoop || $data) {
            cxt.block$data(codegen_1.nil, loopAllRequired);
          } else {
            for (const prop of schema) {
              (0, code_1.checkReportMissingProp)(cxt, prop);
            }
          }
        }
        function exitOnErrorMode() {
          const missing = gen.let("missing");
          if (useLoop || $data) {
            const valid = gen.let("valid", true);
            cxt.block$data(valid, () => loopUntilMissing(missing, valid));
            cxt.ok(valid);
          } else {
            gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
            (0, code_1.reportMissingProp)(cxt, missing);
            gen.else();
          }
        }
        function loopAllRequired() {
          gen.forOf("prop", schemaCode, (prop) => {
            cxt.setParams({ missingProperty: prop });
            gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
          });
        }
        function loopUntilMissing(missing, valid) {
          cxt.setParams({ missingProperty: missing });
          gen.forOf(missing, schemaCode, () => {
            gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));
            gen.if((0, codegen_1.not)(valid), () => {
              cxt.error();
              gen.break();
            });
          }, codegen_1.nil);
        }
      }
    };
    exports2.default = def;
  }
});

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

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

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

// node_modules/ajv/dist/vocabularies/validation/const.js
var require_const = __commonJS({
  "node_modules/ajv/dist/vocabularies/validation/const.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util5();
    var equal_1 = require_equal();
    var error51 = {
      message: "must be equal to constant",
      params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`
    };
    var def = {
      keyword: "const",
      $data: true,
      error: error51,
      code(cxt) {
        const { gen, data, $data, schemaCode, schema } = cxt;
        if ($data || schema && typeof schema == "object") {
          cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
        } else {
          cxt.fail((0, codegen_1._)`${schema} !== ${data}`);
        }
      }
    };
    exports2.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/validation/enum.js
var require_enum = __commonJS({
  "node_modules/ajv/dist/vocabularies/validation/enum.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util5();
    var equal_1 = require_equal();
    var error51 = {
      message: "must be equal to one of the allowed values",
      params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}`
    };
    var def = {
      keyword: "enum",
      schemaType: "array",
      $data: true,
      error: error51,
      code(cxt) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        if (!$data && schema.length === 0)
          throw new Error("enum must have non-empty array");
        const useLoop = schema.length >= it.opts.loopEnum;
        let eql;
        const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default);
        let valid;
        if (useLoop || $data) {
          valid = gen.let("valid");
          cxt.block$data(valid, loopEnum);
        } else {
          if (!Array.isArray(schema))
            throw new Error("ajv implementation error");
          const vSchema = gen.const("vSchema", schemaCode);
          valid = (0, codegen_1.or)(...schema.map((_x, i2) => equalCode(vSchema, i2)));
        }
        cxt.pass(valid);
        function loopEnum() {
          gen.assign(valid, false);
          gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
        }
        function equalCode(vSchema, i2) {
          const sch = schema[i2];
          return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i2}])` : (0, codegen_1._)`${data} === ${sch}`;
        }
      }
    };
    exports2.default = def;
  }
});

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

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

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

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

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

// node_modules/ajv/dist/vocabularies/applicator/contains.js
var require_contains = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util5();
    var error51 = {
      message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`,
      params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}`
    };
    var def = {
      keyword: "contains",
      type: "array",
      schemaType: ["object", "boolean"],
      before: "uniqueItems",
      trackErrors: true,
      error: error51,
      code(cxt) {
        const { gen, schema, parentSchema, data, it } = cxt;
        let min;
        let max;
        const { minContains, maxContains } = parentSchema;
        if (it.opts.next) {
          min = minContains === void 0 ? 1 : minContains;
          max = maxContains;
        } else {
          min = 1;
        }
        const len = gen.const("len", (0, codegen_1._)`${data}.length`);
        cxt.setParams({ min, max });
        if (max === void 0 && min === 0) {
          (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
          return;
        }
        if (max !== void 0 && min > max) {
          (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
          cxt.fail();
          return;
        }
        if ((0, util_1.alwaysValidSchema)(it, schema)) {
          let cond = (0, codegen_1._)`${len} >= ${min}`;
          if (max !== void 0)
            cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`;
          cxt.pass(cond);
          return;
        }
        it.items = true;
        const valid = gen.name("valid");
        if (max === void 0 && min === 1) {
          validateItems(valid, () => gen.if(valid, () => gen.break()));
        } else if (min === 0) {
          gen.let(valid, true);
          if (max !== void 0)
            gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount);
        } else {
          gen.let(valid, false);
          validateItemsWithCount();
        }
        cxt.result(valid, () => cxt.reset());
        function validateItemsWithCount() {
          const schValid = gen.name("_valid");
          const count = gen.let("count", 0);
          validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
        }
        function validateItems(_valid, block) {
          gen.forRange("i", 0, len, (i2) => {
            cxt.subschema({
              keyword: "contains",
              dataProp: i2,
              dataPropType: util_1.Type.Num,
              compositeRule: true
            }, _valid);
            block();
          });
        }
        function checkLimits(count) {
          gen.code((0, codegen_1._)`${count}++`);
          if (max === void 0) {
            gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break());
          } else {
            gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break());
            if (min === 1)
              gen.assign(valid, true);
            else
              gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true));
          }
        }
      }
    };
    exports2.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/dependencies.js
var require_dependencies = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateSchemaDeps = exports2.validatePropertyDeps = exports2.error = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util5();
    var code_1 = require_code2();
    exports2.error = {
      message: ({ params: { property, depsCount, deps } }) => {
        const property_ies = depsCount === 1 ? "property" : "properties";
        return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`;
      },
      params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`
      // TODO change to reference
    };
    var def = {
      keyword: "dependencies",
      type: "object",
      schemaType: "object",
      error: exports2.error,
      code(cxt) {
        const [propDeps, schDeps] = splitDependencies(cxt);
        validatePropertyDeps(cxt, propDeps);
        validateSchemaDeps(cxt, schDeps);
      }
    };
    function splitDependencies({ schema }) {
      const propertyDeps = {};
      const schemaDeps = {};
      for (const key in schema) {
        if (key === "__proto__")
          continue;
        const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
        deps[key] = schema[key];
      }
      return [propertyDeps, schemaDeps];
    }
    function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
      const { gen, data, it } = cxt;
      if (Object.keys(propertyDeps).length === 0)
        return;
      const missing = gen.let("missing");
      for (const prop in propertyDeps) {
        const deps = propertyDeps[prop];
        if (deps.length === 0)
          continue;
        const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);
        cxt.setParams({
          property: prop,
          depsCount: deps.length,
          deps: deps.join(", ")
        });
        if (it.allErrors) {
          gen.if(hasProperty, () => {
            for (const depProp of deps) {
              (0, code_1.checkReportMissingProp)(cxt, depProp);
            }
          });
        } else {
          gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
          (0, code_1.reportMissingProp)(cxt, missing);
          gen.else();
        }
      }
    }
    exports2.validatePropertyDeps = validatePropertyDeps;
    function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
      const { gen, data, keyword, it } = cxt;
      const valid = gen.name("valid");
      for (const prop in schemaDeps) {
        if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))
          continue;
        gen.if(
          (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties),
          () => {
            const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
            cxt.mergeValidEvaluated(schCxt, valid);
          },
          () => gen.var(valid, true)
          // TODO var
        );
        cxt.ok(valid);
      }
    }
    exports2.validateSchemaDeps = validateSchemaDeps;
    exports2.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/propertyNames.js
var require_propertyNames = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util5();
    var error51 = {
      message: "property name must be valid",
      params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}`
    };
    var def = {
      keyword: "propertyNames",
      type: "object",
      schemaType: ["object", "boolean"],
      error: error51,
      code(cxt) {
        const { gen, schema, data, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema))
          return;
        const valid = gen.name("valid");
        gen.forIn("key", data, (key) => {
          cxt.setParams({ propertyName: key });
          cxt.subschema({
            keyword: "propertyNames",
            data: key,
            dataTypes: ["string"],
            propertyName: key,
            compositeRule: true
          }, valid);
          gen.if((0, codegen_1.not)(valid), () => {
            cxt.error(true);
            if (!it.allErrors)
              gen.break();
          });
        });
        cxt.ok(valid);
      }
    };
    exports2.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js
var require_additionalProperties = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code2();
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var util_1 = require_util5();
    var error51 = {
      message: "must NOT have additional properties",
      params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}`
    };
    var def = {
      keyword: "additionalProperties",
      type: ["object"],
      schemaType: ["boolean", "object"],
      allowUndefined: true,
      trackErrors: true,
      error: error51,
      code(cxt) {
        const { gen, schema, parentSchema, data, errsCount, it } = cxt;
        if (!errsCount)
          throw new Error("ajv implementation error");
        const { allErrors, opts } = it;
        it.props = true;
        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema))
          return;
        const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
        const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
        checkAdditionalProperties();
        cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
        function checkAdditionalProperties() {
          gen.forIn("key", data, (key) => {
            if (!props.length && !patProps.length)
              additionalPropertyCode(key);
            else
              gen.if(isAdditional(key), () => additionalPropertyCode(key));
          });
        }
        function isAdditional(key) {
          let definedProp;
          if (props.length > 8) {
            const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
            definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
          } else if (props.length) {
            definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`));
          } else {
            definedProp = codegen_1.nil;
          }
          if (patProps.length) {
            definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
          }
          return (0, codegen_1.not)(definedProp);
        }
        function deleteAdditional(key) {
          gen.code((0, codegen_1._)`delete ${data}[${key}]`);
        }
        function additionalPropertyCode(key) {
          if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) {
            deleteAdditional(key);
            return;
          }
          if (schema === false) {
            cxt.setParams({ additionalProperty: key });
            cxt.error();
            if (!allErrors)
              gen.break();
            return;
          }
          if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
            const valid = gen.name("valid");
            if (opts.removeAdditional === "failing") {
              applyAdditionalSchema(key, valid, false);
              gen.if((0, codegen_1.not)(valid), () => {
                cxt.reset();
                deleteAdditional(key);
              });
            } else {
              applyAdditionalSchema(key, valid);
              if (!allErrors)
                gen.if((0, codegen_1.not)(valid), () => gen.break());
            }
          }
        }
        function applyAdditionalSchema(key, valid, errors) {
          const subschema = {
            keyword: "additionalProperties",
            dataProp: key,
            dataPropType: util_1.Type.Str
          };
          if (errors === false) {
            Object.assign(subschema, {
              compositeRule: true,
              createErrors: false,
              allErrors: false
            });
          }
          cxt.subschema(subschema, valid);
        }
      }
    };
    exports2.default = def;
  }
});

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

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

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

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

// node_modules/ajv/dist/vocabularies/applicator/oneOf.js
var require_oneOf = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util5();
    var error51 = {
      message: "must match exactly one schema in oneOf",
      params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}`
    };
    var def = {
      keyword: "oneOf",
      schemaType: "array",
      trackErrors: true,
      error: error51,
      code(cxt) {
        const { gen, schema, parentSchema, it } = cxt;
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        if (it.opts.discriminator && parentSchema.discriminator)
          return;
        const schArr = schema;
        const valid = gen.let("valid", false);
        const passing = gen.let("passing", null);
        const schValid = gen.name("_valid");
        cxt.setParams({ passing });
        gen.block(validateOneOf);
        cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
        function validateOneOf() {
          schArr.forEach((sch, i2) => {
            let schCxt;
            if ((0, util_1.alwaysValidSchema)(it, sch)) {
              gen.var(schValid, true);
            } else {
              schCxt = cxt.subschema({
                keyword: "oneOf",
                schemaProp: i2,
                compositeRule: true
              }, schValid);
            }
            if (i2 > 0) {
              gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i2}]`).else();
            }
            gen.if(schValid, () => {
              gen.assign(valid, true);
              gen.assign(passing, i2);
              if (schCxt)
                cxt.mergeEvaluated(schCxt, codegen_1.Name);
            });
          });
        }
      }
    };
    exports2.default = def;
  }
});

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

// node_modules/ajv/dist/vocabularies/applicator/if.js
var require_if = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/if.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util5();
    var error51 = {
      message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`,
      params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}`
    };
    var def = {
      keyword: "if",
      schemaType: ["object", "boolean"],
      trackErrors: true,
      error: error51,
      code(cxt) {
        const { gen, parentSchema, it } = cxt;
        if (parentSchema.then === void 0 && parentSchema.else === void 0) {
          (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');
        }
        const hasThen = hasSchema(it, "then");
        const hasElse = hasSchema(it, "else");
        if (!hasThen && !hasElse)
          return;
        const valid = gen.let("valid", true);
        const schValid = gen.name("_valid");
        validateIf();
        cxt.reset();
        if (hasThen && hasElse) {
          const ifClause = gen.let("ifClause");
          cxt.setParams({ ifClause });
          gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
        } else if (hasThen) {
          gen.if(schValid, validateClause("then"));
        } else {
          gen.if((0, codegen_1.not)(schValid), validateClause("else"));
        }
        cxt.pass(valid, () => cxt.error(true));
        function validateIf() {
          const schCxt = cxt.subschema({
            keyword: "if",
            compositeRule: true,
            createErrors: false,
            allErrors: false
          }, schValid);
          cxt.mergeEvaluated(schCxt);
        }
        function validateClause(keyword, ifClause) {
          return () => {
            const schCxt = cxt.subschema({ keyword }, schValid);
            gen.assign(valid, schValid);
            cxt.mergeValidEvaluated(schCxt, valid);
            if (ifClause)
              gen.assign(ifClause, (0, codegen_1._)`${keyword}`);
            else
              cxt.setParams({ ifClause: keyword });
          };
        }
      }
    };
    function hasSchema(it, keyword) {
      const schema = it.schema[keyword];
      return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema);
    }
    exports2.default = def;
  }
});

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

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

// node_modules/ajv/dist/vocabularies/format/format.js
var require_format = __commonJS({
  "node_modules/ajv/dist/vocabularies/format/format.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var error51 = {
      message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`,
      params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}`
    };
    var def = {
      keyword: "format",
      type: ["number", "string"],
      schemaType: "string",
      $data: true,
      error: error51,
      code(cxt, ruleType) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        const { opts, errSchemaPath, schemaEnv, self: self2 } = it;
        if (!opts.validateFormats)
          return;
        if ($data)
          validate$DataFormat();
        else
          validateFormat();
        function validate$DataFormat() {
          const fmts = gen.scopeValue("formats", {
            ref: self2.formats,
            code: opts.code.formats
          });
          const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`);
          const fType = gen.let("fType");
          const format = gen.let("format");
          gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef));
          cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
          function unknownFmt() {
            if (opts.strictSchema === false)
              return codegen_1.nil;
            return (0, codegen_1._)`${schemaCode} && !${format}`;
          }
          function invalidFmt() {
            const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`;
            const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;
            return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;
          }
        }
        function validateFormat() {
          const formatDef = self2.formats[schema];
          if (!formatDef) {
            unknownFormat();
            return;
          }
          if (formatDef === true)
            return;
          const [fmtType, format, fmtRef] = getFormat(formatDef);
          if (fmtType === ruleType)
            cxt.pass(validCondition());
          function unknownFormat() {
            if (opts.strictSchema === false) {
              self2.logger.warn(unknownMsg());
              return;
            }
            throw new Error(unknownMsg());
            function unknownMsg() {
              return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
            }
          }
          function getFormat(fmtDef) {
            const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0;
            const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code });
            if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
              return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`];
            }
            return ["string", fmtDef, fmt];
          }
          function validCondition() {
            if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
              if (!schemaEnv.$async)
                throw new Error("async format in sync schema");
              return (0, codegen_1._)`await ${fmtRef}(${data})`;
            }
            return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`;
          }
        }
      }
    };
    exports2.default = def;
  }
});

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

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

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

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

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

// node_modules/ajv/dist/refs/json-schema-draft-07.json
var require_json_schema_draft_07 = __commonJS({
  "node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports2, module2) {
    module2.exports = {
      $schema: "http://json-schema.org/draft-07/schema#",
      $id: "http://json-schema.org/draft-07/schema#",
      title: "Core schema meta-schema",
      definitions: {
        schemaArray: {
          type: "array",
          minItems: 1,
          items: { $ref: "#" }
        },
        nonNegativeInteger: {
          type: "integer",
          minimum: 0
        },
        nonNegativeIntegerDefault0: {
          allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }]
        },
        simpleTypes: {
          enum: ["array", "boolean", "integer", "null", "number", "object", "string"]
        },
        stringArray: {
          type: "array",
          items: { type: "string" },
          uniqueItems: true,
          default: []
        }
      },
      type: ["object", "boolean"],
      properties: {
        $id: {
          type: "string",
          format: "uri-reference"
        },
        $schema: {
          type: "string",
          format: "uri"
        },
        $ref: {
          type: "string",
          format: "uri-reference"
        },
        $comment: {
          type: "string"
        },
        title: {
          type: "string"
        },
        description: {
          type: "string"
        },
        default: true,
        readOnly: {
          type: "boolean",
          default: false
        },
        examples: {
          type: "array",
          items: true
        },
        multipleOf: {
          type: "number",
          exclusiveMinimum: 0
        },
        maximum: {
          type: "number"
        },
        exclusiveMaximum: {
          type: "number"
        },
        minimum: {
          type: "number"
        },
        exclusiveMinimum: {
          type: "number"
        },
        maxLength: { $ref: "#/definitions/nonNegativeInteger" },
        minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" },
        pattern: {
          type: "string",
          format: "regex"
        },
        additionalItems: { $ref: "#" },
        items: {
          anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }],
          default: true
        },
        maxItems: { $ref: "#/definitions/nonNegativeInteger" },
        minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" },
        uniqueItems: {
          type: "boolean",
          default: false
        },
        contains: { $ref: "#" },
        maxProperties: { $ref: "#/definitions/nonNegativeInteger" },
        minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" },
        required: { $ref: "#/definitions/stringArray" },
        additionalProperties: { $ref: "#" },
        definitions: {
          type: "object",
          additionalProperties: { $ref: "#" },
          default: {}
        },
        properties: {
          type: "object",
          additionalProperties: { $ref: "#" },
          default: {}
        },
        patternProperties: {
          type: "object",
          additionalProperties: { $ref: "#" },
          propertyNames: { format: "regex" },
          default: {}
        },
        dependencies: {
          type: "object",
          additionalProperties: {
            anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }]
          }
        },
        propertyNames: { $ref: "#" },
        const: true,
        enum: {
          type: "array",
          items: true,
          minItems: 1,
          uniqueItems: true
        },
        type: {
          anyOf: [
            { $ref: "#/definitions/simpleTypes" },
            {
              type: "array",
              items: { $ref: "#/definitions/simpleTypes" },
              minItems: 1,
              uniqueItems: true
            }
          ]
        },
        format: { type: "string" },
        contentMediaType: { type: "string" },
        contentEncoding: { type: "string" },
        if: { $ref: "#" },
        then: { $ref: "#" },
        else: { $ref: "#" },
        allOf: { $ref: "#/definitions/schemaArray" },
        anyOf: { $ref: "#/definitions/schemaArray" },
        oneOf: { $ref: "#/definitions/schemaArray" },
        not: { $ref: "#" }
      },
      default: true
    };
  }
});

// node_modules/ajv/dist/ajv.js
var require_ajv = __commonJS({
  "node_modules/ajv/dist/ajv.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MissingRefError = exports2.ValidationError = exports2.CodeGen = exports2.Name = exports2.nil = exports2.stringify = exports2.str = exports2._ = exports2.KeywordCxt = exports2.Ajv = void 0;
    var core_1 = require_core();
    var draft7_1 = require_draft7();
    var discriminator_1 = require_discriminator();
    var draft7MetaSchema = require_json_schema_draft_07();
    var META_SUPPORT_DATA = ["/properties"];
    var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
    var Ajv2 = class extends core_1.default {
      _addVocabularies() {
        super._addVocabularies();
        draft7_1.default.forEach((v) => this.addVocabulary(v));
        if (this.opts.discriminator)
          this.addKeyword(discriminator_1.default);
      }
      _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        if (!this.opts.meta)
          return;
        const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema;
        this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
      }
      defaultMeta() {
        return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0);
      }
    };
    exports2.Ajv = Ajv2;
    module2.exports = exports2 = Ajv2;
    module2.exports.Ajv = Ajv2;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.default = Ajv2;
    var validate_1 = require_validate();
    Object.defineProperty(exports2, "KeywordCxt", { enumerable: true, get: function() {
      return validate_1.KeywordCxt;
    } });
    var codegen_1 = require_codegen();
    Object.defineProperty(exports2, "_", { enumerable: true, get: function() {
      return codegen_1._;
    } });
    Object.defineProperty(exports2, "str", { enumerable: true, get: function() {
      return codegen_1.str;
    } });
    Object.defineProperty(exports2, "stringify", { enumerable: true, get: function() {
      return codegen_1.stringify;
    } });
    Object.defineProperty(exports2, "nil", { enumerable: true, get: function() {
      return codegen_1.nil;
    } });
    Object.defineProperty(exports2, "Name", { enumerable: true, get: function() {
      return codegen_1.Name;
    } });
    Object.defineProperty(exports2, "CodeGen", { enumerable: true, get: function() {
      return codegen_1.CodeGen;
    } });
    var validation_error_1 = require_validation_error();
    Object.defineProperty(exports2, "ValidationError", { enumerable: true, get: function() {
      return validation_error_1.default;
    } });
    var ref_error_1 = require_ref_error();
    Object.defineProperty(exports2, "MissingRefError", { enumerable: true, get: function() {
      return ref_error_1.default;
    } });
  }
});

// node_modules/ajv-formats/dist/formats.js
var require_formats2 = __commonJS({
  "node_modules/ajv-formats/dist/formats.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.formatNames = exports2.fastFormats = exports2.fullFormats = void 0;
    function fmtDef(validate, compare) {
      return { validate, compare };
    }
    exports2.fullFormats = {
      // date: http://tools.ietf.org/html/rfc3339#section-5.6
      date: fmtDef(date5, compareDate),
      // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
      time: fmtDef(getTime(true), compareTime),
      "date-time": fmtDef(getDateTime(true), compareDateTime),
      "iso-time": fmtDef(getTime(), compareIsoTime),
      "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime),
      // duration: https://tools.ietf.org/html/rfc3339#appendix-A
      duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,
      uri,
      "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,
      // uri-template: https://tools.ietf.org/html/rfc6570
      "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,
      // For the source: https://gist.github.com/dperini/729294
      // For test cases: https://mathiasbynens.be/demo/url-regex
      url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,
      email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
      hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,
      // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
      ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,
      ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,
      regex,
      // uuid: http://tools.ietf.org/html/rfc4122
      uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,
      // JSON-pointer: https://tools.ietf.org/html/rfc6901
      // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
      "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/,
      "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,
      // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
      "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,
      // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types
      // byte: https://github.com/miguelmota/is-base64
      byte,
      // signed 32 bit integer
      int32: { type: "number", validate: validateInt32 },
      // signed 64 bit integer
      int64: { type: "number", validate: validateInt64 },
      // C-type float
      float: { type: "number", validate: validateNumber },
      // C-type double
      double: { type: "number", validate: validateNumber },
      // hint to the UI to hide input strings
      password: true,
      // unchecked string payload
      binary: true
    };
    exports2.fastFormats = {
      ...exports2.fullFormats,
      date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate),
      time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime),
      "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime),
      "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime),
      "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime),
      // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
      uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
      "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
      // email (sources from jsen validator):
      // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
      // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation')
      email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i
    };
    exports2.formatNames = Object.keys(exports2.fullFormats);
    function isLeapYear(year) {
      return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
    }
    var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
    var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    function date5(str) {
      const matches = DATE.exec(str);
      if (!matches)
        return false;
      const year = +matches[1];
      const month = +matches[2];
      const day = +matches[3];
      return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]);
    }
    function compareDate(d1, d2) {
      if (!(d1 && d2))
        return void 0;
      if (d1 > d2)
        return 1;
      if (d1 < d2)
        return -1;
      return 0;
    }
    var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;
    function getTime(strictTimeZone) {
      return function time3(str) {
        const matches = TIME.exec(str);
        if (!matches)
          return false;
        const hr = +matches[1];
        const min = +matches[2];
        const sec = +matches[3];
        const tz = matches[4];
        const tzSign = matches[5] === "-" ? -1 : 1;
        const tzH = +(matches[6] || 0);
        const tzM = +(matches[7] || 0);
        if (tzH > 23 || tzM > 59 || strictTimeZone && !tz)
          return false;
        if (hr <= 23 && min <= 59 && sec < 60)
          return true;
        const utcMin = min - tzM * tzSign;
        const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0);
        return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61;
      };
    }
    function compareTime(s1, s2) {
      if (!(s1 && s2))
        return void 0;
      const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf();
      const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf();
      if (!(t1 && t2))
        return void 0;
      return t1 - t2;
    }
    function compareIsoTime(t1, t2) {
      if (!(t1 && t2))
        return void 0;
      const a1 = TIME.exec(t1);
      const a2 = TIME.exec(t2);
      if (!(a1 && a2))
        return void 0;
      t1 = a1[1] + a1[2] + a1[3];
      t2 = a2[1] + a2[2] + a2[3];
      if (t1 > t2)
        return 1;
      if (t1 < t2)
        return -1;
      return 0;
    }
    var DATE_TIME_SEPARATOR = /t|\s/i;
    function getDateTime(strictTimeZone) {
      const time3 = getTime(strictTimeZone);
      return function date_time(str) {
        const dateTime = str.split(DATE_TIME_SEPARATOR);
        return dateTime.length === 2 && date5(dateTime[0]) && time3(dateTime[1]);
      };
    }
    function compareDateTime(dt1, dt2) {
      if (!(dt1 && dt2))
        return void 0;
      const d1 = new Date(dt1).valueOf();
      const d2 = new Date(dt2).valueOf();
      if (!(d1 && d2))
        return void 0;
      return d1 - d2;
    }
    function compareIsoDateTime(dt1, dt2) {
      if (!(dt1 && dt2))
        return void 0;
      const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR);
      const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR);
      const res = compareDate(d1, d2);
      if (res === void 0)
        return void 0;
      return res || compareTime(t1, t2);
    }
    var NOT_URI_FRAGMENT = /\/|:/;
    var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
    function uri(str) {
      return NOT_URI_FRAGMENT.test(str) && URI.test(str);
    }
    var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;
    function byte(str) {
      BYTE.lastIndex = 0;
      return BYTE.test(str);
    }
    var MIN_INT32 = -(2 ** 31);
    var MAX_INT32 = 2 ** 31 - 1;
    function validateInt32(value) {
      return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32;
    }
    function validateInt64(value) {
      return Number.isInteger(value);
    }
    function validateNumber() {
      return true;
    }
    var Z_ANCHOR = /[^\\]\\Z/;
    function regex(str) {
      if (Z_ANCHOR.test(str))
        return false;
      try {
        new RegExp(str);
        return true;
      } catch (e2) {
        return false;
      }
    }
  }
});

// node_modules/ajv-formats/dist/limit.js
var require_limit = __commonJS({
  "node_modules/ajv-formats/dist/limit.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.formatLimitDefinition = void 0;
    var ajv_1 = require_ajv();
    var codegen_1 = require_codegen();
    var ops = codegen_1.operators;
    var KWDs = {
      formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
      formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
      formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
      formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }
    };
    var error51 = {
      message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`,
      params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`
    };
    exports2.formatLimitDefinition = {
      keyword: Object.keys(KWDs),
      type: "string",
      schemaType: "string",
      $data: true,
      error: error51,
      code(cxt) {
        const { gen, data, schemaCode, keyword, it } = cxt;
        const { opts, self: self2 } = it;
        if (!opts.validateFormats)
          return;
        const fCxt = new ajv_1.KeywordCxt(it, self2.RULES.all.format.definition, "format");
        if (fCxt.$data)
          validate$DataFormat();
        else
          validateFormat();
        function validate$DataFormat() {
          const fmts = gen.scopeValue("formats", {
            ref: self2.formats,
            code: opts.code.formats
          });
          const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`);
          cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt)));
        }
        function validateFormat() {
          const format = fCxt.schema;
          const fmtDef = self2.formats[format];
          if (!fmtDef || fmtDef === true)
            return;
          if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") {
            throw new Error(`"${keyword}": format "${format}" does not define "compare" function`);
          }
          const fmt = gen.scopeValue("formats", {
            key: format,
            ref: fmtDef,
            code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0
          });
          cxt.fail$data(compareCode(fmt));
        }
        function compareCode(fmt) {
          return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`;
        }
      },
      dependencies: ["format"]
    };
    var formatLimitPlugin = (ajv) => {
      ajv.addKeyword(exports2.formatLimitDefinition);
      return ajv;
    };
    exports2.default = formatLimitPlugin;
  }
});

// node_modules/ajv-formats/dist/index.js
var require_dist4 = __commonJS({
  "node_modules/ajv-formats/dist/index.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var formats_1 = require_formats2();
    var limit_1 = require_limit();
    var codegen_1 = require_codegen();
    var fullName = new codegen_1.Name("fullFormats");
    var fastName = new codegen_1.Name("fastFormats");
    var formatsPlugin = (ajv, opts = { keywords: true }) => {
      if (Array.isArray(opts)) {
        addFormats(ajv, opts, formats_1.fullFormats, fullName);
        return ajv;
      }
      const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];
      const list = opts.formats || formats_1.formatNames;
      addFormats(ajv, list, formats, exportName);
      if (opts.keywords)
        (0, limit_1.default)(ajv);
      return ajv;
    };
    formatsPlugin.get = (name, mode = "full") => {
      const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats;
      const f3 = formats[name];
      if (!f3)
        throw new Error(`Unknown format "${name}"`);
      return f3;
    };
    function addFormats(ajv, list, fs2, exportName) {
      var _a3;
      var _b;
      (_a3 = (_b = ajv.opts.code).formats) !== null && _a3 !== void 0 ? _a3 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
      for (const f3 of list)
        ajv.addFormat(f3, fs2[f3]);
    }
    module2.exports = exports2 = formatsPlugin;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.default = formatsPlugin;
  }
});

// node_modules/@kirbah/mcp-youtube/dist/index.js
var index_exports = {};
__export(index_exports, {
  runServer: () => runServer
});
module.exports = __toCommonJS(index_exports);

// node_modules/@kirbah/mcp-youtube/dist/utils/env.js
var import_node_fs = require("node:fs");
var import_node_path = require("node:path");
function loadEnv() {
  const envPath = (0, import_node_path.resolve)(process.cwd(), ".env");
  if ((0, import_node_fs.existsSync)(envPath)) {
    try {
      process.loadEnvFile(envPath);
    } catch (error51) {
      console.error("Failed to load .env file:", error51);
    }
  }
}

// node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
var import_node_process = __toESM(require("node:process"), 1);

// node_modules/zod/v4/classic/external.js
var external_exports = {};
__export(external_exports, {
  $brand: () => $brand,
  $input: () => $input,
  $output: () => $output,
  NEVER: () => NEVER,
  TimePrecision: () => TimePrecision,
  ZodAny: () => ZodAny,
  ZodArray: () => ZodArray,
  ZodBase64: () => ZodBase64,
  ZodBase64URL: () => ZodBase64URL,
  ZodBigInt: () => ZodBigInt,
  ZodBigIntFormat: () => ZodBigIntFormat,
  ZodBoolean: () => ZodBoolean,
  ZodCIDRv4: () => ZodCIDRv4,
  ZodCIDRv6: () => ZodCIDRv6,
  ZodCUID: () => ZodCUID,
  ZodCUID2: () => ZodCUID2,
  ZodCatch: () => ZodCatch,
  ZodCodec: () => ZodCodec,
  ZodCustom: () => ZodCustom,
  ZodCustomStringFormat: () => ZodCustomStringFormat,
  ZodDate: () => ZodDate,
  ZodDefault: () => ZodDefault,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
  ZodE164: () => ZodE164,
  ZodEmail: () => ZodEmail,
  ZodEmoji: () => ZodEmoji,
  ZodEnum: () => ZodEnum,
  ZodError: () => ZodError,
  ZodExactOptional: () => ZodExactOptional,
  ZodFile: () => ZodFile,
  ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
  ZodFunction: () => ZodFunction,
  ZodGUID: () => ZodGUID,
  ZodIPv4: () => ZodIPv4,
  ZodIPv6: () => ZodIPv6,
  ZodISODate: () => ZodISODate,
  ZodISODateTime: () => ZodISODateTime,
  ZodISODuration: () => ZodISODuration,
  ZodISOTime: () => ZodISOTime,
  ZodIntersection: () => ZodIntersection,
  ZodIssueCode: () => ZodIssueCode,
  ZodJWT: () => ZodJWT,
  ZodKSUID: () => ZodKSUID,
  ZodLazy: () => ZodLazy,
  ZodLiteral: () => ZodLiteral,
  ZodMAC: () => ZodMAC,
  ZodMap: () => ZodMap,
  ZodNaN: () => ZodNaN,
  ZodNanoID: () => ZodNanoID,
  ZodNever: () => ZodNever,
  ZodNonOptional: () => ZodNonOptional,
  ZodNull: () => ZodNull,
  ZodNullable: () => ZodNullable,
  ZodNumber: () => ZodNumber,
  ZodNumberFormat: () => ZodNumberFormat,
  ZodObject: () => ZodObject,
  ZodOptional: () => ZodOptional,
  ZodPipe: () => ZodPipe,
  ZodPrefault: () => ZodPrefault,
  ZodPreprocess: () => ZodPreprocess,
  ZodPromise: () => ZodPromise,
  ZodReadonly: () => ZodReadonly,
  ZodRealError: () => ZodRealError,
  ZodRecord: () => ZodRecord,
  ZodSet: () => ZodSet,
  ZodString: () => ZodString,
  ZodStringFormat: () => ZodStringFormat,
  ZodSuccess: () => ZodSuccess,
  ZodSymbol: () => ZodSymbol,
  ZodTemplateLiteral: () => ZodTemplateLiteral,
  ZodTransform: () => ZodTransform,
  ZodTuple: () => ZodTuple,
  ZodType: () => ZodType,
  ZodULID: () => ZodULID,
  ZodURL: () => ZodURL,
  ZodUUID: () => ZodUUID,
  ZodUndefined: () => ZodUndefined,
  ZodUnion: () => ZodUnion,
  ZodUnknown: () => ZodUnknown,
  ZodVoid: () => ZodVoid,
  ZodXID: () => ZodXID,
  ZodXor: () => ZodXor,
  _ZodString: () => _ZodString,
  _default: () => _default2,
  _function: () => _function,
  any: () => any,
  array: () => array,
  base64: () => base642,
  base64url: () => base64url2,
  bigint: () => bigint2,
  boolean: () => boolean2,
  catch: () => _catch2,
  check: () => check,
  cidrv4: () => cidrv42,
  cidrv6: () => cidrv62,
  clone: () => clone,
  codec: () => codec,
  coerce: () => coerce_exports,
  config: () => config,
  core: () => core_exports2,
  cuid: () => cuid3,
  cuid2: () => cuid22,
  custom: () => custom,
  date: () => date3,
  decode: () => decode2,
  decodeAsync: () => decodeAsync2,
  describe: () => describe2,
  discriminatedUnion: () => discriminatedUnion,
  e164: () => e1642,
  email: () => email2,
  emoji: () => emoji2,
  encode: () => encode2,
  encodeAsync: () => encodeAsync2,
  endsWith: () => _endsWith,
  enum: () => _enum2,
  exactOptional: () => exactOptional,
  file: () => file,
  flattenError: () => flattenError,
  float32: () => float32,
  float64: () => float64,
  formatError: () => formatError,
  fromJSONSchema: () => fromJSONSchema,
  function: () => _function,
  getErrorMap: () => getErrorMap,
  globalRegistry: () => globalRegistry,
  gt: () => _gt,
  gte: () => _gte,
  guid: () => guid2,
  hash: () => hash,
  hex: () => hex2,
  hostname: () => hostname2,
  httpUrl: () => httpUrl,
  includes: () => _includes,
  instanceof: () => _instanceof,
  int: () => int,
  int32: () => int32,
  int64: () => int64,
  intersection: () => intersection,
  invertCodec: () => invertCodec,
  ipv4: () => ipv42,
  ipv6: () => ipv62,
  iso: () => iso_exports,
  json: () => json,
  jwt: () => jwt,
  keyof: () => keyof,
  ksuid: () => ksuid2,
  lazy: () => lazy,
  length: () => _length,
  literal: () => literal,
  locales: () => locales_exports,
  looseObject: () => looseObject,
  looseRecord: () => looseRecord,
  lowercase: () => _lowercase,
  lt: () => _lt,
  lte: () => _lte,
  mac: () => mac2,
  map: () => map,
  maxLength: () => _maxLength,
  maxSize: () => _maxSize,
  meta: () => meta2,
  mime: () => _mime,
  minLength: () => _minLength,
  minSize: () => _minSize,
  multipleOf: () => _multipleOf,
  nan: () => nan,
  nanoid: () => nanoid2,
  nativeEnum: () => nativeEnum,
  negative: () => _negative,
  never: () => never,
  nonnegative: () => _nonnegative,
  nonoptional: () => nonoptional,
  nonpositive: () => _nonpositive,
  normalize: () => _normalize,
  null: () => _null3,
  nullable: () => nullable,
  nullish: () => nullish2,
  number: () => number2,
  object: () => object,
  optional: () => optional,
  overwrite: () => _overwrite,
  parse: () => parse2,
  parseAsync: () => parseAsync2,
  partialRecord: () => partialRecord,
  pipe: () => pipe,
  positive: () => _positive,
  prefault: () => prefault,
  preprocess: () => preprocess,
  prettifyError: () => prettifyError,
  promise: () => promise,
  property: () => _property,
  readonly: () => readonly,
  record: () => record,
  refine: () => refine,
  regex: () => _regex,
  regexes: () => regexes_exports,
  registry: () => registry,
  safeDecode: () => safeDecode2,
  safeDecodeAsync: () => safeDecodeAsync2,
  safeEncode: () => safeEncode2,
  safeEncodeAsync: () => safeEncodeAsync2,
  safeParse: () => safeParse2,
  safeParseAsync: () => safeParseAsync2,
  set: () => set,
  setErrorMap: () => setErrorMap,
  size: () => _size,
  slugify: () => _slugify,
  startsWith: () => _startsWith,
  strictObject: () => strictObject,
  string: () => string2,
  stringFormat: () => stringFormat,
  stringbool: () => stringbool,
  success: () => success,
  superRefine: () => superRefine,
  symbol: () => symbol,
  templateLiteral: () => templateLiteral,
  toJSONSchema: () => toJSONSchema,
  toLowerCase: () => _toLowerCase,
  toUpperCase: () => _toUpperCase,
  transform: () => transform,
  treeifyError: () => treeifyError,
  trim: () => _trim,
  tuple: () => tuple,
  uint32: () => uint32,
  uint64: () => uint64,
  ulid: () => ulid2,
  undefined: () => _undefined3,
  union: () => union,
  unknown: () => unknown,
  uppercase: () => _uppercase,
  url: () => url,
  util: () => util_exports,
  uuid: () => uuid2,
  uuidv4: () => uuidv4,
  uuidv6: () => uuidv6,
  uuidv7: () => uuidv7,
  void: () => _void2,
  xid: () => xid2,
  xor: () => xor
});

// node_modules/zod/v4/core/index.js
var core_exports2 = {};
__export(core_exports2, {
  $ZodAny: () => $ZodAny,
  $ZodArray: () => $ZodArray,
  $ZodAsyncError: () => $ZodAsyncError,
  $ZodBase64: () => $ZodBase64,
  $ZodBase64URL: () => $ZodBase64URL,
  $ZodBigInt: () => $ZodBigInt,
  $ZodBigIntFormat: () => $ZodBigIntFormat,
  $ZodBoolean: () => $ZodBoolean,
  $ZodCIDRv4: () => $ZodCIDRv4,
  $ZodCIDRv6: () => $ZodCIDRv6,
  $ZodCUID: () => $ZodCUID,
  $ZodCUID2: () => $ZodCUID2,
  $ZodCatch: () => $ZodCatch,
  $ZodCheck: () => $ZodCheck,
  $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat,
  $ZodCheckEndsWith: () => $ZodCheckEndsWith,
  $ZodCheckGreaterThan: () => $ZodCheckGreaterThan,
  $ZodCheckIncludes: () => $ZodCheckIncludes,
  $ZodCheckLengthEquals: () => $ZodCheckLengthEquals,
  $ZodCheckLessThan: () => $ZodCheckLessThan,
  $ZodCheckLowerCase: () => $ZodCheckLowerCase,
  $ZodCheckMaxLength: () => $ZodCheckMaxLength,
  $ZodCheckMaxSize: () => $ZodCheckMaxSize,
  $ZodCheckMimeType: () => $ZodCheckMimeType,
  $ZodCheckMinLength: () => $ZodCheckMinLength,
  $ZodCheckMinSize: () => $ZodCheckMinSize,
  $ZodCheckMultipleOf: () => $ZodCheckMultipleOf,
  $ZodCheckNumberFormat: () => $ZodCheckNumberFormat,
  $ZodCheckOverwrite: () => $ZodCheckOverwrite,
  $ZodCheckProperty: () => $ZodCheckProperty,
  $ZodCheckRegex: () => $ZodCheckRegex,
  $ZodCheckSizeEquals: () => $ZodCheckSizeEquals,
  $ZodCheckStartsWith: () => $ZodCheckStartsWith,
  $ZodCheckStringFormat: () => $ZodCheckStringFormat,
  $ZodCheckUpperCase: () => $ZodCheckUpperCase,
  $ZodCodec: () => $ZodCodec,
  $ZodCustom: () => $ZodCustom,
  $ZodCustomStringFormat: () => $ZodCustomStringFormat,
  $ZodDate: () => $ZodDate,
  $ZodDefault: () => $ZodDefault,
  $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion,
  $ZodE164: () => $ZodE164,
  $ZodEmail: () => $ZodEmail,
  $ZodEmoji: () => $ZodEmoji,
  $ZodEncodeError: () => $ZodEncodeError,
  $ZodEnum: () => $ZodEnum,
  $ZodError: () => $ZodError,
  $ZodExactOptional: () => $ZodExactOptional,
  $ZodFile: () => $ZodFile,
  $ZodFunction: () => $ZodFunction,
  $ZodGUID: () => $ZodGUID,
  $ZodIPv4: () => $ZodIPv4,
  $ZodIPv6: () => $ZodIPv6,
  $ZodISODate: () => $ZodISODate,
  $ZodISODateTime: () => $ZodISODateTime,
  $ZodISODuration: () => $ZodISODuration,
  $ZodISOTime: () => $ZodISOTime,
  $ZodIntersection: () => $ZodIntersection,
  $ZodJWT: () => $ZodJWT,
  $ZodKSUID: () => $ZodKSUID,
  $ZodLazy: () => $ZodLazy,
  $ZodLiteral: () => $ZodLiteral,
  $ZodMAC: () => $ZodMAC,
  $ZodMap: () => $ZodMap,
  $ZodNaN: () => $ZodNaN,
  $ZodNanoID: () => $ZodNanoID,
  $ZodNever: () => $ZodNever,
  $ZodNonOptional: () => $ZodNonOptional,
  $ZodNull: () => $ZodNull,
  $ZodNullable: () => $ZodNullable,
  $ZodNumber: () => $ZodNumber,
  $ZodNumberFormat: () => $ZodNumberFormat,
  $ZodObject: () => $ZodObject,
  $ZodObjectJIT: () => $ZodObjectJIT,
  $ZodOptional: () => $ZodOptional,
  $ZodPipe: () => $ZodPipe,
  $ZodPrefault: () => $ZodPrefault,
  $ZodPreprocess: () => $ZodPreprocess,
  $ZodPromise: () => $ZodPromise,
  $ZodReadonly: () => $ZodReadonly,
  $ZodRealError: () => $ZodRealError,
  $ZodRecord: () => $ZodRecord,
  $ZodRegistry: () => $ZodRegistry,
  $ZodSet: () => $ZodSet,
  $ZodString: () => $ZodString,
  $ZodStringFormat: () => $ZodStringFormat,
  $ZodSuccess: () => $ZodSuccess,
  $ZodSymbol: () => $ZodSymbol,
  $ZodTemplateLiteral: () => $ZodTemplateLiteral,
  $ZodTransform: () => $ZodTransform,
  $ZodTuple: () => $ZodTuple,
  $ZodType: () => $ZodType,
  $ZodULID: () => $ZodULID,
  $ZodURL: () => $ZodURL,
  $ZodUUID: () => $ZodUUID,
  $ZodUndefined: () => $ZodUndefined,
  $ZodUnion: () => $ZodUnion,
  $ZodUnknown: () => $ZodUnknown,
  $ZodVoid: () => $ZodVoid,
  $ZodXID: () => $ZodXID,
  $ZodXor: () => $ZodXor,
  $brand: () => $brand,
  $constructor: () => $constructor,
  $input: () => $input,
  $output: () => $output,
  Doc: () => Doc,
  JSONSchema: () => json_schema_exports,
  JSONSchemaGenerator: () => JSONSchemaGenerator,
  NEVER: () => NEVER,
  TimePrecision: () => TimePrecision,
  _any: () => _any,
  _array: () => _array,
  _base64: () => _base64,
  _base64url: () => _base64url,
  _bigint: () => _bigint,
  _boolean: () => _boolean,
  _catch: () => _catch,
  _check: () => _check,
  _cidrv4: () => _cidrv4,
  _cidrv6: () => _cidrv6,
  _coercedBigint: () => _coercedBigint,
  _coercedBoolean: () => _coercedBoolean,
  _coercedDate: () => _coercedDate,
  _coercedNumber: () => _coercedNumber,
  _coercedString: () => _coercedString,
  _cuid: () => _cuid,
  _cuid2: () => _cuid2,
  _custom: () => _custom,
  _date: () => _date,
  _decode: () => _decode,
  _decodeAsync: () => _decodeAsync,
  _default: () => _default,
  _discriminatedUnion: () => _discriminatedUnion,
  _e164: () => _e164,
  _email: () => _email,
  _emoji: () => _emoji2,
  _encode: () => _encode,
  _encodeAsync: () => _encodeAsync,
  _endsWith: () => _endsWith,
  _enum: () => _enum,
  _file: () => _file,
  _float32: () => _float32,
  _float64: () => _float64,
  _gt: () => _gt,
  _gte: () => _gte,
  _guid: () => _guid,
  _includes: () => _includes,
  _int: () => _int,
  _int32: () => _int32,
  _int64: () => _int64,
  _intersection: () => _intersection,
  _ipv4: () => _ipv4,
  _ipv6: () => _ipv6,
  _isoDate: () => _isoDate,
  _isoDateTime: () => _isoDateTime,
  _isoDuration: () => _isoDuration,
  _isoTime: () => _isoTime,
  _jwt: () => _jwt,
  _ksuid: () => _ksuid,
  _lazy: () => _lazy,
  _length: () => _length,
  _literal: () => _literal,
  _lowercase: () => _lowercase,
  _lt: () => _lt,
  _lte: () => _lte,
  _mac: () => _mac,
  _map: () => _map,
  _max: () => _lte,
  _maxLength: () => _maxLength,
  _maxSize: () => _maxSize,
  _mime: () => _mime,
  _min: () => _gte,
  _minLength: () => _minLength,
  _minSize: () => _minSize,
  _multipleOf: () => _multipleOf,
  _nan: () => _nan,
  _nanoid: () => _nanoid,
  _nativeEnum: () => _nativeEnum,
  _negative: () => _negative,
  _never: () => _never,
  _nonnegative: () => _nonnegative,
  _nonoptional: () => _nonoptional,
  _nonpositive: () => _nonpositive,
  _normalize: () => _normalize,
  _null: () => _null2,
  _nullable: () => _nullable,
  _number: () => _number,
  _optional: () => _optional,
  _overwrite: () => _overwrite,
  _parse: () => _parse,
  _parseAsync: () => _parseAsync,
  _pipe: () => _pipe,
  _positive: () => _positive,
  _promise: () => _promise,
  _property: () => _property,
  _readonly: () => _readonly,
  _record: () => _record,
  _refine: () => _refine,
  _regex: () => _regex,
  _safeDecode: () => _safeDecode,
  _safeDecodeAsync: () => _safeDecodeAsync,
  _safeEncode: () => _safeEncode,
  _safeEncodeAsync: () => _safeEncodeAsync,
  _safeParse: () => _safeParse,
  _safeParseAsync: () => _safeParseAsync,
  _set: () => _set,
  _size: () => _size,
  _slugify: () => _slugify,
  _startsWith: () => _startsWith,
  _string: () => _string,
  _stringFormat: () => _stringFormat,
  _stringbool: () => _stringbool,
  _success: () => _success,
  _superRefine: () => _superRefine,
  _symbol: () => _symbol,
  _templateLiteral: () => _templateLiteral,
  _toLowerCase: () => _toLowerCase,
  _toUpperCase: () => _toUpperCase,
  _transform: () => _transform,
  _trim: () => _trim,
  _tuple: () => _tuple,
  _uint32: () => _uint32,
  _uint64: () => _uint64,
  _ulid: () => _ulid,
  _undefined: () => _undefined2,
  _union: () => _union,
  _unknown: () => _unknown,
  _uppercase: () => _uppercase,
  _url: () => _url,
  _uuid: () => _uuid,
  _uuidv4: () => _uuidv4,
  _uuidv6: () => _uuidv6,
  _uuidv7: () => _uuidv7,
  _void: () => _void,
  _xid: () => _xid,
  _xor: () => _xor,
  clone: () => clone,
  config: () => config,
  createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod,
  createToJSONSchemaMethod: () => createToJSONSchemaMethod,
  decode: () => decode,
  decodeAsync: () => decodeAsync,
  describe: () => describe,
  encode: () => encode,
  encodeAsync: () => encodeAsync,
  extractDefs: () => extractDefs,
  finalize: () => finalize,
  flattenError: () => flattenError,
  formatError: () => formatError,
  globalConfig: () => globalConfig,
  globalRegistry: () => globalRegistry,
  initializeContext: () => initializeContext,
  isValidBase64: () => isValidBase64,
  isValidBase64URL: () => isValidBase64URL,
  isValidJWT: () => isValidJWT,
  locales: () => locales_exports,
  meta: () => meta,
  parse: () => parse,
  parseAsync: () => parseAsync,
  prettifyError: () => prettifyError,
  process: () => process2,
  regexes: () => regexes_exports,
  registry: () => registry,
  safeDecode: () => safeDecode,
  safeDecodeAsync: () => safeDecodeAsync,
  safeEncode: () => safeEncode,
  safeEncodeAsync: () => safeEncodeAsync,
  safeParse: () => safeParse,
  safeParseAsync: () => safeParseAsync,
  toDotPath: () => toDotPath,
  toJSONSchema: () => toJSONSchema,
  treeifyError: () => treeifyError,
  util: () => util_exports,
  version: () => version
});

// node_modules/zod/v4/core/core.js
var _a;
var NEVER = /* @__PURE__ */ Object.freeze({
  status: "aborted"
});
// @__NO_SIDE_EFFECTS__
function $constructor(name, initializer3, params) {
  function init(inst, def) {
    if (!inst._zod) {
      Object.defineProperty(inst, "_zod", {
        value: {
          def,
          constr: _,
          traits: /* @__PURE__ */ new Set()
        },
        enumerable: false
      });
    }
    if (inst._zod.traits.has(name)) {
      return;
    }
    inst._zod.traits.add(name);
    initializer3(inst, def);
    const proto = _.prototype;
    const keys = Object.keys(proto);
    for (let i2 = 0; i2 < keys.length; i2++) {
      const k = keys[i2];
      if (!(k in inst)) {
        inst[k] = proto[k].bind(inst);
      }
    }
  }
  const Parent = params?.Parent ?? Object;
  class Definition extends Parent {
  }
  Object.defineProperty(Definition, "name", { value: name });
  function _(def) {
    var _a3;
    const inst = params?.Parent ? new Definition() : this;
    init(inst, def);
    (_a3 = inst._zod).deferred ?? (_a3.deferred = []);
    for (const fn of inst._zod.deferred) {
      fn();
    }
    return inst;
  }
  Object.defineProperty(_, "init", { value: init });
  Object.defineProperty(_, Symbol.hasInstance, {
    value: (inst) => {
      if (params?.Parent && inst instanceof params.Parent)
        return true;
      return inst?._zod?.traits?.has(name);
    }
  });
  Object.defineProperty(_, "name", { value: name });
  return _;
}
var $brand = /* @__PURE__ */ Symbol("zod_brand");
var $ZodAsyncError = class extends Error {
  constructor() {
    super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
  }
};
var $ZodEncodeError = class extends Error {
  constructor(name) {
    super(`Encountered unidirectional transform during encode: ${name}`);
    this.name = "ZodEncodeError";
  }
};
(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});
var globalConfig = globalThis.__zod_globalConfig;
function config(newConfig) {
  if (newConfig)
    Object.assign(globalConfig, newConfig);
  return globalConfig;
}

// node_modules/zod/v4/core/util.js
var util_exports = {};
__export(util_exports, {
  BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES,
  Class: () => Class,
  NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES,
  aborted: () => aborted,
  allowsEval: () => allowsEval,
  assert: () => assert,
  assertEqual: () => assertEqual,
  assertIs: () => assertIs,
  assertNever: () => assertNever,
  assertNotEqual: () => assertNotEqual,
  assignProp: () => assignProp,
  base64ToUint8Array: () => base64ToUint8Array,
  base64urlToUint8Array: () => base64urlToUint8Array,
  cached: () => cached,
  captureStackTrace: () => captureStackTrace,
  cleanEnum: () => cleanEnum,
  cleanRegex: () => cleanRegex,
  clone: () => clone,
  cloneDef: () => cloneDef,
  createTransparentProxy: () => createTransparentProxy,
  defineLazy: () => defineLazy,
  esc: () => esc,
  escapeRegex: () => escapeRegex,
  explicitlyAborted: () => explicitlyAborted,
  extend: () => extend,
  finalizeIssue: () => finalizeIssue,
  floatSafeRemainder: () => floatSafeRemainder,
  getElementAtPath: () => getElementAtPath,
  getEnumValues: () => getEnumValues,
  getLengthableOrigin: () => getLengthableOrigin,
  getParsedType: () => getParsedType,
  getSizableOrigin: () => getSizableOrigin,
  hexToUint8Array: () => hexToUint8Array,
  isObject: () => isObject,
  isPlainObject: () => isPlainObject,
  issue: () => issue,
  joinValues: () => joinValues,
  jsonStringifyReplacer: () => jsonStringifyReplacer,
  merge: () => merge,
  mergeDefs: () => mergeDefs,
  normalizeParams: () => normalizeParams,
  nullish: () => nullish,
  numKeys: () => numKeys,
  objectClone: () => objectClone,
  omit: () => omit,
  optionalKeys: () => optionalKeys,
  parsedType: () => parsedType,
  partial: () => partial,
  pick: () => pick,
  prefixIssues: () => prefixIssues,
  primitiveTypes: () => primitiveTypes,
  promiseAllObject: () => promiseAllObject,
  propertyKeyTypes: () => propertyKeyTypes,
  randomString: () => randomString,
  required: () => required,
  safeExtend: () => safeExtend,
  shallowClone: () => shallowClone,
  slugify: () => slugify,
  stringifyPrimitive: () => stringifyPrimitive,
  uint8ArrayToBase64: () => uint8ArrayToBase64,
  uint8ArrayToBase64url: () => uint8ArrayToBase64url,
  uint8ArrayToHex: () => uint8ArrayToHex,
  unwrapMessage: () => unwrapMessage
});
function assertEqual(val) {
  return val;
}
function assertNotEqual(val) {
  return val;
}
function assertIs(_arg) {
}
function assertNever(_x) {
  throw new Error("Unexpected value in exhaustive check");
}
function assert(_) {
}
function getEnumValues(entries) {
  const numericValues = Object.values(entries).filter((v) => typeof v === "number");
  const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
  return values;
}
function joinValues(array2, separator = "|") {
  return array2.map((val) => stringifyPrimitive(val)).join(separator);
}
function jsonStringifyReplacer(_, value) {
  if (typeof value === "bigint")
    return value.toString();
  return value;
}
function cached(getter) {
  const set2 = false;
  return {
    get value() {
      if (!set2) {
        const value = getter();
        Object.defineProperty(this, "value", { value });
        return value;
      }
      throw new Error("cached value already set");
    }
  };
}
function nullish(input) {
  return input === null || input === void 0;
}
function cleanRegex(source) {
  const start = source.startsWith("^") ? 1 : 0;
  const end = source.endsWith("$") ? source.length - 1 : source.length;
  return source.slice(start, end);
}
function floatSafeRemainder(val, step) {
  const ratio = val / step;
  const roundedRatio = Math.round(ratio);
  const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);
  if (Math.abs(ratio - roundedRatio) < tolerance)
    return 0;
  return ratio - roundedRatio;
}
var EVALUATING = /* @__PURE__ */ Symbol("evaluating");
function defineLazy(object3, key, getter) {
  let value = void 0;
  Object.defineProperty(object3, key, {
    get() {
      if (value === EVALUATING) {
        return void 0;
      }
      if (value === void 0) {
        value = EVALUATING;
        value = getter();
      }
      return value;
    },
    set(v) {
      Object.defineProperty(object3, key, {
        value: v
        // configurable: true,
      });
    },
    configurable: true
  });
}
function objectClone(obj) {
  return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
}
function assignProp(target, prop, value) {
  Object.defineProperty(target, prop, {
    value,
    writable: true,
    enumerable: true,
    configurable: true
  });
}
function mergeDefs(...defs) {
  const mergedDescriptors = {};
  for (const def of defs) {
    const descriptors = Object.getOwnPropertyDescriptors(def);
    Object.assign(mergedDescriptors, descriptors);
  }
  return Object.defineProperties({}, mergedDescriptors);
}
function cloneDef(schema) {
  return mergeDefs(schema._zod.def);
}
function getElementAtPath(obj, path) {
  if (!path)
    return obj;
  return path.reduce((acc, key) => acc?.[key], obj);
}
function promiseAllObject(promisesObj) {
  const keys = Object.keys(promisesObj);
  const promises = keys.map((key) => promisesObj[key]);
  return Promise.all(promises).then((results) => {
    const resolvedObj = {};
    for (let i2 = 0; i2 < keys.length; i2++) {
      resolvedObj[keys[i2]] = results[i2];
    }
    return resolvedObj;
  });
}
function randomString(length = 10) {
  const chars = "abcdefghijklmnopqrstuvwxyz";
  let str = "";
  for (let i2 = 0; i2 < length; i2++) {
    str += chars[Math.floor(Math.random() * chars.length)];
  }
  return str;
}
function esc(str) {
  return JSON.stringify(str);
}
function slugify(input) {
  return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
}
var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {
};
function isObject(data) {
  return typeof data === "object" && data !== null && !Array.isArray(data);
}
var allowsEval = /* @__PURE__ */ cached(() => {
  if (globalConfig.jitless) {
    return false;
  }
  if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
    return false;
  }
  try {
    const F2 = Function;
    new F2("");
    return true;
  } catch (_) {
    return false;
  }
});
function isPlainObject(o) {
  if (isObject(o) === false)
    return false;
  const ctor = o.constructor;
  if (ctor === void 0)
    return true;
  if (typeof ctor !== "function")
    return true;
  const prot = ctor.prototype;
  if (isObject(prot) === false)
    return false;
  if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
    return false;
  }
  return true;
}
function shallowClone(o) {
  if (isPlainObject(o))
    return { ...o };
  if (Array.isArray(o))
    return [...o];
  if (o instanceof Map)
    return new Map(o);
  if (o instanceof Set)
    return new Set(o);
  return o;
}
function numKeys(data) {
  let keyCount = 0;
  for (const key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      keyCount++;
    }
  }
  return keyCount;
}
var getParsedType = (data) => {
  const t2 = typeof data;
  switch (t2) {
    case "undefined":
      return "undefined";
    case "string":
      return "string";
    case "number":
      return Number.isNaN(data) ? "nan" : "number";
    case "boolean":
      return "boolean";
    case "function":
      return "function";
    case "bigint":
      return "bigint";
    case "symbol":
      return "symbol";
    case "object":
      if (Array.isArray(data)) {
        return "array";
      }
      if (data === null) {
        return "null";
      }
      if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
        return "promise";
      }
      if (typeof Map !== "undefined" && data instanceof Map) {
        return "map";
      }
      if (typeof Set !== "undefined" && data instanceof Set) {
        return "set";
      }
      if (typeof Date !== "undefined" && data instanceof Date) {
        return "date";
      }
      if (typeof File !== "undefined" && data instanceof File) {
        return "file";
      }
      return "object";
    default:
      throw new Error(`Unknown data type: ${t2}`);
  }
};
var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]);
var primitiveTypes = /* @__PURE__ */ new Set([
  "string",
  "number",
  "bigint",
  "boolean",
  "symbol",
  "undefined"
]);
function escapeRegex(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function clone(inst, def, params) {
  const cl = new inst._zod.constr(def ?? inst._zod.def);
  if (!def || params?.parent)
    cl._zod.parent = inst;
  return cl;
}
function normalizeParams(_params) {
  const params = _params;
  if (!params)
    return {};
  if (typeof params === "string")
    return { error: () => params };
  if (params?.message !== void 0) {
    if (params?.error !== void 0)
      throw new Error("Cannot specify both `message` and `error` params");
    params.error = params.message;
  }
  delete params.message;
  if (typeof params.error === "string")
    return { ...params, error: () => params.error };
  return params;
}
function createTransparentProxy(getter) {
  let target;
  return new Proxy({}, {
    get(_, prop, receiver) {
      target ?? (target = getter());
      return Reflect.get(target, prop, receiver);
    },
    set(_, prop, value, receiver) {
      target ?? (target = getter());
      return Reflect.set(target, prop, value, receiver);
    },
    has(_, prop) {
      target ?? (target = getter());
      return Reflect.has(target, prop);
    },
    deleteProperty(_, prop) {
      target ?? (target = getter());
      return Reflect.deleteProperty(target, prop);
    },
    ownKeys(_) {
      target ?? (target = getter());
      return Reflect.ownKeys(target);
    },
    getOwnPropertyDescriptor(_, prop) {
      target ?? (target = getter());
      return Reflect.getOwnPropertyDescriptor(target, prop);
    },
    defineProperty(_, prop, descriptor) {
      target ?? (target = getter());
      return Reflect.defineProperty(target, prop, descriptor);
    }
  });
}
function stringifyPrimitive(value) {
  if (typeof value === "bigint")
    return value.toString() + "n";
  if (typeof value === "string")
    return `"${value}"`;
  return `${value}`;
}
function optionalKeys(shape) {
  return Object.keys(shape).filter((k) => {
    return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
  });
}
var NUMBER_FORMAT_RANGES = {
  safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
  int32: [-2147483648, 2147483647],
  uint32: [0, 4294967295],
  float32: [-34028234663852886e22, 34028234663852886e22],
  float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
};
var BIGINT_FORMAT_RANGES = {
  int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")],
  uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")]
};
function pick(schema, mask) {
  const currDef = schema._zod.def;
  const checks = currDef.checks;
  const hasChecks = checks && checks.length > 0;
  if (hasChecks) {
    throw new Error(".pick() cannot be used on object schemas containing refinements");
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const newShape = {};
      for (const key in mask) {
        if (!(key in currDef.shape)) {
          throw new Error(`Unrecognized key: "${key}"`);
        }
        if (!mask[key])
          continue;
        newShape[key] = currDef.shape[key];
      }
      assignProp(this, "shape", newShape);
      return newShape;
    },
    checks: []
  });
  return clone(schema, def);
}
function omit(schema, mask) {
  const currDef = schema._zod.def;
  const checks = currDef.checks;
  const hasChecks = checks && checks.length > 0;
  if (hasChecks) {
    throw new Error(".omit() cannot be used on object schemas containing refinements");
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const newShape = { ...schema._zod.def.shape };
      for (const key in mask) {
        if (!(key in currDef.shape)) {
          throw new Error(`Unrecognized key: "${key}"`);
        }
        if (!mask[key])
          continue;
        delete newShape[key];
      }
      assignProp(this, "shape", newShape);
      return newShape;
    },
    checks: []
  });
  return clone(schema, def);
}
function extend(schema, shape) {
  if (!isPlainObject(shape)) {
    throw new Error("Invalid input to extend: expected a plain object");
  }
  const checks = schema._zod.def.checks;
  const hasChecks = checks && checks.length > 0;
  if (hasChecks) {
    const existingShape = schema._zod.def.shape;
    for (const key in shape) {
      if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) {
        throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
      }
    }
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const _shape = { ...schema._zod.def.shape, ...shape };
      assignProp(this, "shape", _shape);
      return _shape;
    }
  });
  return clone(schema, def);
}
function safeExtend(schema, shape) {
  if (!isPlainObject(shape)) {
    throw new Error("Invalid input to safeExtend: expected a plain object");
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const _shape = { ...schema._zod.def.shape, ...shape };
      assignProp(this, "shape", _shape);
      return _shape;
    }
  });
  return clone(schema, def);
}
function merge(a, b) {
  if (a._zod.def.checks?.length) {
    throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
  }
  const def = mergeDefs(a._zod.def, {
    get shape() {
      const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
      assignProp(this, "shape", _shape);
      return _shape;
    },
    get catchall() {
      return b._zod.def.catchall;
    },
    checks: b._zod.def.checks ?? []
  });
  return clone(a, def);
}
function partial(Class2, schema, mask) {
  const currDef = schema._zod.def;
  const checks = currDef.checks;
  const hasChecks = checks && checks.length > 0;
  if (hasChecks) {
    throw new Error(".partial() cannot be used on object schemas containing refinements");
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const oldShape = schema._zod.def.shape;
      const shape = { ...oldShape };
      if (mask) {
        for (const key in mask) {
          if (!(key in oldShape)) {
            throw new Error(`Unrecognized key: "${key}"`);
          }
          if (!mask[key])
            continue;
          shape[key] = Class2 ? new Class2({
            type: "optional",
            innerType: oldShape[key]
          }) : oldShape[key];
        }
      } else {
        for (const key in oldShape) {
          shape[key] = Class2 ? new Class2({
            type: "optional",
            innerType: oldShape[key]
          }) : oldShape[key];
        }
      }
      assignProp(this, "shape", shape);
      return shape;
    },
    checks: []
  });
  return clone(schema, def);
}
function required(Class2, schema, mask) {
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const oldShape = schema._zod.def.shape;
      const shape = { ...oldShape };
      if (mask) {
        for (const key in mask) {
          if (!(key in shape)) {
            throw new Error(`Unrecognized key: "${key}"`);
          }
          if (!mask[key])
            continue;
          shape[key] = new Class2({
            type: "nonoptional",
            innerType: oldShape[key]
          });
        }
      } else {
        for (const key in oldShape) {
          shape[key] = new Class2({
            type: "nonoptional",
            innerType: oldShape[key]
          });
        }
      }
      assignProp(this, "shape", shape);
      return shape;
    }
  });
  return clone(schema, def);
}
function aborted(x2, startIndex = 0) {
  if (x2.aborted === true)
    return true;
  for (let i2 = startIndex; i2 < x2.issues.length; i2++) {
    if (x2.issues[i2]?.continue !== true) {
      return true;
    }
  }
  return false;
}
function explicitlyAborted(x2, startIndex = 0) {
  if (x2.aborted === true)
    return true;
  for (let i2 = startIndex; i2 < x2.issues.length; i2++) {
    if (x2.issues[i2]?.continue === false) {
      return true;
    }
  }
  return false;
}
function prefixIssues(path, issues) {
  return issues.map((iss) => {
    var _a3;
    (_a3 = iss).path ?? (_a3.path = []);
    iss.path.unshift(path);
    return iss;
  });
}
function unwrapMessage(message) {
  return typeof message === "string" ? message : message?.message;
}
function finalizeIssue(iss, ctx, config2) {
  const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
  const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;
  rest.path ?? (rest.path = []);
  rest.message = message;
  if (ctx?.reportInput) {
    rest.input = _input;
  }
  return rest;
}
function getSizableOrigin(input) {
  if (input instanceof Set)
    return "set";
  if (input instanceof Map)
    return "map";
  if (input instanceof File)
    return "file";
  return "unknown";
}
function getLengthableOrigin(input) {
  if (Array.isArray(input))
    return "array";
  if (typeof input === "string")
    return "string";
  return "unknown";
}
function parsedType(data) {
  const t2 = typeof data;
  switch (t2) {
    case "number": {
      return Number.isNaN(data) ? "nan" : "number";
    }
    case "object": {
      if (data === null) {
        return "null";
      }
      if (Array.isArray(data)) {
        return "array";
      }
      const obj = data;
      if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) {
        return obj.constructor.name;
      }
    }
  }
  return t2;
}
function issue(...args) {
  const [iss, input, inst] = args;
  if (typeof iss === "string") {
    return {
      message: iss,
      code: "custom",
      input,
      inst
    };
  }
  return { ...iss };
}
function cleanEnum(obj) {
  return Object.entries(obj).filter(([k, _]) => {
    return Number.isNaN(Number.parseInt(k, 10));
  }).map((el) => el[1]);
}
function base64ToUint8Array(base643) {
  const binaryString = atob(base643);
  const bytes = new Uint8Array(binaryString.length);
  for (let i2 = 0; i2 < binaryString.length; i2++) {
    bytes[i2] = binaryString.charCodeAt(i2);
  }
  return bytes;
}
function uint8ArrayToBase64(bytes) {
  let binaryString = "";
  for (let i2 = 0; i2 < bytes.length; i2++) {
    binaryString += String.fromCharCode(bytes[i2]);
  }
  return btoa(binaryString);
}
function base64urlToUint8Array(base64url3) {
  const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
  const padding = "=".repeat((4 - base643.length % 4) % 4);
  return base64ToUint8Array(base643 + padding);
}
function uint8ArrayToBase64url(bytes) {
  return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
function hexToUint8Array(hex3) {
  const cleanHex = hex3.replace(/^0x/, "");
  if (cleanHex.length % 2 !== 0) {
    throw new Error("Invalid hex string length");
  }
  const bytes = new Uint8Array(cleanHex.length / 2);
  for (let i2 = 0; i2 < cleanHex.length; i2 += 2) {
    bytes[i2 / 2] = Number.parseInt(cleanHex.slice(i2, i2 + 2), 16);
  }
  return bytes;
}
function uint8ArrayToHex(bytes) {
  return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
}
var Class = class {
  constructor(..._args) {
  }
};

// node_modules/zod/v4/core/errors.js
var initializer = (inst, def) => {
  inst.name = "$ZodError";
  Object.defineProperty(inst, "_zod", {
    value: inst._zod,
    enumerable: false
  });
  Object.defineProperty(inst, "issues", {
    value: def,
    enumerable: false
  });
  inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
  Object.defineProperty(inst, "toString", {
    value: () => inst.message,
    enumerable: false
  });
};
var $ZodError = $constructor("$ZodError", initializer);
var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
function flattenError(error51, mapper = (issue2) => issue2.message) {
  const fieldErrors = {};
  const formErrors = [];
  for (const sub of error51.issues) {
    if (sub.path.length > 0) {
      fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
      fieldErrors[sub.path[0]].push(mapper(sub));
    } else {
      formErrors.push(mapper(sub));
    }
  }
  return { formErrors, fieldErrors };
}
function formatError(error51, mapper = (issue2) => issue2.message) {
  const fieldErrors = { _errors: [] };
  const processError = (error52, path = []) => {
    for (const issue2 of error52.issues) {
      if (issue2.code === "invalid_union" && issue2.errors.length) {
        issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path]));
      } else if (issue2.code === "invalid_key") {
        processError({ issues: issue2.issues }, [...path, ...issue2.path]);
      } else if (issue2.code === "invalid_element") {
        processError({ issues: issue2.issues }, [...path, ...issue2.path]);
      } else {
        const fullpath = [...path, ...issue2.path];
        if (fullpath.length === 0) {
          fieldErrors._errors.push(mapper(issue2));
        } else {
          let curr = fieldErrors;
          let i2 = 0;
          while (i2 < fullpath.length) {
            const el = fullpath[i2];
            const terminal = i2 === fullpath.length - 1;
            if (!terminal) {
              curr[el] = curr[el] || { _errors: [] };
            } else {
              curr[el] = curr[el] || { _errors: [] };
              curr[el]._errors.push(mapper(issue2));
            }
            curr = curr[el];
            i2++;
          }
        }
      }
    }
  };
  processError(error51);
  return fieldErrors;
}
function treeifyError(error51, mapper = (issue2) => issue2.message) {
  const result = { errors: [] };
  const processError = (error52, path = []) => {
    var _a3, _b;
    for (const issue2 of error52.issues) {
      if (issue2.code === "invalid_union" && issue2.errors.length) {
        issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path]));
      } else if (issue2.code === "invalid_key") {
        processError({ issues: issue2.issues }, [...path, ...issue2.path]);
      } else if (issue2.code === "invalid_element") {
        processError({ issues: issue2.issues }, [...path, ...issue2.path]);
      } else {
        const fullpath = [...path, ...issue2.path];
        if (fullpath.length === 0) {
          result.errors.push(mapper(issue2));
          continue;
        }
        let curr = result;
        let i2 = 0;
        while (i2 < fullpath.length) {
          const el = fullpath[i2];
          const terminal = i2 === fullpath.length - 1;
          if (typeof el === "string") {
            curr.properties ?? (curr.properties = {});
            (_a3 = curr.properties)[el] ?? (_a3[el] = { errors: [] });
            curr = curr.properties[el];
          } else {
            curr.items ?? (curr.items = []);
            (_b = curr.items)[el] ?? (_b[el] = { errors: [] });
            curr = curr.items[el];
          }
          if (terminal) {
            curr.errors.push(mapper(issue2));
          }
          i2++;
        }
      }
    }
  };
  processError(error51);
  return result;
}
function toDotPath(_path) {
  const segs = [];
  const path = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
  for (const seg of path) {
    if (typeof seg === "number")
      segs.push(`[${seg}]`);
    else if (typeof seg === "symbol")
      segs.push(`[${JSON.stringify(String(seg))}]`);
    else if (/[^\w$]/.test(seg))
      segs.push(`[${JSON.stringify(seg)}]`);
    else {
      if (segs.length)
        segs.push(".");
      segs.push(seg);
    }
  }
  return segs.join("");
}
function prettifyError(error51) {
  const lines = [];
  const issues = [...error51.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);
  for (const issue2 of issues) {
    lines.push(`\u2716 ${issue2.message}`);
    if (issue2.path?.length)
      lines.push(`  \u2192 at ${toDotPath(issue2.path)}`);
  }
  return lines.join("\n");
}

// node_modules/zod/v4/core/parse.js
var _parse = (_Err) => (schema, value, _ctx, _params) => {
  const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
  const result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise) {
    throw new $ZodAsyncError();
  }
  if (result.issues.length) {
    const e2 = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
    captureStackTrace(e2, _params?.callee);
    throw e2;
  }
  return result.value;
};
var parse = /* @__PURE__ */ _parse($ZodRealError);
var _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
  const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
  let result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise)
    result = await result;
  if (result.issues.length) {
    const e2 = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
    captureStackTrace(e2, params?.callee);
    throw e2;
  }
  return result.value;
};
var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError);
var _safeParse = (_Err) => (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
  const result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise) {
    throw new $ZodAsyncError();
  }
  return result.issues.length ? {
    success: false,
    error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
  } : { success: true, data: result.value };
};
var safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
var _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
  let result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise)
    result = await result;
  return result.issues.length ? {
    success: false,
    error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
  } : { success: true, data: result.value };
};
var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError);
var _encode = (_Err) => (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
  return _parse(_Err)(schema, value, ctx);
};
var encode = /* @__PURE__ */ _encode($ZodRealError);
var _decode = (_Err) => (schema, value, _ctx) => {
  return _parse(_Err)(schema, value, _ctx);
};
var decode = /* @__PURE__ */ _decode($ZodRealError);
var _encodeAsync = (_Err) => async (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
  return _parseAsync(_Err)(schema, value, ctx);
};
var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError);
var _decodeAsync = (_Err) => async (schema, value, _ctx) => {
  return _parseAsync(_Err)(schema, value, _ctx);
};
var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError);
var _safeEncode = (_Err) => (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
  return _safeParse(_Err)(schema, value, ctx);
};
var safeEncode = /* @__PURE__ */ _safeEncode($ZodRealError);
var _safeDecode = (_Err) => (schema, value, _ctx) => {
  return _safeParse(_Err)(schema, value, _ctx);
};
var safeDecode = /* @__PURE__ */ _safeDecode($ZodRealError);
var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
  return _safeParseAsync(_Err)(schema, value, ctx);
};
var safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync($ZodRealError);
var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
  return _safeParseAsync(_Err)(schema, value, _ctx);
};
var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError);

// node_modules/zod/v4/core/regexes.js
var regexes_exports = {};
__export(regexes_exports, {
  base64: () => base64,
  base64url: () => base64url,
  bigint: () => bigint,
  boolean: () => boolean,
  browserEmail: () => browserEmail,
  cidrv4: () => cidrv4,
  cidrv6: () => cidrv6,
  cuid: () => cuid,
  cuid2: () => cuid2,
  date: () => date,
  datetime: () => datetime,
  domain: () => domain,
  duration: () => duration,
  e164: () => e164,
  email: () => email,
  emoji: () => emoji,
  extendedDuration: () => extendedDuration,
  guid: () => guid,
  hex: () => hex,
  hostname: () => hostname,
  html5Email: () => html5Email,
  httpProtocol: () => httpProtocol,
  idnEmail: () => idnEmail,
  integer: () => integer,
  ipv4: () => ipv4,
  ipv6: () => ipv6,
  ksuid: () => ksuid,
  lowercase: () => lowercase,
  mac: () => mac,
  md5_base64: () => md5_base64,
  md5_base64url: () => md5_base64url,
  md5_hex: () => md5_hex,
  nanoid: () => nanoid,
  null: () => _null,
  number: () => number,
  rfc5322Email: () => rfc5322Email,
  sha1_base64: () => sha1_base64,
  sha1_base64url: () => sha1_base64url,
  sha1_hex: () => sha1_hex,
  sha256_base64: () => sha256_base64,
  sha256_base64url: () => sha256_base64url,
  sha256_hex: () => sha256_hex,
  sha384_base64: () => sha384_base64,
  sha384_base64url: () => sha384_base64url,
  sha384_hex: () => sha384_hex,
  sha512_base64: () => sha512_base64,
  sha512_base64url: () => sha512_base64url,
  sha512_hex: () => sha512_hex,
  string: () => string,
  time: () => time,
  ulid: () => ulid,
  undefined: () => _undefined,
  unicodeEmail: () => unicodeEmail,
  uppercase: () => uppercase,
  uuid: () => uuid,
  uuid4: () => uuid4,
  uuid6: () => uuid6,
  uuid7: () => uuid7,
  xid: () => xid
});
var cuid = /^[cC][0-9a-z]{6,}$/;
var cuid2 = /^[0-9a-z]+$/;
var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
var xid = /^[0-9a-vA-V]{20}$/;
var ksuid = /^[A-Za-z0-9]{27}$/;
var nanoid = /^[a-zA-Z0-9_-]{21}$/;
var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
var uuid = (version2) => {
  if (!version2)
    return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
  return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
};
var uuid4 = /* @__PURE__ */ uuid(4);
var uuid6 = /* @__PURE__ */ uuid(6);
var uuid7 = /* @__PURE__ */ uuid(7);
var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u;
var idnEmail = unicodeEmail;
var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
function emoji() {
  return new RegExp(_emoji, "u");
}
var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
var mac = (delimiter) => {
  const escapedDelim = escapeRegex(delimiter ?? ":");
  return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);
};
var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
var base64url = /^[A-Za-z0-9_-]*$/;
var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;
var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
var httpProtocol = /^https?$/;
var e164 = /^\+[1-9]\d{6,14}$/;
var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
function timeSource(args) {
  const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
  const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
  return regex;
}
function time(args) {
  return new RegExp(`^${timeSource(args)}$`);
}
function datetime(args) {
  const time3 = timeSource({ precision: args.precision });
  const opts = ["Z"];
  if (args.local)
    opts.push("");
  if (args.offset)
    opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
  const timeRegex2 = `${time3}(?:${opts.join("|")})`;
  return new RegExp(`^${dateSource}T(?:${timeRegex2})$`);
}
var string = (params) => {
  const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
  return new RegExp(`^${regex}$`);
};
var bigint = /^-?\d+n?$/;
var integer = /^-?\d+$/;
var number = /^-?\d+(?:\.\d+)?$/;
var boolean = /^(?:true|false)$/i;
var _null = /^null$/i;
var _undefined = /^undefined$/i;
var lowercase = /^[^A-Z]*$/;
var uppercase = /^[^a-z]*$/;
var hex = /^[0-9a-fA-F]*$/;
function fixedBase64(bodyLength, padding) {
  return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);
}
function fixedBase64url(length) {
  return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);
}
var md5_hex = /^[0-9a-fA-F]{32}$/;
var md5_base64 = /* @__PURE__ */ fixedBase64(22, "==");
var md5_base64url = /* @__PURE__ */ fixedBase64url(22);
var sha1_hex = /^[0-9a-fA-F]{40}$/;
var sha1_base64 = /* @__PURE__ */ fixedBase64(27, "=");
var sha1_base64url = /* @__PURE__ */ fixedBase64url(27);
var sha256_hex = /^[0-9a-fA-F]{64}$/;
var sha256_base64 = /* @__PURE__ */ fixedBase64(43, "=");
var sha256_base64url = /* @__PURE__ */ fixedBase64url(43);
var sha384_hex = /^[0-9a-fA-F]{96}$/;
var sha384_base64 = /* @__PURE__ */ fixedBase64(64, "");
var sha384_base64url = /* @__PURE__ */ fixedBase64url(64);
var sha512_hex = /^[0-9a-fA-F]{128}$/;
var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "==");
var sha512_base64url = /* @__PURE__ */ fixedBase64url(86);

// node_modules/zod/v4/core/checks.js
var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
  var _a3;
  inst._zod ?? (inst._zod = {});
  inst._zod.def = def;
  (_a3 = inst._zod).onattach ?? (_a3.onattach = []);
});
var numericOriginMap = {
  number: "number",
  bigint: "bigint",
  object: "date"
};
var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
  $ZodCheck.init(inst, def);
  const origin = numericOriginMap[typeof def.value];
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
    if (def.value < curr) {
      if (def.inclusive)
        bag.maximum = def.value;
      else
        bag.exclusiveMaximum = def.value;
    }
  });
  inst._zod.check = (payload) => {
    if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
      return;
    }
    payload.issues.push({
      origin,
      code: "too_big",
      maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
      input: payload.value,
      inclusive: def.inclusive,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
  $ZodCheck.init(inst, def);
  const origin = numericOriginMap[typeof def.value];
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
    if (def.value > curr) {
      if (def.inclusive)
        bag.minimum = def.value;
      else
        bag.exclusiveMinimum = def.value;
    }
  });
  inst._zod.check = (payload) => {
    if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
      return;
    }
    payload.issues.push({
      origin,
      code: "too_small",
      minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
      input: payload.value,
      inclusive: def.inclusive,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
  $ZodCheck.init(inst, def);
  inst._zod.onattach.push((inst2) => {
    var _a3;
    (_a3 = inst2._zod.bag).multipleOf ?? (_a3.multipleOf = def.value);
  });
  inst._zod.check = (payload) => {
    if (typeof payload.value !== typeof def.value)
      throw new Error("Cannot mix number and bigint in multiple_of check.");
    const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0;
    if (isMultiple)
      return;
    payload.issues.push({
      origin: typeof payload.value,
      code: "not_multiple_of",
      divisor: def.value,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
  $ZodCheck.init(inst, def);
  def.format = def.format || "float64";
  const isInt = def.format?.includes("int");
  const origin = isInt ? "int" : "number";
  const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.format = def.format;
    bag.minimum = minimum;
    bag.maximum = maximum;
    if (isInt)
      bag.pattern = integer;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    if (isInt) {
      if (!Number.isInteger(input)) {
        payload.issues.push({
          expected: origin,
          format: def.format,
          code: "invalid_type",
          continue: false,
          input,
          inst
        });
        return;
      }
      if (!Number.isSafeInteger(input)) {
        if (input > 0) {
          payload.issues.push({
            input,
            code: "too_big",
            maximum: Number.MAX_SAFE_INTEGER,
            note: "Integers must be within the safe integer range.",
            inst,
            origin,
            inclusive: true,
            continue: !def.abort
          });
        } else {
          payload.issues.push({
            input,
            code: "too_small",
            minimum: Number.MIN_SAFE_INTEGER,
            note: "Integers must be within the safe integer range.",
            inst,
            origin,
            inclusive: true,
            continue: !def.abort
          });
        }
        return;
      }
    }
    if (input < minimum) {
      payload.issues.push({
        origin: "number",
        input,
        code: "too_small",
        minimum,
        inclusive: true,
        inst,
        continue: !def.abort
      });
    }
    if (input > maximum) {
      payload.issues.push({
        origin: "number",
        input,
        code: "too_big",
        maximum,
        inclusive: true,
        inst,
        continue: !def.abort
      });
    }
  };
});
var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => {
  $ZodCheck.init(inst, def);
  const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format];
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.format = def.format;
    bag.minimum = minimum;
    bag.maximum = maximum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    if (input < minimum) {
      payload.issues.push({
        origin: "bigint",
        input,
        code: "too_small",
        minimum,
        inclusive: true,
        inst,
        continue: !def.abort
      });
    }
    if (input > maximum) {
      payload.issues.push({
        origin: "bigint",
        input,
        code: "too_big",
        maximum,
        inclusive: true,
        inst,
        continue: !def.abort
      });
    }
  };
});
var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => {
  var _a3;
  $ZodCheck.init(inst, def);
  (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.size !== void 0;
  });
  inst._zod.onattach.push((inst2) => {
    const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
    if (def.maximum < curr)
      inst2._zod.bag.maximum = def.maximum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const size = input.size;
    if (size <= def.maximum)
      return;
    payload.issues.push({
      origin: getSizableOrigin(input),
      code: "too_big",
      maximum: def.maximum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => {
  var _a3;
  $ZodCheck.init(inst, def);
  (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.size !== void 0;
  });
  inst._zod.onattach.push((inst2) => {
    const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
    if (def.minimum > curr)
      inst2._zod.bag.minimum = def.minimum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const size = input.size;
    if (size >= def.minimum)
      return;
    payload.issues.push({
      origin: getSizableOrigin(input),
      code: "too_small",
      minimum: def.minimum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => {
  var _a3;
  $ZodCheck.init(inst, def);
  (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.size !== void 0;
  });
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.minimum = def.size;
    bag.maximum = def.size;
    bag.size = def.size;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const size = input.size;
    if (size === def.size)
      return;
    const tooBig = size > def.size;
    payload.issues.push({
      origin: getSizableOrigin(input),
      ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size },
      inclusive: true,
      exact: true,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
  var _a3;
  $ZodCheck.init(inst, def);
  (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.length !== void 0;
  });
  inst._zod.onattach.push((inst2) => {
    const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
    if (def.maximum < curr)
      inst2._zod.bag.maximum = def.maximum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const length = input.length;
    if (length <= def.maximum)
      return;
    const origin = getLengthableOrigin(input);
    payload.issues.push({
      origin,
      code: "too_big",
      maximum: def.maximum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
  var _a3;
  $ZodCheck.init(inst, def);
  (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.length !== void 0;
  });
  inst._zod.onattach.push((inst2) => {
    const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
    if (def.minimum > curr)
      inst2._zod.bag.minimum = def.minimum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const length = input.length;
    if (length >= def.minimum)
      return;
    const origin = getLengthableOrigin(input);
    payload.issues.push({
      origin,
      code: "too_small",
      minimum: def.minimum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
  var _a3;
  $ZodCheck.init(inst, def);
  (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.length !== void 0;
  });
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.minimum = def.length;
    bag.maximum = def.length;
    bag.length = def.length;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const length = input.length;
    if (length === def.length)
      return;
    const origin = getLengthableOrigin(input);
    const tooBig = length > def.length;
    payload.issues.push({
      origin,
      ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length },
      inclusive: true,
      exact: true,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
  var _a3, _b;
  $ZodCheck.init(inst, def);
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.format = def.format;
    if (def.pattern) {
      bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
      bag.patterns.add(def.pattern);
    }
  });
  if (def.pattern)
    (_a3 = inst._zod).check ?? (_a3.check = (payload) => {
      def.pattern.lastIndex = 0;
      if (def.pattern.test(payload.value))
        return;
      payload.issues.push({
        origin: "string",
        code: "invalid_format",
        format: def.format,
        input: payload.value,
        ...def.pattern ? { pattern: def.pattern.toString() } : {},
        inst,
        continue: !def.abort
      });
    });
  else
    (_b = inst._zod).check ?? (_b.check = () => {
    });
});
var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {
  $ZodCheckStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    def.pattern.lastIndex = 0;
    if (def.pattern.test(payload.value))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "regex",
      input: payload.value,
      pattern: def.pattern.toString(),
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {
  def.pattern ?? (def.pattern = lowercase);
  $ZodCheckStringFormat.init(inst, def);
});
var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
  def.pattern ?? (def.pattern = uppercase);
  $ZodCheckStringFormat.init(inst, def);
});
var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
  $ZodCheck.init(inst, def);
  const escapedRegex = escapeRegex(def.includes);
  const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
  def.pattern = pattern;
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
    bag.patterns.add(pattern);
  });
  inst._zod.check = (payload) => {
    if (payload.value.includes(def.includes, def.position))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "includes",
      includes: def.includes,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
  $ZodCheck.init(inst, def);
  const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
  def.pattern ?? (def.pattern = pattern);
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
    bag.patterns.add(pattern);
  });
  inst._zod.check = (payload) => {
    if (payload.value.startsWith(def.prefix))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "starts_with",
      prefix: def.prefix,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
  $ZodCheck.init(inst, def);
  const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
  def.pattern ?? (def.pattern = pattern);
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
    bag.patterns.add(pattern);
  });
  inst._zod.check = (payload) => {
    if (payload.value.endsWith(def.suffix))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "ends_with",
      suffix: def.suffix,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
function handleCheckPropertyResult(result, payload, property) {
  if (result.issues.length) {
    payload.issues.push(...prefixIssues(property, result.issues));
  }
}
var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def) => {
  $ZodCheck.init(inst, def);
  inst._zod.check = (payload) => {
    const result = def.schema._zod.run({
      value: payload.value[def.property],
      issues: []
    }, {});
    if (result instanceof Promise) {
      return result.then((result2) => handleCheckPropertyResult(result2, payload, def.property));
    }
    handleCheckPropertyResult(result, payload, def.property);
    return;
  };
});
var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => {
  $ZodCheck.init(inst, def);
  const mimeSet = new Set(def.mime);
  inst._zod.onattach.push((inst2) => {
    inst2._zod.bag.mime = def.mime;
  });
  inst._zod.check = (payload) => {
    if (mimeSet.has(payload.value.type))
      return;
    payload.issues.push({
      code: "invalid_value",
      values: def.mime,
      input: payload.value.type,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
  $ZodCheck.init(inst, def);
  inst._zod.check = (payload) => {
    payload.value = def.tx(payload.value);
  };
});

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

// node_modules/zod/v4/core/versions.js
var version = {
  major: 4,
  minor: 4,
  patch: 3
};

// node_modules/zod/v4/core/schemas.js
var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
  var _a3;
  inst ?? (inst = {});
  inst._zod.def = def;
  inst._zod.bag = inst._zod.bag || {};
  inst._zod.version = version;
  const checks = [...inst._zod.def.checks ?? []];
  if (inst._zod.traits.has("$ZodCheck")) {
    checks.unshift(inst);
  }
  for (const ch of checks) {
    for (const fn of ch._zod.onattach) {
      fn(inst);
    }
  }
  if (checks.length === 0) {
    (_a3 = inst._zod).deferred ?? (_a3.deferred = []);
    inst._zod.deferred?.push(() => {
      inst._zod.run = inst._zod.parse;
    });
  } else {
    const runChecks = (payload, checks2, ctx) => {
      let isAborted2 = aborted(payload);
      let asyncResult;
      for (const ch of checks2) {
        if (ch._zod.def.when) {
          if (explicitlyAborted(payload))
            continue;
          const shouldRun = ch._zod.def.when(payload);
          if (!shouldRun)
            continue;
        } else if (isAborted2) {
          continue;
        }
        const currLen = payload.issues.length;
        const _ = ch._zod.check(payload);
        if (_ instanceof Promise && ctx?.async === false) {
          throw new $ZodAsyncError();
        }
        if (asyncResult || _ instanceof Promise) {
          asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
            await _;
            const nextLen = payload.issues.length;
            if (nextLen === currLen)
              return;
            if (!isAborted2)
              isAborted2 = aborted(payload, currLen);
          });
        } else {
          const nextLen = payload.issues.length;
          if (nextLen === currLen)
            continue;
          if (!isAborted2)
            isAborted2 = aborted(payload, currLen);
        }
      }
      if (asyncResult) {
        return asyncResult.then(() => {
          return payload;
        });
      }
      return payload;
    };
    const handleCanaryResult = (canary, payload, ctx) => {
      if (aborted(canary)) {
        canary.aborted = true;
        return canary;
      }
      const checkResult = runChecks(payload, checks, ctx);
      if (checkResult instanceof Promise) {
        if (ctx.async === false)
          throw new $ZodAsyncError();
        return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, ctx));
      }
      return inst._zod.parse(checkResult, ctx);
    };
    inst._zod.run = (payload, ctx) => {
      if (ctx.skipChecks) {
        return inst._zod.parse(payload, ctx);
      }
      if (ctx.direction === "backward") {
        const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });
        if (canary instanceof Promise) {
          return canary.then((canary2) => {
            return handleCanaryResult(canary2, payload, ctx);
          });
        }
        return handleCanaryResult(canary, payload, ctx);
      }
      const result = inst._zod.parse(payload, ctx);
      if (result instanceof Promise) {
        if (ctx.async === false)
          throw new $ZodAsyncError();
        return result.then((result2) => runChecks(result2, checks, ctx));
      }
      return runChecks(result, checks, ctx);
    };
  }
  defineLazy(inst, "~standard", () => ({
    validate: (value) => {
      try {
        const r2 = safeParse(inst, value);
        return r2.success ? { value: r2.data } : { issues: r2.error?.issues };
      } catch (_) {
        return safeParseAsync(inst, value).then((r2) => r2.success ? { value: r2.data } : { issues: r2.error?.issues });
      }
    },
    vendor: "zod",
    version: 1
  }));
});
var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag);
  inst._zod.parse = (payload, _) => {
    if (def.coerce)
      try {
        payload.value = String(payload.value);
      } catch (_2) {
      }
    if (typeof payload.value === "string")
      return payload;
    payload.issues.push({
      expected: "string",
      code: "invalid_type",
      input: payload.value,
      inst
    });
    return payload;
  };
});
var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => {
  $ZodCheckStringFormat.init(inst, def);
  $ZodString.init(inst, def);
});
var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {
  def.pattern ?? (def.pattern = guid);
  $ZodStringFormat.init(inst, def);
});
var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
  if (def.version) {
    const versionMap = {
      v1: 1,
      v2: 2,
      v3: 3,
      v4: 4,
      v5: 5,
      v6: 6,
      v7: 7,
      v8: 8
    };
    const v = versionMap[def.version];
    if (v === void 0)
      throw new Error(`Invalid UUID version: "${def.version}"`);
    def.pattern ?? (def.pattern = uuid(v));
  } else
    def.pattern ?? (def.pattern = uuid());
  $ZodStringFormat.init(inst, def);
});
var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
  def.pattern ?? (def.pattern = email);
  $ZodStringFormat.init(inst, def);
});
var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    try {
      const trimmed = payload.value.trim();
      if (!def.normalize && def.protocol?.source === httpProtocol.source) {
        if (!/^https?:\/\//i.test(trimmed)) {
          payload.issues.push({
            code: "invalid_format",
            format: "url",
            note: "Invalid URL format",
            input: payload.value,
            inst,
            continue: !def.abort
          });
          return;
        }
      }
      const url2 = new URL(trimmed);
      if (def.hostname) {
        def.hostname.lastIndex = 0;
        if (!def.hostname.test(url2.hostname)) {
          payload.issues.push({
            code: "invalid_format",
            format: "url",
            note: "Invalid hostname",
            pattern: def.hostname.source,
            input: payload.value,
            inst,
            continue: !def.abort
          });
        }
      }
      if (def.protocol) {
        def.protocol.lastIndex = 0;
        if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) {
          payload.issues.push({
            code: "invalid_format",
            format: "url",
            note: "Invalid protocol",
            pattern: def.protocol.source,
            input: payload.value,
            inst,
            continue: !def.abort
          });
        }
      }
      if (def.normalize) {
        payload.value = url2.href;
      } else {
        payload.value = trimmed;
      }
      return;
    } catch (_) {
      payload.issues.push({
        code: "invalid_format",
        format: "url",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    }
  };
});
var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
  def.pattern ?? (def.pattern = emoji());
  $ZodStringFormat.init(inst, def);
});
var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
  def.pattern ?? (def.pattern = nanoid);
  $ZodStringFormat.init(inst, def);
});
var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
  def.pattern ?? (def.pattern = cuid);
  $ZodStringFormat.init(inst, def);
});
var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {
  def.pattern ?? (def.pattern = cuid2);
  $ZodStringFormat.init(inst, def);
});
var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {
  def.pattern ?? (def.pattern = ulid);
  $ZodStringFormat.init(inst, def);
});
var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {
  def.pattern ?? (def.pattern = xid);
  $ZodStringFormat.init(inst, def);
});
var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
  def.pattern ?? (def.pattern = ksuid);
  $ZodStringFormat.init(inst, def);
});
var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
  def.pattern ?? (def.pattern = datetime(def));
  $ZodStringFormat.init(inst, def);
});
var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
  def.pattern ?? (def.pattern = date);
  $ZodStringFormat.init(inst, def);
});
var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
  def.pattern ?? (def.pattern = time(def));
  $ZodStringFormat.init(inst, def);
});
var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
  def.pattern ?? (def.pattern = duration);
  $ZodStringFormat.init(inst, def);
});
var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
  def.pattern ?? (def.pattern = ipv4);
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.format = `ipv4`;
});
var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
  def.pattern ?? (def.pattern = ipv6);
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.format = `ipv6`;
  inst._zod.check = (payload) => {
    try {
      new URL(`http://[${payload.value}]`);
    } catch {
      payload.issues.push({
        code: "invalid_format",
        format: "ipv6",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    }
  };
});
var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => {
  def.pattern ?? (def.pattern = mac(def.delimiter));
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.format = `mac`;
});
var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
  def.pattern ?? (def.pattern = cidrv4);
  $ZodStringFormat.init(inst, def);
});
var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
  def.pattern ?? (def.pattern = cidrv6);
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    const parts = payload.value.split("/");
    try {
      if (parts.length !== 2)
        throw new Error();
      const [address, prefix] = parts;
      if (!prefix)
        throw new Error();
      const prefixNum = Number(prefix);
      if (`${prefixNum}` !== prefix)
        throw new Error();
      if (prefixNum < 0 || prefixNum > 128)
        throw new Error();
      new URL(`http://[${address}]`);
    } catch {
      payload.issues.push({
        code: "invalid_format",
        format: "cidrv6",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    }
  };
});
function isValidBase64(data) {
  if (data === "")
    return true;
  if (/\s/.test(data))
    return false;
  if (data.length % 4 !== 0)
    return false;
  try {
    atob(data);
    return true;
  } catch {
    return false;
  }
}
var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
  def.pattern ?? (def.pattern = base64);
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.contentEncoding = "base64";
  inst._zod.check = (payload) => {
    if (isValidBase64(payload.value))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: "base64",
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
function isValidBase64URL(data) {
  if (!base64url.test(data))
    return false;
  const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
  const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "=");
  return isValidBase64(padded);
}
var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
  def.pattern ?? (def.pattern = base64url);
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.contentEncoding = "base64url";
  inst._zod.check = (payload) => {
    if (isValidBase64URL(payload.value))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: "base64url",
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {
  def.pattern ?? (def.pattern = e164);
  $ZodStringFormat.init(inst, def);
});
function isValidJWT(token, algorithm = null) {
  try {
    const tokensParts = token.split(".");
    if (tokensParts.length !== 3)
      return false;
    const [header] = tokensParts;
    if (!header)
      return false;
    const parsedHeader = JSON.parse(atob(header));
    if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")
      return false;
    if (!parsedHeader.alg)
      return false;
    if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
      return false;
    return true;
  } catch {
    return false;
  }
}
var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    if (isValidJWT(payload.value, def.alg))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: "jwt",
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    if (def.fn(payload.value))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: def.format,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = inst._zod.bag.pattern ?? number;
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce)
      try {
        payload.value = Number(payload.value);
      } catch (_) {
      }
    const input = payload.value;
    if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
      return payload;
    }
    const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
    payload.issues.push({
      expected: "number",
      code: "invalid_type",
      input,
      inst,
      ...received ? { received } : {}
    });
    return payload;
  };
});
var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => {
  $ZodCheckNumberFormat.init(inst, def);
  $ZodNumber.init(inst, def);
});
var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = boolean;
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce)
      try {
        payload.value = Boolean(payload.value);
      } catch (_) {
      }
    const input = payload.value;
    if (typeof input === "boolean")
      return payload;
    payload.issues.push({
      expected: "boolean",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = bigint;
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce)
      try {
        payload.value = BigInt(payload.value);
      } catch (_) {
      }
    if (typeof payload.value === "bigint")
      return payload;
    payload.issues.push({
      expected: "bigint",
      code: "invalid_type",
      input: payload.value,
      inst
    });
    return payload;
  };
});
var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, def) => {
  $ZodCheckBigIntFormat.init(inst, def);
  $ZodBigInt.init(inst, def);
});
var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (typeof input === "symbol")
      return payload;
    payload.issues.push({
      expected: "symbol",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = _undefined;
  inst._zod.values = /* @__PURE__ */ new Set([void 0]);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (typeof input === "undefined")
      return payload;
    payload.issues.push({
      expected: "undefined",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = _null;
  inst._zod.values = /* @__PURE__ */ new Set([null]);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (input === null)
      return payload;
    payload.issues.push({
      expected: "null",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload) => payload;
});
var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload) => payload;
});
var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    payload.issues.push({
      expected: "never",
      code: "invalid_type",
      input: payload.value,
      inst
    });
    return payload;
  };
});
var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (typeof input === "undefined")
      return payload;
    payload.issues.push({
      expected: "void",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce) {
      try {
        payload.value = new Date(payload.value);
      } catch (_err) {
      }
    }
    const input = payload.value;
    const isDate = input instanceof Date;
    const isValidDate = isDate && !Number.isNaN(input.getTime());
    if (isValidDate)
      return payload;
    payload.issues.push({
      expected: "date",
      code: "invalid_type",
      input,
      ...isDate ? { received: "Invalid Date" } : {},
      inst
    });
    return payload;
  };
});
function handleArrayResult(result, final, index) {
  if (result.issues.length) {
    final.issues.push(...prefixIssues(index, result.issues));
  }
  final.value[index] = result.value;
}
var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!Array.isArray(input)) {
      payload.issues.push({
        expected: "array",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    payload.value = Array(input.length);
    const proms = [];
    for (let i2 = 0; i2 < input.length; i2++) {
      const item = input[i2];
      const result = def.element._zod.run({
        value: item,
        issues: []
      }, ctx);
      if (result instanceof Promise) {
        proms.push(result.then((result2) => handleArrayResult(result2, payload, i2)));
      } else {
        handleArrayResult(result, payload, i2);
      }
    }
    if (proms.length) {
      return Promise.all(proms).then(() => payload);
    }
    return payload;
  };
});
function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {
  const isPresent = key in input;
  if (result.issues.length) {
    if (isOptionalIn && isOptionalOut && !isPresent) {
      return;
    }
    final.issues.push(...prefixIssues(key, result.issues));
  }
  if (!isPresent && !isOptionalIn) {
    if (!result.issues.length) {
      final.issues.push({
        code: "invalid_type",
        expected: "nonoptional",
        input: void 0,
        path: [key]
      });
    }
    return;
  }
  if (result.value === void 0) {
    if (isPresent) {
      final.value[key] = void 0;
    }
  } else {
    final.value[key] = result.value;
  }
}
function normalizeDef(def) {
  const keys = Object.keys(def.shape);
  for (const k of keys) {
    if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) {
      throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
    }
  }
  const okeys = optionalKeys(def.shape);
  return {
    ...def,
    keys,
    keySet: new Set(keys),
    numKeys: keys.length,
    optionalKeys: new Set(okeys)
  };
}
function handleCatchall(proms, input, payload, ctx, def, inst) {
  const unrecognized = [];
  const keySet = def.keySet;
  const _catchall = def.catchall._zod;
  const t2 = _catchall.def.type;
  const isOptionalIn = _catchall.optin === "optional";
  const isOptionalOut = _catchall.optout === "optional";
  for (const key in input) {
    if (key === "__proto__")
      continue;
    if (keySet.has(key))
      continue;
    if (t2 === "never") {
      unrecognized.push(key);
      continue;
    }
    const r2 = _catchall.run({ value: input[key], issues: [] }, ctx);
    if (r2 instanceof Promise) {
      proms.push(r2.then((r3) => handlePropertyResult(r3, payload, key, input, isOptionalIn, isOptionalOut)));
    } else {
      handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut);
    }
  }
  if (unrecognized.length) {
    payload.issues.push({
      code: "unrecognized_keys",
      keys: unrecognized,
      input,
      inst
    });
  }
  if (!proms.length)
    return payload;
  return Promise.all(proms).then(() => {
    return payload;
  });
}
var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
  $ZodType.init(inst, def);
  const desc = Object.getOwnPropertyDescriptor(def, "shape");
  if (!desc?.get) {
    const sh = def.shape;
    Object.defineProperty(def, "shape", {
      get: () => {
        const newSh = { ...sh };
        Object.defineProperty(def, "shape", {
          value: newSh
        });
        return newSh;
      }
    });
  }
  const _normalized = cached(() => normalizeDef(def));
  defineLazy(inst._zod, "propValues", () => {
    const shape = def.shape;
    const propValues = {};
    for (const key in shape) {
      const field = shape[key]._zod;
      if (field.values) {
        propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
        for (const v of field.values)
          propValues[key].add(v);
      }
    }
    return propValues;
  });
  const isObject2 = isObject;
  const catchall = def.catchall;
  let value;
  inst._zod.parse = (payload, ctx) => {
    value ?? (value = _normalized.value);
    const input = payload.value;
    if (!isObject2(input)) {
      payload.issues.push({
        expected: "object",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    payload.value = {};
    const proms = [];
    const shape = value.shape;
    for (const key of value.keys) {
      const el = shape[key];
      const isOptionalIn = el._zod.optin === "optional";
      const isOptionalOut = el._zod.optout === "optional";
      const r2 = el._zod.run({ value: input[key], issues: [] }, ctx);
      if (r2 instanceof Promise) {
        proms.push(r2.then((r3) => handlePropertyResult(r3, payload, key, input, isOptionalIn, isOptionalOut)));
      } else {
        handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut);
      }
    }
    if (!catchall) {
      return proms.length ? Promise.all(proms).then(() => payload) : payload;
    }
    return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
  };
});
var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
  $ZodObject.init(inst, def);
  const superParse = inst._zod.parse;
  const _normalized = cached(() => normalizeDef(def));
  const generateFastpass = (shape) => {
    const doc = new Doc(["shape", "payload", "ctx"]);
    const normalized = _normalized.value;
    const parseStr = (key) => {
      const k = esc(key);
      return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
    };
    doc.write(`const input = payload.value;`);
    const ids = /* @__PURE__ */ Object.create(null);
    let counter = 0;
    for (const key of normalized.keys) {
      ids[key] = `key_${counter++}`;
    }
    doc.write(`const newResult = {};`);
    for (const key of normalized.keys) {
      const id = ids[key];
      const k = esc(key);
      const schema = shape[key];
      const isOptionalIn = schema?._zod?.optin === "optional";
      const isOptionalOut = schema?._zod?.optout === "optional";
      doc.write(`const ${id} = ${parseStr(key)};`);
      if (isOptionalIn && isOptionalOut) {
        doc.write(`
        if (${id}.issues.length) {
          if (${k} in input) {
            payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
              ...iss,
              path: iss.path ? [${k}, ...iss.path] : [${k}]
            })));
          }
        }
        
        if (${id}.value === undefined) {
          if (${k} in input) {
            newResult[${k}] = undefined;
          }
        } else {
          newResult[${k}] = ${id}.value;
        }
        
      `);
      } else if (!isOptionalIn) {
        doc.write(`
        const ${id}_present = ${k} in input;
        if (${id}.issues.length) {
          payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
            ...iss,
            path: iss.path ? [${k}, ...iss.path] : [${k}]
          })));
        }
        if (!${id}_present && !${id}.issues.length) {
          payload.issues.push({
            code: "invalid_type",
            expected: "nonoptional",
            input: undefined,
            path: [${k}]
          });
        }

        if (${id}_present) {
          if (${id}.value === undefined) {
            newResult[${k}] = undefined;
          } else {
            newResult[${k}] = ${id}.value;
          }
        }

      `);
      } else {
        doc.write(`
        if (${id}.issues.length) {
          payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
            ...iss,
            path: iss.path ? [${k}, ...iss.path] : [${k}]
          })));
        }
        
        if (${id}.value === undefined) {
          if (${k} in input) {
            newResult[${k}] = undefined;
          }
        } else {
          newResult[${k}] = ${id}.value;
        }
        
      `);
      }
    }
    doc.write(`payload.value = newResult;`);
    doc.write(`return payload;`);
    const fn = doc.compile();
    return (payload, ctx) => fn(shape, payload, ctx);
  };
  let fastpass;
  const isObject2 = isObject;
  const jit = !globalConfig.jitless;
  const allowsEval2 = allowsEval;
  const fastEnabled = jit && allowsEval2.value;
  const catchall = def.catchall;
  let value;
  inst._zod.parse = (payload, ctx) => {
    value ?? (value = _normalized.value);
    const input = payload.value;
    if (!isObject2(input)) {
      payload.issues.push({
        expected: "object",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
      if (!fastpass)
        fastpass = generateFastpass(def.shape);
      payload = fastpass(payload, ctx);
      if (!catchall)
        return payload;
      return handleCatchall([], input, payload, ctx, value, inst);
    }
    return superParse(payload, ctx);
  };
});
function handleUnionResults(results, final, inst, ctx) {
  for (const result of results) {
    if (result.issues.length === 0) {
      final.value = result.value;
      return final;
    }
  }
  const nonaborted = results.filter((r2) => !aborted(r2));
  if (nonaborted.length === 1) {
    final.value = nonaborted[0].value;
    return nonaborted[0];
  }
  final.issues.push({
    code: "invalid_union",
    input: final.value,
    inst,
    errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
  });
  return final;
}
var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0);
  defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
  defineLazy(inst._zod, "values", () => {
    if (def.options.every((o) => o._zod.values)) {
      return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
    }
    return void 0;
  });
  defineLazy(inst._zod, "pattern", () => {
    if (def.options.every((o) => o._zod.pattern)) {
      const patterns = def.options.map((o) => o._zod.pattern);
      return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
    }
    return void 0;
  });
  const first = def.options.length === 1 ? def.options[0]._zod.run : null;
  inst._zod.parse = (payload, ctx) => {
    if (first) {
      return first(payload, ctx);
    }
    let async = false;
    const results = [];
    for (const option of def.options) {
      const result = option._zod.run({
        value: payload.value,
        issues: []
      }, ctx);
      if (result instanceof Promise) {
        results.push(result);
        async = true;
      } else {
        if (result.issues.length === 0)
          return result;
        results.push(result);
      }
    }
    if (!async)
      return handleUnionResults(results, payload, inst, ctx);
    return Promise.all(results).then((results2) => {
      return handleUnionResults(results2, payload, inst, ctx);
    });
  };
});
function handleExclusiveUnionResults(results, final, inst, ctx) {
  const successes = results.filter((r2) => r2.issues.length === 0);
  if (successes.length === 1) {
    final.value = successes[0].value;
    return final;
  }
  if (successes.length === 0) {
    final.issues.push({
      code: "invalid_union",
      input: final.value,
      inst,
      errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
    });
  } else {
    final.issues.push({
      code: "invalid_union",
      input: final.value,
      inst,
      errors: [],
      inclusive: false
    });
  }
  return final;
}
var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => {
  $ZodUnion.init(inst, def);
  def.inclusive = false;
  const first = def.options.length === 1 ? def.options[0]._zod.run : null;
  inst._zod.parse = (payload, ctx) => {
    if (first) {
      return first(payload, ctx);
    }
    let async = false;
    const results = [];
    for (const option of def.options) {
      const result = option._zod.run({
        value: payload.value,
        issues: []
      }, ctx);
      if (result instanceof Promise) {
        results.push(result);
        async = true;
      } else {
        results.push(result);
      }
    }
    if (!async)
      return handleExclusiveUnionResults(results, payload, inst, ctx);
    return Promise.all(results).then((results2) => {
      return handleExclusiveUnionResults(results2, payload, inst, ctx);
    });
  };
});
var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => {
  def.inclusive = false;
  $ZodUnion.init(inst, def);
  const _super = inst._zod.parse;
  defineLazy(inst._zod, "propValues", () => {
    const propValues = {};
    for (const option of def.options) {
      const pv = option._zod.propValues;
      if (!pv || Object.keys(pv).length === 0)
        throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
      for (const [k, v] of Object.entries(pv)) {
        if (!propValues[k])
          propValues[k] = /* @__PURE__ */ new Set();
        for (const val of v) {
          propValues[k].add(val);
        }
      }
    }
    return propValues;
  });
  const disc = cached(() => {
    const opts = def.options;
    const map2 = /* @__PURE__ */ new Map();
    for (const o of opts) {
      const values = o._zod.propValues?.[def.discriminator];
      if (!values || values.size === 0)
        throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
      for (const v of values) {
        if (map2.has(v)) {
          throw new Error(`Duplicate discriminator value "${String(v)}"`);
        }
        map2.set(v, o);
      }
    }
    return map2;
  });
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!isObject(input)) {
      payload.issues.push({
        code: "invalid_type",
        expected: "object",
        input,
        inst
      });
      return payload;
    }
    const opt = disc.value.get(input?.[def.discriminator]);
    if (opt) {
      return opt._zod.run(payload, ctx);
    }
    if (def.unionFallback || ctx.direction === "backward") {
      return _super(payload, ctx);
    }
    payload.issues.push({
      code: "invalid_union",
      errors: [],
      note: "No matching discriminator",
      discriminator: def.discriminator,
      options: Array.from(disc.value.keys()),
      input,
      path: [def.discriminator],
      inst
    });
    return payload;
  };
});
var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    const left = def.left._zod.run({ value: input, issues: [] }, ctx);
    const right = def.right._zod.run({ value: input, issues: [] }, ctx);
    const async = left instanceof Promise || right instanceof Promise;
    if (async) {
      return Promise.all([left, right]).then(([left2, right2]) => {
        return handleIntersectionResults(payload, left2, right2);
      });
    }
    return handleIntersectionResults(payload, left, right);
  };
});
function mergeValues(a, b) {
  if (a === b) {
    return { valid: true, data: a };
  }
  if (a instanceof Date && b instanceof Date && +a === +b) {
    return { valid: true, data: a };
  }
  if (isPlainObject(a) && isPlainObject(b)) {
    const bKeys = Object.keys(b);
    const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a, ...b };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a[key], b[key]);
      if (!sharedValue.valid) {
        return {
          valid: false,
          mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
        };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  }
  if (Array.isArray(a) && Array.isArray(b)) {
    if (a.length !== b.length) {
      return { valid: false, mergeErrorPath: [] };
    }
    const newArray = [];
    for (let index = 0; index < a.length; index++) {
      const itemA = a[index];
      const itemB = b[index];
      const sharedValue = mergeValues(itemA, itemB);
      if (!sharedValue.valid) {
        return {
          valid: false,
          mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
        };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  }
  return { valid: false, mergeErrorPath: [] };
}
function handleIntersectionResults(result, left, right) {
  const unrecKeys = /* @__PURE__ */ new Map();
  let unrecIssue;
  for (const iss of left.issues) {
    if (iss.code === "unrecognized_keys") {
      unrecIssue ?? (unrecIssue = iss);
      for (const k of iss.keys) {
        if (!unrecKeys.has(k))
          unrecKeys.set(k, {});
        unrecKeys.get(k).l = true;
      }
    } else {
      result.issues.push(iss);
    }
  }
  for (const iss of right.issues) {
    if (iss.code === "unrecognized_keys") {
      for (const k of iss.keys) {
        if (!unrecKeys.has(k))
          unrecKeys.set(k, {});
        unrecKeys.get(k).r = true;
      }
    } else {
      result.issues.push(iss);
    }
  }
  const bothKeys = [...unrecKeys].filter(([, f3]) => f3.l && f3.r).map(([k]) => k);
  if (bothKeys.length && unrecIssue) {
    result.issues.push({ ...unrecIssue, keys: bothKeys });
  }
  if (aborted(result))
    return result;
  const merged = mergeValues(left.value, right.value);
  if (!merged.valid) {
    throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
  }
  result.value = merged.data;
  return result;
}
var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => {
  $ZodType.init(inst, def);
  const items = def.items;
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!Array.isArray(input)) {
      payload.issues.push({
        input,
        inst,
        expected: "tuple",
        code: "invalid_type"
      });
      return payload;
    }
    payload.value = [];
    const proms = [];
    const optinStart = getTupleOptStart(items, "optin");
    const optoutStart = getTupleOptStart(items, "optout");
    if (!def.rest) {
      if (input.length < optinStart) {
        payload.issues.push({
          code: "too_small",
          minimum: optinStart,
          inclusive: true,
          input,
          inst,
          origin: "array"
        });
        return payload;
      }
      if (input.length > items.length) {
        payload.issues.push({
          code: "too_big",
          maximum: items.length,
          inclusive: true,
          input,
          inst,
          origin: "array"
        });
      }
    }
    const itemResults = new Array(items.length);
    for (let i2 = 0; i2 < items.length; i2++) {
      const r2 = items[i2]._zod.run({ value: input[i2], issues: [] }, ctx);
      if (r2 instanceof Promise) {
        proms.push(r2.then((rr) => {
          itemResults[i2] = rr;
        }));
      } else {
        itemResults[i2] = r2;
      }
    }
    if (def.rest) {
      let i2 = items.length - 1;
      const rest = input.slice(items.length);
      for (const el of rest) {
        i2++;
        const result = def.rest._zod.run({ value: el, issues: [] }, ctx);
        if (result instanceof Promise) {
          proms.push(result.then((r2) => handleTupleResult(r2, payload, i2)));
        } else {
          handleTupleResult(result, payload, i2);
        }
      }
    }
    if (proms.length) {
      return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));
    }
    return handleTupleResults(itemResults, payload, items, input, optoutStart);
  };
});
function getTupleOptStart(items, key) {
  for (let i2 = items.length - 1; i2 >= 0; i2--) {
    if (items[i2]._zod[key] !== "optional")
      return i2 + 1;
  }
  return 0;
}
function handleTupleResult(result, final, index) {
  if (result.issues.length) {
    final.issues.push(...prefixIssues(index, result.issues));
  }
  final.value[index] = result.value;
}
function handleTupleResults(itemResults, final, items, input, optoutStart) {
  for (let i2 = 0; i2 < items.length; i2++) {
    const r2 = itemResults[i2];
    const isPresent = i2 < input.length;
    if (r2.issues.length) {
      if (!isPresent && i2 >= optoutStart) {
        final.value.length = i2;
        break;
      }
      final.issues.push(...prefixIssues(i2, r2.issues));
    }
    final.value[i2] = r2.value;
  }
  for (let i2 = final.value.length - 1; i2 >= input.length; i2--) {
    if (items[i2]._zod.optout === "optional" && final.value[i2] === void 0) {
      final.value.length = i2;
    } else {
      break;
    }
  }
  return final;
}
var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!isPlainObject(input)) {
      payload.issues.push({
        expected: "record",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    const proms = [];
    const values = def.keyType._zod.values;
    if (values) {
      payload.value = {};
      const recordKeys = /* @__PURE__ */ new Set();
      for (const key of values) {
        if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
          recordKeys.add(typeof key === "number" ? key.toString() : key);
          const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
          if (keyResult instanceof Promise) {
            throw new Error("Async schemas not supported in object keys currently");
          }
          if (keyResult.issues.length) {
            payload.issues.push({
              code: "invalid_key",
              origin: "record",
              issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
              input: key,
              path: [key],
              inst
            });
            continue;
          }
          const outKey = keyResult.value;
          const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
          if (result instanceof Promise) {
            proms.push(result.then((result2) => {
              if (result2.issues.length) {
                payload.issues.push(...prefixIssues(key, result2.issues));
              }
              payload.value[outKey] = result2.value;
            }));
          } else {
            if (result.issues.length) {
              payload.issues.push(...prefixIssues(key, result.issues));
            }
            payload.value[outKey] = result.value;
          }
        }
      }
      let unrecognized;
      for (const key in input) {
        if (!recordKeys.has(key)) {
          unrecognized = unrecognized ?? [];
          unrecognized.push(key);
        }
      }
      if (unrecognized && unrecognized.length > 0) {
        payload.issues.push({
          code: "unrecognized_keys",
          input,
          inst,
          keys: unrecognized
        });
      }
    } else {
      payload.value = {};
      for (const key of Reflect.ownKeys(input)) {
        if (key === "__proto__")
          continue;
        if (!Object.prototype.propertyIsEnumerable.call(input, key))
          continue;
        let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
        if (keyResult instanceof Promise) {
          throw new Error("Async schemas not supported in object keys currently");
        }
        const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length;
        if (checkNumericKey) {
          const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);
          if (retryResult instanceof Promise) {
            throw new Error("Async schemas not supported in object keys currently");
          }
          if (retryResult.issues.length === 0) {
            keyResult = retryResult;
          }
        }
        if (keyResult.issues.length) {
          if (def.mode === "loose") {
            payload.value[key] = input[key];
          } else {
            payload.issues.push({
              code: "invalid_key",
              origin: "record",
              issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
              input: key,
              path: [key],
              inst
            });
          }
          continue;
        }
        const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
        if (result instanceof Promise) {
          proms.push(result.then((result2) => {
            if (result2.issues.length) {
              payload.issues.push(...prefixIssues(key, result2.issues));
            }
            payload.value[keyResult.value] = result2.value;
          }));
        } else {
          if (result.issues.length) {
            payload.issues.push(...prefixIssues(key, result.issues));
          }
          payload.value[keyResult.value] = result.value;
        }
      }
    }
    if (proms.length) {
      return Promise.all(proms).then(() => payload);
    }
    return payload;
  };
});
var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!(input instanceof Map)) {
      payload.issues.push({
        expected: "map",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    const proms = [];
    payload.value = /* @__PURE__ */ new Map();
    for (const [key, value] of input) {
      const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
      const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx);
      if (keyResult instanceof Promise || valueResult instanceof Promise) {
        proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => {
          handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx);
        }));
      } else {
        handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);
      }
    }
    if (proms.length)
      return Promise.all(proms).then(() => payload);
    return payload;
  };
});
function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {
  if (keyResult.issues.length) {
    if (propertyKeyTypes.has(typeof key)) {
      final.issues.push(...prefixIssues(key, keyResult.issues));
    } else {
      final.issues.push({
        code: "invalid_key",
        origin: "map",
        input,
        inst,
        issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
      });
    }
  }
  if (valueResult.issues.length) {
    if (propertyKeyTypes.has(typeof key)) {
      final.issues.push(...prefixIssues(key, valueResult.issues));
    } else {
      final.issues.push({
        origin: "map",
        code: "invalid_element",
        input,
        inst,
        key,
        issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
      });
    }
  }
  final.value.set(keyResult.value, valueResult.value);
}
var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!(input instanceof Set)) {
      payload.issues.push({
        input,
        inst,
        expected: "set",
        code: "invalid_type"
      });
      return payload;
    }
    const proms = [];
    payload.value = /* @__PURE__ */ new Set();
    for (const item of input) {
      const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);
      if (result instanceof Promise) {
        proms.push(result.then((result2) => handleSetResult(result2, payload)));
      } else
        handleSetResult(result, payload);
    }
    if (proms.length)
      return Promise.all(proms).then(() => payload);
    return payload;
  };
});
function handleSetResult(result, final) {
  if (result.issues.length) {
    final.issues.push(...result.issues);
  }
  final.value.add(result.value);
}
var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
  $ZodType.init(inst, def);
  const values = getEnumValues(def.entries);
  const valuesSet = new Set(values);
  inst._zod.values = valuesSet;
  inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (valuesSet.has(input)) {
      return payload;
    }
    payload.issues.push({
      code: "invalid_value",
      values,
      input,
      inst
    });
    return payload;
  };
});
var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
  $ZodType.init(inst, def);
  if (def.values.length === 0) {
    throw new Error("Cannot create literal schema with no valid values");
  }
  const values = new Set(def.values);
  inst._zod.values = values;
  inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (values.has(input)) {
      return payload;
    }
    payload.issues.push({
      code: "invalid_value",
      values: def.values,
      input,
      inst
    });
    return payload;
  };
});
var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (input instanceof File)
      return payload;
    payload.issues.push({
      expected: "file",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      throw new $ZodEncodeError(inst.constructor.name);
    }
    const _out = def.transform(payload.value, payload);
    if (ctx.async) {
      const output = _out instanceof Promise ? _out : Promise.resolve(_out);
      return output.then((output2) => {
        payload.value = output2;
        payload.fallback = true;
        return payload;
      });
    }
    if (_out instanceof Promise) {
      throw new $ZodAsyncError();
    }
    payload.value = _out;
    payload.fallback = true;
    return payload;
  };
});
function handleOptionalResult(result, input) {
  if (input === void 0 && (result.issues.length || result.fallback)) {
    return { issues: [], value: void 0 };
  }
  return result;
}
var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  inst._zod.optout = "optional";
  defineLazy(inst._zod, "values", () => {
    return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0;
  });
  defineLazy(inst._zod, "pattern", () => {
    const pattern = def.innerType._zod.pattern;
    return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;
  });
  inst._zod.parse = (payload, ctx) => {
    if (def.innerType._zod.optin === "optional") {
      const input = payload.value;
      const result = def.innerType._zod.run(payload, ctx);
      if (result instanceof Promise)
        return result.then((r2) => handleOptionalResult(r2, input));
      return handleOptionalResult(result, input);
    }
    if (payload.value === void 0) {
      return payload;
    }
    return def.innerType._zod.run(payload, ctx);
  };
});
var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => {
  $ZodOptional.init(inst, def);
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern);
  inst._zod.parse = (payload, ctx) => {
    return def.innerType._zod.run(payload, ctx);
  };
});
var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
  defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
  defineLazy(inst._zod, "pattern", () => {
    const pattern = def.innerType._zod.pattern;
    return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;
  });
  defineLazy(inst._zod, "values", () => {
    return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0;
  });
  inst._zod.parse = (payload, ctx) => {
    if (payload.value === null)
      return payload;
    return def.innerType._zod.run(payload, ctx);
  };
});
var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      return def.innerType._zod.run(payload, ctx);
    }
    if (payload.value === void 0) {
      payload.value = def.defaultValue;
      return payload;
    }
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then((result2) => handleDefaultResult(result2, def));
    }
    return handleDefaultResult(result, def);
  };
});
function handleDefaultResult(payload, def) {
  if (payload.value === void 0) {
    payload.value = def.defaultValue;
  }
  return payload;
}
var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      return def.innerType._zod.run(payload, ctx);
    }
    if (payload.value === void 0) {
      payload.value = def.defaultValue;
    }
    return def.innerType._zod.run(payload, ctx);
  };
});
var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "values", () => {
    const v = def.innerType._zod.values;
    return v ? new Set([...v].filter((x2) => x2 !== void 0)) : void 0;
  });
  inst._zod.parse = (payload, ctx) => {
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then((result2) => handleNonOptionalResult(result2, inst));
    }
    return handleNonOptionalResult(result, inst);
  };
});
function handleNonOptionalResult(payload, inst) {
  if (!payload.issues.length && payload.value === void 0) {
    payload.issues.push({
      code: "invalid_type",
      expected: "nonoptional",
      input: payload.value,
      inst
    });
  }
  return payload;
}
var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      throw new $ZodEncodeError("ZodSuccess");
    }
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then((result2) => {
        payload.value = result2.issues.length === 0;
        return payload;
      });
    }
    payload.value = result.issues.length === 0;
    return payload;
  };
});
var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      return def.innerType._zod.run(payload, ctx);
    }
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then((result2) => {
        payload.value = result2.value;
        if (result2.issues.length) {
          payload.value = def.catchValue({
            ...payload,
            error: {
              issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))
            },
            input: payload.value
          });
          payload.issues = [];
          payload.fallback = true;
        }
        return payload;
      });
    }
    payload.value = result.value;
    if (result.issues.length) {
      payload.value = def.catchValue({
        ...payload,
        error: {
          issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
        },
        input: payload.value
      });
      payload.issues = [];
      payload.fallback = true;
    }
    return payload;
  };
});
var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) {
      payload.issues.push({
        input: payload.value,
        inst,
        expected: "nan",
        code: "invalid_type"
      });
      return payload;
    }
    return payload;
  };
});
var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "values", () => def.in._zod.values);
  defineLazy(inst._zod, "optin", () => def.in._zod.optin);
  defineLazy(inst._zod, "optout", () => def.out._zod.optout);
  defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      const right = def.out._zod.run(payload, ctx);
      if (right instanceof Promise) {
        return right.then((right2) => handlePipeResult(right2, def.in, ctx));
      }
      return handlePipeResult(right, def.in, ctx);
    }
    const left = def.in._zod.run(payload, ctx);
    if (left instanceof Promise) {
      return left.then((left2) => handlePipeResult(left2, def.out, ctx));
    }
    return handlePipeResult(left, def.out, ctx);
  };
});
function handlePipeResult(left, next, ctx) {
  if (left.issues.length) {
    left.aborted = true;
    return left;
  }
  return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);
}
var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "values", () => def.in._zod.values);
  defineLazy(inst._zod, "optin", () => def.in._zod.optin);
  defineLazy(inst._zod, "optout", () => def.out._zod.optout);
  defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
  inst._zod.parse = (payload, ctx) => {
    const direction = ctx.direction || "forward";
    if (direction === "forward") {
      const left = def.in._zod.run(payload, ctx);
      if (left instanceof Promise) {
        return left.then((left2) => handleCodecAResult(left2, def, ctx));
      }
      return handleCodecAResult(left, def, ctx);
    } else {
      const right = def.out._zod.run(payload, ctx);
      if (right instanceof Promise) {
        return right.then((right2) => handleCodecAResult(right2, def, ctx));
      }
      return handleCodecAResult(right, def, ctx);
    }
  };
});
function handleCodecAResult(result, def, ctx) {
  if (result.issues.length) {
    result.aborted = true;
    return result;
  }
  const direction = ctx.direction || "forward";
  if (direction === "forward") {
    const transformed = def.transform(result.value, result);
    if (transformed instanceof Promise) {
      return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));
    }
    return handleCodecTxResult(result, transformed, def.out, ctx);
  } else {
    const transformed = def.reverseTransform(result.value, result);
    if (transformed instanceof Promise) {
      return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));
    }
    return handleCodecTxResult(result, transformed, def.in, ctx);
  }
}
function handleCodecTxResult(left, value, nextSchema, ctx) {
  if (left.issues.length) {
    left.aborted = true;
    return left;
  }
  return nextSchema._zod.run({ value, issues: left.issues }, ctx);
}
var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) => {
  $ZodPipe.init(inst, def);
});
var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin);
  defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      return def.innerType._zod.run(payload, ctx);
    }
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then(handleReadonlyResult);
    }
    return handleReadonlyResult(result);
  };
});
function handleReadonlyResult(payload) {
  payload.value = Object.freeze(payload.value);
  return payload;
}
var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => {
  $ZodType.init(inst, def);
  const regexParts = [];
  for (const part of def.parts) {
    if (typeof part === "object" && part !== null) {
      if (!part._zod.pattern) {
        throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);
      }
      const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;
      if (!source)
        throw new Error(`Invalid template literal part: ${part._zod.traits}`);
      const start = source.startsWith("^") ? 1 : 0;
      const end = source.endsWith("$") ? source.length - 1 : source.length;
      regexParts.push(source.slice(start, end));
    } else if (part === null || primitiveTypes.has(typeof part)) {
      regexParts.push(escapeRegex(`${part}`));
    } else {
      throw new Error(`Invalid template literal part: ${part}`);
    }
  }
  inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`);
  inst._zod.parse = (payload, _ctx) => {
    if (typeof payload.value !== "string") {
      payload.issues.push({
        input: payload.value,
        inst,
        expected: "string",
        code: "invalid_type"
      });
      return payload;
    }
    inst._zod.pattern.lastIndex = 0;
    if (!inst._zod.pattern.test(payload.value)) {
      payload.issues.push({
        input: payload.value,
        inst,
        code: "invalid_format",
        format: def.format ?? "template_literal",
        pattern: inst._zod.pattern.source
      });
      return payload;
    }
    return payload;
  };
});
var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => {
  $ZodType.init(inst, def);
  inst._def = def;
  inst._zod.def = def;
  inst.implement = (func) => {
    if (typeof func !== "function") {
      throw new Error("implement() must be called with a function");
    }
    return function(...args) {
      const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;
      const result = Reflect.apply(func, this, parsedArgs);
      if (inst._def.output) {
        return parse(inst._def.output, result);
      }
      return result;
    };
  };
  inst.implementAsync = (func) => {
    if (typeof func !== "function") {
      throw new Error("implementAsync() must be called with a function");
    }
    return async function(...args) {
      const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;
      const result = await Reflect.apply(func, this, parsedArgs);
      if (inst._def.output) {
        return await parseAsync(inst._def.output, result);
      }
      return result;
    };
  };
  inst._zod.parse = (payload, _ctx) => {
    if (typeof payload.value !== "function") {
      payload.issues.push({
        code: "invalid_type",
        expected: "function",
        input: payload.value,
        inst
      });
      return payload;
    }
    const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise";
    if (hasPromiseOutput) {
      payload.value = inst.implementAsync(payload.value);
    } else {
      payload.value = inst.implement(payload.value);
    }
    return payload;
  };
  inst.input = (...args) => {
    const F2 = inst.constructor;
    if (Array.isArray(args[0])) {
      return new F2({
        type: "function",
        input: new $ZodTuple({
          type: "tuple",
          items: args[0],
          rest: args[1]
        }),
        output: inst._def.output
      });
    }
    return new F2({
      type: "function",
      input: args[0],
      output: inst._def.output
    });
  };
  inst.output = (output) => {
    const F2 = inst.constructor;
    return new F2({
      type: "function",
      input: inst._def.input,
      output
    });
  };
  return inst;
});
var $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));
  };
});
var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "innerType", () => {
    const d = def;
    if (!d._cachedInner)
      d._cachedInner = def.getter();
    return d._cachedInner;
  });
  defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern);
  defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues);
  defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0);
  defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0);
  inst._zod.parse = (payload, ctx) => {
    const inner = inst._zod.innerType;
    return inner._zod.run(payload, ctx);
  };
});
var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
  $ZodCheck.init(inst, def);
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _) => {
    return payload;
  };
  inst._zod.check = (payload) => {
    const input = payload.value;
    const r2 = def.fn(input);
    if (r2 instanceof Promise) {
      return r2.then((r3) => handleRefineResult(r3, payload, input, inst));
    }
    handleRefineResult(r2, payload, input, inst);
    return;
  };
});
function handleRefineResult(result, payload, input, inst) {
  if (!result) {
    const _iss = {
      code: "custom",
      input,
      inst,
      // incorporates params.error into issue reporting
      path: [...inst._zod.def.path ?? []],
      // incorporates params.error into issue reporting
      continue: !inst._zod.def.abort
      // params: inst._zod.def.params,
    };
    if (inst._zod.def.params)
      _iss.params = inst._zod.def.params;
    payload.issues.push(issue(_iss));
  }
}

// node_modules/zod/v4/locales/index.js
var locales_exports = {};
__export(locales_exports, {
  ar: () => ar_default,
  az: () => az_default,
  be: () => be_default,
  bg: () => bg_default,
  ca: () => ca_default,
  cs: () => cs_default,
  da: () => da_default,
  de: () => de_default,
  el: () => el_default,
  en: () => en_default,
  eo: () => eo_default,
  es: () => es_default,
  fa: () => fa_default,
  fi: () => fi_default,
  fr: () => fr_default,
  frCA: () => fr_CA_default,
  he: () => he_default,
  hr: () => hr_default,
  hu: () => hu_default,
  hy: () => hy_default,
  id: () => id_default,
  is: () => is_default,
  it: () => it_default,
  ja: () => ja_default,
  ka: () => ka_default,
  kh: () => kh_default,
  km: () => km_default,
  ko: () => ko_default,
  lt: () => lt_default,
  mk: () => mk_default,
  ms: () => ms_default,
  nl: () => nl_default,
  no: () => no_default,
  ota: () => ota_default,
  pl: () => pl_default,
  ps: () => ps_default,
  pt: () => pt_default,
  ro: () => ro_default,
  ru: () => ru_default,
  sl: () => sl_default,
  sv: () => sv_default,
  ta: () => ta_default,
  th: () => th_default,
  tr: () => tr_default,
  ua: () => ua_default,
  uk: () => uk_default,
  ur: () => ur_default,
  uz: () => uz_default,
  vi: () => vi_default,
  yo: () => yo_default,
  zhCN: () => zh_CN_default,
  zhTW: () => zh_TW_default
});

// node_modules/zod/v4/locales/ar.js
var error = () => {
  const Sizable = {
    string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" },
    file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" },
    array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" },
    set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0645\u062F\u062E\u0644",
    email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",
    url: "\u0631\u0627\u0628\u0637",
    emoji: "\u0625\u064A\u0645\u0648\u062C\u064A",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
    date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
    time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
    duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
    ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4",
    ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6",
    cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",
    cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",
    base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",
    base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",
    json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",
    e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",
    jwt: "JWT",
    template_literal: "\u0645\u062F\u062E\u0644"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`;
        }
        return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`;
        return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"}`;
        return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`;
        if (_issue.format === "ends_with")
          return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`;
        return `${FormatDictionary[_issue.format] ?? issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`;
      }
      case "not_multiple_of":
        return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u0645\u0639\u0631\u0641${issue2.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue2.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue2.keys, "\u060C ")}`;
      case "invalid_key":
        return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`;
      case "invalid_union":
        return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";
      case "invalid_element":
        return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`;
      default:
        return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";
    }
  };
};
function ar_default() {
  return {
    localeError: error()
  };
}

// node_modules/zod/v4/locales/az.js
var error2 = () => {
  const Sizable = {
    string: { unit: "simvol", verb: "olmal\u0131d\u0131r" },
    file: { unit: "bayt", verb: "olmal\u0131d\u0131r" },
    array: { unit: "element", verb: "olmal\u0131d\u0131r" },
    set: { unit: "element", verb: "olmal\u0131d\u0131r" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "email address",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO datetime",
    date: "ISO date",
    time: "ISO time",
    duration: "ISO duration",
    ipv4: "IPv4 address",
    ipv6: "IPv6 address",
    cidrv4: "IPv4 range",
    cidrv6: "IPv6 range",
    base64: "base64-encoded string",
    base64url: "base64url-encoded string",
    json_string: "JSON string",
    e164: "E.164 number",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${issue2.expected}, daxil olan ${received}`;
        }
        return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`;
        return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`;
        return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`;
        if (_issue.format === "ends_with")
          return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`;
        if (_issue.format === "includes")
          return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`;
        if (_issue.format === "regex")
          return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;
        return `Yanl\u0131\u015F ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;
      case "unrecognized_keys":
        return `Tan\u0131nmayan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;
      case "invalid_union":
        return "Yanl\u0131\u015F d\u0259y\u0259r";
      case "invalid_element":
        return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;
      default:
        return `Yanl\u0131\u015F d\u0259y\u0259r`;
    }
  };
};
function az_default() {
  return {
    localeError: error2()
  };
}

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

// node_modules/zod/v4/locales/bg.js
var error4 = () => {
  const Sizable = {
    string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" },
    file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" },
    array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" },
    set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0432\u0445\u043E\u0434",
    email: "\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441",
    url: "URL",
    emoji: "\u0435\u043C\u043E\u0434\u0436\u0438",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \u0432\u0440\u0435\u043C\u0435",
    date: "ISO \u0434\u0430\u0442\u0430",
    time: "ISO \u0432\u0440\u0435\u043C\u0435",
    duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442",
    ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441",
    ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441",
    cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
    cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
    base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",
    base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",
    json_string: "JSON \u043D\u0438\u0437",
    e164: "E.164 \u043D\u043E\u043C\u0435\u0440",
    jwt: "JWT",
    template_literal: "\u0432\u0445\u043E\u0434"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0447\u0438\u0441\u043B\u043E",
    array: "\u043C\u0430\u0441\u0438\u0432"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`;
        }
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${stringifyPrimitive(issue2.values[0])}`;
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`;
        return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${_issue.pattern}`;
        let invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";
        if (_issue.format === "emoji")
          invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";
        if (_issue.format === "datetime")
          invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";
        if (_issue.format === "date")
          invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";
        if (_issue.format === "time")
          invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";
        if (_issue.format === "duration")
          invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";
        return `${invalid_adj} ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue2.keys.length > 1 ? "\u0438" : ""} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u043E\u0432\u0435" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`;
      case "invalid_union":
        return "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434";
      case "invalid_element":
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${issue2.origin}`;
      default:
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434`;
    }
  };
};
function bg_default() {
  return {
    localeError: error4()
  };
}

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

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

// node_modules/zod/v4/locales/da.js
var error7 = () => {
  const Sizable = {
    string: { unit: "tegn", verb: "havde" },
    file: { unit: "bytes", verb: "havde" },
    array: { unit: "elementer", verb: "indeholdt" },
    set: { unit: "elementer", verb: "indeholdt" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "e-mailadresse",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO dato- og klokkesl\xE6t",
    date: "ISO-dato",
    time: "ISO-klokkesl\xE6t",
    duration: "ISO-varighed",
    ipv4: "IPv4-omr\xE5de",
    ipv6: "IPv6-omr\xE5de",
    cidrv4: "IPv4-spektrum",
    cidrv6: "IPv6-spektrum",
    base64: "base64-kodet streng",
    base64url: "base64url-kodet streng",
    json_string: "JSON-streng",
    e164: "E.164-nummer",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN",
    string: "streng",
    number: "tal",
    boolean: "boolean",
    array: "liste",
    object: "objekt",
    set: "s\xE6t",
    file: "fil"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ugyldigt input: forventede instanceof ${issue2.expected}, fik ${received}`;
        }
        return `Ugyldigt input: forventede ${expected}, fik ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ugyldig v\xE6rdi: forventede ${stringifyPrimitive(issue2.values[0])}`;
        return `Ugyldigt valg: forventede en af f\xF8lgende ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        if (sizing)
          return `For stor: forventede ${origin ?? "value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`;
        return `For stor: forventede ${origin ?? "value"} havde ${adj} ${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        if (sizing) {
          return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Ugyldig streng: skal starte med "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Ugyldig streng: skal ende med "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Ugyldig streng: skal indeholde "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Ugyldig streng: skal matche m\xF8nsteret ${_issue.pattern}`;
        return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Ugyldigt tal: skal v\xE6re deleligt med ${issue2.divisor}`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "Ukendte n\xF8gler" : "Ukendt n\xF8gle"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Ugyldig n\xF8gle i ${issue2.origin}`;
      case "invalid_union":
        return "Ugyldigt input: matcher ingen af de tilladte typer";
      case "invalid_element":
        return `Ugyldig v\xE6rdi i ${issue2.origin}`;
      default:
        return `Ugyldigt input`;
    }
  };
};
function da_default() {
  return {
    localeError: error7()
  };
}

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

// node_modules/zod/v4/locales/el.js
var error9 = () => {
  const Sizable = {
    string: { unit: "\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" },
    file: { unit: "bytes", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" },
    array: { unit: "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" },
    set: { unit: "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" },
    map: { unit: "\u03BA\u03B1\u03C4\u03B1\u03C7\u03C9\u03C1\u03AE\u03C3\u03B5\u03B9\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2",
    email: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 email",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1 \u03BA\u03B1\u03B9 \u03CE\u03C1\u03B1",
    date: "ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1",
    time: "ISO \u03CE\u03C1\u03B1",
    duration: "ISO \u03B4\u03B9\u03AC\u03C1\u03BA\u03B5\u03B9\u03B1",
    ipv4: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv4",
    ipv6: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv6",
    mac: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 MAC",
    cidrv4: "\u03B5\u03CD\u03C1\u03BF\u03C2 IPv4",
    cidrv6: "\u03B5\u03CD\u03C1\u03BF\u03C2 IPv6",
    base64: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64",
    base64url: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url",
    json_string: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON",
    e164: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164",
    jwt: "JWT",
    template_literal: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (typeof issue2.expected === "string" && /^[A-Z]/.test(issue2.expected)) {
          return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD instanceof ${issue2.expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${received}`;
        }
        return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${stringifyPrimitive(issue2.values[0])}`;
        return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03C0\u03B9\u03BB\u03BF\u03B3\u03AE: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD \u03AD\u03BD\u03B1 \u03B1\u03C0\u03CC ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin ?? "\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1"}`;
        return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin ?? "\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03BE\u03B5\u03BA\u03B9\u03BD\u03AC \u03BC\u03B5 "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B5\u03BB\u03B5\u03B9\u03CE\u03BD\u03B5\u03B9 \u03BC\u03B5 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C0\u03B5\u03C1\u03B9\u03AD\u03C7\u03B5\u03B9 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B1\u03B9\u03C1\u03B9\u03AC\u03B6\u03B5\u03B9 \u03BC\u03B5 \u03C4\u03BF \u03BC\u03BF\u03C4\u03AF\u03B2\u03BF ${_issue.pattern}`;
        return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF: ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF\u03C2 \u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 \u03C0\u03BF\u03BB\u03BB\u03B1\u03C0\u03BB\u03AC\u03C3\u03B9\u03BF \u03C4\u03BF\u03C5 ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${issue2.keys.length > 1 ? "\u03B1" : "\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${issue2.keys.length > 1 ? "\u03B9\u03AC" : "\u03AF"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${issue2.origin}`;
      case "invalid_union":
        return "\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2";
      case "invalid_element":
        return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C4\u03B9\u03BC\u03AE \u03C3\u03C4\u03BF ${issue2.origin}`;
      default:
        return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2`;
    }
  };
};
function el_default() {
  return {
    localeError: error9()
  };
}

// node_modules/zod/v4/locales/en.js
var error10 = () => {
  const Sizable = {
    string: { unit: "characters", verb: "to have" },
    file: { unit: "bytes", verb: "to have" },
    array: { unit: "items", verb: "to have" },
    set: { unit: "items", verb: "to have" },
    map: { unit: "entries", verb: "to have" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "email address",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO datetime",
    date: "ISO date",
    time: "ISO time",
    duration: "ISO duration",
    ipv4: "IPv4 address",
    ipv6: "IPv6 address",
    mac: "MAC address",
    cidrv4: "IPv4 range",
    cidrv6: "IPv6 range",
    base64: "base64-encoded string",
    base64url: "base64url-encoded string",
    json_string: "JSON string",
    e164: "E.164 number",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    // Compatibility: "nan" -> "NaN" for display
    nan: "NaN"
    // All other type names omitted - they fall back to raw values via ?? operator
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        return `Invalid input: expected ${expected}, received ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;
        return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`;
        return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Invalid string: must start with "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Invalid string: must end with "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Invalid string: must include "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Invalid string: must match pattern ${_issue.pattern}`;
        return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Invalid number: must be a multiple of ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Invalid key in ${issue2.origin}`;
      case "invalid_union":
        if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) {
          const opts = issue2.options.map((o) => `'${o}'`).join(" | ");
          return `Invalid discriminator value. Expected ${opts}`;
        }
        return "Invalid input";
      case "invalid_element":
        return `Invalid value in ${issue2.origin}`;
      default:
        return `Invalid input`;
    }
  };
};
function en_default() {
  return {
    localeError: error10()
  };
}

// node_modules/zod/v4/locales/eo.js
var error11 = () => {
  const Sizable = {
    string: { unit: "karaktrojn", verb: "havi" },
    file: { unit: "bajtojn", verb: "havi" },
    array: { unit: "elementojn", verb: "havi" },
    set: { unit: "elementojn", verb: "havi" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "enigo",
    email: "retadreso",
    url: "URL",
    emoji: "emo\u011Dio",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO-datotempo",
    date: "ISO-dato",
    time: "ISO-tempo",
    duration: "ISO-da\u016Dro",
    ipv4: "IPv4-adreso",
    ipv6: "IPv6-adreso",
    cidrv4: "IPv4-rango",
    cidrv6: "IPv6-rango",
    base64: "64-ume kodita karaktraro",
    base64url: "URL-64-ume kodita karaktraro",
    json_string: "JSON-karaktraro",
    e164: "E.164-nombro",
    jwt: "JWT",
    template_literal: "enigo"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "nombro",
    array: "tabelo",
    null: "senvalora"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Nevalida enigo: atendi\u011Dis instanceof ${issue2.expected}, ricevi\u011Dis ${received}`;
        }
        return `Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`;
        return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementojn"}`;
        return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`;
        return `Nevalida ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Nekonata${issue2.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Nevalida \u015Dlosilo en ${issue2.origin}`;
      case "invalid_union":
        return "Nevalida enigo";
      case "invalid_element":
        return `Nevalida valoro en ${issue2.origin}`;
      default:
        return `Nevalida enigo`;
    }
  };
};
function eo_default() {
  return {
    localeError: error11()
  };
}

// node_modules/zod/v4/locales/es.js
var error12 = () => {
  const Sizable = {
    string: { unit: "caracteres", verb: "tener" },
    file: { unit: "bytes", verb: "tener" },
    array: { unit: "elementos", verb: "tener" },
    set: { unit: "elementos", verb: "tener" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "entrada",
    email: "direcci\xF3n de correo electr\xF3nico",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "fecha y hora ISO",
    date: "fecha ISO",
    time: "hora ISO",
    duration: "duraci\xF3n ISO",
    ipv4: "direcci\xF3n IPv4",
    ipv6: "direcci\xF3n IPv6",
    cidrv4: "rango IPv4",
    cidrv6: "rango IPv6",
    base64: "cadena codificada en base64",
    base64url: "URL codificada en base64",
    json_string: "cadena JSON",
    e164: "n\xFAmero E.164",
    jwt: "JWT",
    template_literal: "entrada"
  };
  const TypeDictionary = {
    nan: "NaN",
    string: "texto",
    number: "n\xFAmero",
    boolean: "booleano",
    array: "arreglo",
    object: "objeto",
    set: "conjunto",
    file: "archivo",
    date: "fecha",
    bigint: "n\xFAmero grande",
    symbol: "s\xEDmbolo",
    undefined: "indefinido",
    null: "nulo",
    function: "funci\xF3n",
    map: "mapa",
    record: "registro",
    tuple: "tupla",
    enum: "enumeraci\xF3n",
    union: "uni\xF3n",
    literal: "literal",
    promise: "promesa",
    void: "vac\xEDo",
    never: "nunca",
    unknown: "desconocido",
    any: "cualquiera"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Entrada inv\xE1lida: se esperaba instanceof ${issue2.expected}, recibido ${received}`;
        }
        return `Entrada inv\xE1lida: se esperaba ${expected}, recibido ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`;
        return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        if (sizing)
          return `Demasiado grande: se esperaba que ${origin ?? "valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`;
        return `Demasiado grande: se esperaba que ${origin ?? "valor"} fuera ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        if (sizing) {
          return `Demasiado peque\xF1o: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Demasiado peque\xF1o: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`;
        return `Inv\xE1lido ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Llave inv\xE1lida en ${TypeDictionary[issue2.origin] ?? issue2.origin}`;
      case "invalid_union":
        return "Entrada inv\xE1lida";
      case "invalid_element":
        return `Valor inv\xE1lido en ${TypeDictionary[issue2.origin] ?? issue2.origin}`;
      default:
        return `Entrada inv\xE1lida`;
    }
  };
};
function es_default() {
  return {
    localeError: error12()
  };
}

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

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

// node_modules/zod/v4/locales/fr.js
var error15 = () => {
  const Sizable = {
    string: { unit: "caract\xE8res", verb: "avoir" },
    file: { unit: "octets", verb: "avoir" },
    array: { unit: "\xE9l\xE9ments", verb: "avoir" },
    set: { unit: "\xE9l\xE9ments", verb: "avoir" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "entr\xE9e",
    email: "adresse e-mail",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "date et heure ISO",
    date: "date ISO",
    time: "heure ISO",
    duration: "dur\xE9e ISO",
    ipv4: "adresse IPv4",
    ipv6: "adresse IPv6",
    cidrv4: "plage IPv4",
    cidrv6: "plage IPv6",
    base64: "cha\xEEne encod\xE9e en base64",
    base64url: "cha\xEEne encod\xE9e en base64url",
    json_string: "cha\xEEne JSON",
    e164: "num\xE9ro E.164",
    jwt: "JWT",
    template_literal: "entr\xE9e"
  };
  const TypeDictionary = {
    string: "cha\xEEne",
    number: "nombre",
    int: "entier",
    boolean: "bool\xE9en",
    bigint: "grand entier",
    symbol: "symbole",
    undefined: "ind\xE9fini",
    null: "null",
    never: "jamais",
    void: "vide",
    date: "date",
    array: "tableau",
    object: "objet",
    tuple: "tuple",
    record: "enregistrement",
    map: "carte",
    set: "ensemble",
    file: "fichier",
    nonoptional: "non-optionnel",
    nan: "NaN",
    function: "fonction"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`;
        }
        return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`;
        return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Trop grand : ${TypeDictionary[issue2.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`;
        return `Trop grand : ${TypeDictionary[issue2.origin] ?? "valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Trop petit : ${TypeDictionary[issue2.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        return `Trop petit : ${TypeDictionary[issue2.origin] ?? "valeur"} doit \xEAtre ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`;
        return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`;
      }
      case "not_multiple_of":
        return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Cl\xE9 invalide dans ${issue2.origin}`;
      case "invalid_union":
        return "Entr\xE9e invalide";
      case "invalid_element":
        return `Valeur invalide dans ${issue2.origin}`;
      default:
        return `Entr\xE9e invalide`;
    }
  };
};
function fr_default() {
  return {
    localeError: error15()
  };
}

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

// node_modules/zod/v4/locales/he.js
var error17 = () => {
  const TypeNames = {
    string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" },
    number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" },
    boolean: { label: "\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9", gender: "m" },
    bigint: { label: "BigInt", gender: "m" },
    date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA", gender: "m" },
    array: { label: "\u05DE\u05E2\u05E8\u05DA", gender: "m" },
    object: { label: "\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8", gender: "m" },
    null: { label: "\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)", gender: "m" },
    undefined: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)", gender: "m" },
    symbol: { label: "\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)", gender: "m" },
    function: { label: "\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4", gender: "f" },
    map: { label: "\u05DE\u05E4\u05D4 (Map)", gender: "f" },
    set: { label: "\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)", gender: "f" },
    file: { label: "\u05E7\u05D5\u05D1\u05E5", gender: "m" },
    promise: { label: "Promise", gender: "m" },
    NaN: { label: "NaN", gender: "m" },
    unknown: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2", gender: "m" },
    value: { label: "\u05E2\u05E8\u05DA", gender: "m" }
  };
  const Sizable = {
    string: { unit: "\u05EA\u05D5\u05D5\u05D9\u05DD", shortLabel: "\u05E7\u05E6\u05E8", longLabel: "\u05D0\u05E8\u05D5\u05DA" },
    file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" },
    array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" },
    set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" },
    number: { unit: "", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }
    // no unit
  };
  const typeEntry = (t2) => t2 ? TypeNames[t2] : void 0;
  const typeLabel = (t2) => {
    const e2 = typeEntry(t2);
    if (e2)
      return e2.label;
    return t2 ?? TypeNames.unknown.label;
  };
  const withDefinite = (t2) => `\u05D4${typeLabel(t2)}`;
  const verbFor = (t2) => {
    const e2 = typeEntry(t2);
    const gender = e2?.gender ?? "m";
    return gender === "f" ? "\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA" : "\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA";
  };
  const getSizing = (origin) => {
    if (!origin)
      return null;
    return Sizable[origin] ?? null;
  };
  const FormatDictionary = {
    regex: { label: "\u05E7\u05DC\u05D8", gender: "m" },
    email: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC", gender: "f" },
    url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" },
    emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" },
    uuid: { label: "UUID", gender: "m" },
    nanoid: { label: "nanoid", gender: "m" },
    guid: { label: "GUID", gender: "m" },
    cuid: { label: "cuid", gender: "m" },
    cuid2: { label: "cuid2", gender: "m" },
    ulid: { label: "ULID", gender: "m" },
    xid: { label: "XID", gender: "m" },
    ksuid: { label: "KSUID", gender: "m" },
    datetime: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO", gender: "m" },
    date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO", gender: "m" },
    time: { label: "\u05D6\u05DE\u05DF ISO", gender: "m" },
    duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" },
    ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" },
    ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" },
    cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" },
    cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" },
    base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" },
    base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" },
    json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" },
    e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" },
    jwt: { label: "JWT", gender: "m" },
    ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" },
    includes: { label: "\u05E7\u05DC\u05D8", gender: "m" },
    lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" },
    starts_with: { label: "\u05E7\u05DC\u05D8", gender: "m" },
    uppercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expectedKey = issue2.expected;
        const expected = TypeDictionary[expectedKey ?? ""] ?? typeLabel(expectedKey);
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`;
        }
        return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`;
      }
      case "invalid_value": {
        if (issue2.values.length === 1) {
          return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${stringifyPrimitive(issue2.values[0])}`;
        }
        const stringified = issue2.values.map((v) => stringifyPrimitive(v));
        if (issue2.values.length === 2) {
          return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${stringified[0]} \u05D0\u05D5 ${stringified[1]}`;
        }
        const lastValue = stringified[stringified.length - 1];
        const restValues = stringified.slice(0, -1).join(", ");
        return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${restValues} \u05D0\u05D5 ${lastValue}`;
      }
      case "too_big": {
        const sizing = getSizing(issue2.origin);
        const subject = withDefinite(issue2.origin ?? "value");
        if (issue2.origin === "string") {
          return `${sizing?.longLabel ?? "\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.maximum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA" : "\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();
        }
        if (issue2.origin === "number") {
          const comparison = issue2.inclusive ? `\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.maximum}` : `\u05E7\u05D8\u05DF \u05DE-${issue2.maximum}`;
          return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`;
        }
        if (issue2.origin === "array" || issue2.origin === "set") {
          const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA";
          const comparison = issue2.inclusive ? `${issue2.maximum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA` : `\u05E4\u05D7\u05D5\u05EA \u05DE-${issue2.maximum} ${sizing?.unit ?? ""}`;
          return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim();
        }
        const adj = issue2.inclusive ? "<=" : "<";
        const be = verbFor(issue2.origin ?? "value");
        if (sizing?.unit) {
          return `${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
        }
        return `${sizing?.longLabel ?? "\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const sizing = getSizing(issue2.origin);
        const subject = withDefinite(issue2.origin ?? "value");
        if (issue2.origin === "string") {
          return `${sizing?.shortLabel ?? "\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.minimum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8" : "\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();
        }
        if (issue2.origin === "number") {
          const comparison = issue2.inclusive ? `\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.minimum}` : `\u05D2\u05D3\u05D5\u05DC \u05DE-${issue2.minimum}`;
          return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`;
        }
        if (issue2.origin === "array" || issue2.origin === "set") {
          const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA";
          if (issue2.minimum === 1 && issue2.inclusive) {
            const singularPhrase = issue2.origin === "set" ? "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3" : "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3";
            return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${singularPhrase}`;
          }
          const comparison = issue2.inclusive ? `${issue2.minimum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8` : `\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue2.minimum} ${sizing?.unit ?? ""}`;
          return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim();
        }
        const adj = issue2.inclusive ? ">=" : ">";
        const be = verbFor(issue2.origin ?? "value");
        if (sizing?.unit) {
          return `${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `${sizing?.shortLabel ?? "\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`;
        const nounEntry = FormatDictionary[_issue.format];
        const noun = nounEntry?.label ?? _issue.format;
        const gender = nounEntry?.gender ?? "m";
        const adjective = gender === "f" ? "\u05EA\u05E7\u05D9\u05E0\u05D4" : "\u05EA\u05E7\u05D9\u05DF";
        return `${noun} \u05DC\u05D0 ${adjective}`;
      }
      case "not_multiple_of":
        return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u05DE\u05E4\u05EA\u05D7${issue2.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key": {
        return `\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8`;
      }
      case "invalid_union":
        return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";
      case "invalid_element": {
        const place = withDefinite(issue2.origin ?? "array");
        return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${place}`;
      }
      default:
        return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`;
    }
  };
};
function he_default() {
  return {
    localeError: error17()
  };
}

// node_modules/zod/v4/locales/hr.js
var error18 = () => {
  const Sizable = {
    string: { unit: "znakova", verb: "imati" },
    file: { unit: "bajtova", verb: "imati" },
    array: { unit: "stavki", verb: "imati" },
    set: { unit: "stavki", verb: "imati" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "unos",
    email: "email adresa",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO datum i vrijeme",
    date: "ISO datum",
    time: "ISO vrijeme",
    duration: "ISO trajanje",
    ipv4: "IPv4 adresa",
    ipv6: "IPv6 adresa",
    cidrv4: "IPv4 raspon",
    cidrv6: "IPv6 raspon",
    base64: "base64 kodirani tekst",
    base64url: "base64url kodirani tekst",
    json_string: "JSON tekst",
    e164: "E.164 broj",
    jwt: "JWT",
    template_literal: "unos"
  };
  const TypeDictionary = {
    nan: "NaN",
    string: "tekst",
    number: "broj",
    boolean: "boolean",
    array: "niz",
    object: "objekt",
    set: "skup",
    file: "datoteka",
    date: "datum",
    bigint: "bigint",
    symbol: "simbol",
    undefined: "undefined",
    null: "null",
    function: "funkcija",
    map: "mapa"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Neispravan unos: o\u010Dekuje se instanceof ${issue2.expected}, a primljeno je ${received}`;
        }
        return `Neispravan unos: o\u010Dekuje se ${expected}, a primljeno je ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Neispravna vrijednost: o\u010Dekivano ${stringifyPrimitive(issue2.values[0])}`;
        return `Neispravna opcija: o\u010Dekivano jedno od ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        if (sizing)
          return `Preveliko: o\u010Dekivano da ${origin ?? "vrijednost"} ima ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemenata"}`;
        return `Preveliko: o\u010Dekivano da ${origin ?? "vrijednost"} bude ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        if (sizing) {
          return `Premalo: o\u010Dekivano da ${origin} ima ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Premalo: o\u010Dekivano da ${origin} bude ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Neispravan tekst: mora zapo\u010Dinjati s "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Neispravan tekst: mora zavr\u0161avati s "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Neispravan tekst: mora sadr\u017Eavati "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Neispravan tekst: mora odgovarati uzorku ${_issue.pattern}`;
        return `Neispravna ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Neispravan broj: mora biti vi\u0161ekratnik od ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Neprepoznat${issue2.keys.length > 1 ? "i klju\u010Devi" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Neispravan klju\u010D u ${TypeDictionary[issue2.origin] ?? issue2.origin}`;
      case "invalid_union":
        return "Neispravan unos";
      case "invalid_element":
        return `Neispravna vrijednost u ${TypeDictionary[issue2.origin] ?? issue2.origin}`;
      default:
        return `Neispravan unos`;
    }
  };
};
function hr_default() {
  return {
    localeError: error18()
  };
}

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

// node_modules/zod/v4/locales/hy.js
function getArmenianPlural(count, one, many) {
  return Math.abs(count) === 1 ? one : many;
}
function withDefiniteArticle(word) {
  if (!word)
    return "";
  const vowels = ["\u0561", "\u0565", "\u0568", "\u056B", "\u0578", "\u0578\u0582", "\u0585"];
  const lastChar = word[word.length - 1];
  return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568");
}
var error20 = () => {
  const Sizable = {
    string: {
      unit: {
        one: "\u0576\u0577\u0561\u0576",
        many: "\u0576\u0577\u0561\u0576\u0576\u0565\u0580"
      },
      verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C"
    },
    file: {
      unit: {
        one: "\u0562\u0561\u0575\u0569",
        many: "\u0562\u0561\u0575\u0569\u0565\u0580"
      },
      verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C"
    },
    array: {
      unit: {
        one: "\u057F\u0561\u0580\u0580",
        many: "\u057F\u0561\u0580\u0580\u0565\u0580"
      },
      verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C"
    },
    set: {
      unit: {
        one: "\u057F\u0561\u0580\u0580",
        many: "\u057F\u0561\u0580\u0580\u0565\u0580"
      },
      verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C"
    }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0574\u0578\u0582\u057F\u0584",
    email: "\u0567\u056C. \u0570\u0561\u057D\u0581\u0565",
    url: "URL",
    emoji: "\u0567\u0574\u0578\u057B\u056B",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574",
    date: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E",
    time: "ISO \u056A\u0561\u0574",
    duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576",
    ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565",
    ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565",
    cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",
    cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",
    base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",
    base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",
    json_string: "JSON \u057F\u0578\u0572",
    e164: "E.164 \u0570\u0561\u0574\u0561\u0580",
    jwt: "JWT",
    template_literal: "\u0574\u0578\u0582\u057F\u0584"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0569\u056B\u057E",
    array: "\u0566\u0561\u0576\u0563\u057E\u0561\u056E"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${issue2.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`;
        }
        return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${stringifyPrimitive(issue2.values[1])}`;
        return `\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const maxValue = Number(issue2.maximum);
          const unit = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many);
          return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.maximum.toString()} ${unit}`;
        }
        return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const minValue = Number(issue2.minimum);
          const unit = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many);
          return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.minimum.toString()} ${unit}`;
        }
        return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056C\u056B\u0576\u056B ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${_issue.prefix}"-\u0578\u057E`;
        if (_issue.format === "ends_with")
          return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${_issue.suffix}"-\u0578\u057E`;
        if (_issue.format === "includes")
          return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${_issue.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`;
        return `\u054D\u056D\u0561\u056C ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${issue2.divisor}-\u056B`;
      case "unrecognized_keys":
        return `\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue2.keys.length > 1 ? "\u0576\u0565\u0580" : ""}. ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`;
      case "invalid_union":
        return "\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574";
      case "invalid_element":
        return `\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`;
      default:
        return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574`;
    }
  };
};
function hy_default() {
  return {
    localeError: error20()
  };
}

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

// node_modules/zod/v4/locales/is.js
var error22 = () => {
  const Sizable = {
    string: { unit: "stafi", verb: "a\xF0 hafa" },
    file: { unit: "b\xE6ti", verb: "a\xF0 hafa" },
    array: { unit: "hluti", verb: "a\xF0 hafa" },
    set: { unit: "hluti", verb: "a\xF0 hafa" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "gildi",
    email: "netfang",
    url: "vefsl\xF3\xF0",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO dagsetning og t\xEDmi",
    date: "ISO dagsetning",
    time: "ISO t\xEDmi",
    duration: "ISO t\xEDmalengd",
    ipv4: "IPv4 address",
    ipv6: "IPv6 address",
    cidrv4: "IPv4 range",
    cidrv6: "IPv6 range",
    base64: "base64-encoded strengur",
    base64url: "base64url-encoded strengur",
    json_string: "JSON strengur",
    e164: "E.164 t\xF6lugildi",
    jwt: "JWT",
    template_literal: "gildi"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "n\xFAmer",
    array: "fylki"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera instanceof ${issue2.expected}`;
        }
        return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera ${expected}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Rangt gildi: gert r\xE1\xF0 fyrir ${stringifyPrimitive(issue2.values[0])}`;
        return `\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} hafi ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "hluti"}`;
        return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} s\xE9 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} s\xE9 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${_issue.pattern}`;
        return `Rangt ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\xD3\xFEekkt ${issue2.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Rangur lykill \xED ${issue2.origin}`;
      case "invalid_union":
        return "Rangt gildi";
      case "invalid_element":
        return `Rangt gildi \xED ${issue2.origin}`;
      default:
        return `Rangt gildi`;
    }
  };
};
function is_default() {
  return {
    localeError: error22()
  };
}

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

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

// node_modules/zod/v4/locales/ka.js
var error25 = () => {
  const Sizable = {
    string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" },
    file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" },
    array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" },
    set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0",
    email: "\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",
    url: "URL",
    emoji: "\u10D4\u10DB\u10DD\u10EF\u10D8",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD",
    date: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8",
    time: "\u10D3\u10E0\u10DD",
    duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0",
    ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",
    ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",
    cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",
    cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",
    base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",
    base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",
    json_string: "JSON \u10D5\u10D4\u10DA\u10D8",
    e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8",
    jwt: "JWT",
    template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8",
    string: "\u10D5\u10D4\u10DA\u10D8",
    boolean: "\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8",
    function: "\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0",
    array: "\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${issue2.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`;
        }
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${stringifyPrimitive(issue2.values[0])}`;
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${joinValues(issue2.values, "|")}-\u10D3\u10D0\u10DC`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
        return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.prefix}"-\u10D8\u10D7`;
        }
        if (_issue.format === "ends_with")
          return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.suffix}"-\u10D8\u10D7`;
        if (_issue.format === "includes")
          return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${_issue.includes}"-\u10E1`;
        if (_issue.format === "regex")
          return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${_issue.pattern}`;
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${issue2.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`;
      case "unrecognized_keys":
        return `\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${issue2.keys.length > 1 ? "\u10D4\u10D1\u10D8" : "\u10D8"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue2.origin}-\u10E8\u10D8`;
      case "invalid_union":
        return "\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0";
      case "invalid_element":
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${issue2.origin}-\u10E8\u10D8`;
      default:
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0`;
    }
  };
};
function ka_default() {
  return {
    localeError: error25()
  };
}

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

// node_modules/zod/v4/locales/kh.js
function kh_default() {
  return km_default();
}

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

// node_modules/zod/v4/locales/lt.js
var capitalizeFirstCharacter = (text) => {
  return text.charAt(0).toUpperCase() + text.slice(1);
};
function getUnitTypeFromNumber(number4) {
  const abs = Math.abs(number4);
  const last = abs % 10;
  const last2 = abs % 100;
  if (last2 >= 11 && last2 <= 19 || last === 0)
    return "many";
  if (last === 1)
    return "one";
  return "few";
}
var error28 = () => {
  const Sizable = {
    string: {
      unit: {
        one: "simbolis",
        few: "simboliai",
        many: "simboli\u0173"
      },
      verb: {
        smaller: {
          inclusive: "turi b\u016Bti ne ilgesn\u0117 kaip",
          notInclusive: "turi b\u016Bti trumpesn\u0117 kaip"
        },
        bigger: {
          inclusive: "turi b\u016Bti ne trumpesn\u0117 kaip",
          notInclusive: "turi b\u016Bti ilgesn\u0117 kaip"
        }
      }
    },
    file: {
      unit: {
        one: "baitas",
        few: "baitai",
        many: "bait\u0173"
      },
      verb: {
        smaller: {
          inclusive: "turi b\u016Bti ne didesnis kaip",
          notInclusive: "turi b\u016Bti ma\u017Eesnis kaip"
        },
        bigger: {
          inclusive: "turi b\u016Bti ne ma\u017Eesnis kaip",
          notInclusive: "turi b\u016Bti didesnis kaip"
        }
      }
    },
    array: {
      unit: {
        one: "element\u0105",
        few: "elementus",
        many: "element\u0173"
      },
      verb: {
        smaller: {
          inclusive: "turi tur\u0117ti ne daugiau kaip",
          notInclusive: "turi tur\u0117ti ma\u017Eiau kaip"
        },
        bigger: {
          inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip",
          notInclusive: "turi tur\u0117ti daugiau kaip"
        }
      }
    },
    set: {
      unit: {
        one: "element\u0105",
        few: "elementus",
        many: "element\u0173"
      },
      verb: {
        smaller: {
          inclusive: "turi tur\u0117ti ne daugiau kaip",
          notInclusive: "turi tur\u0117ti ma\u017Eiau kaip"
        },
        bigger: {
          inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip",
          notInclusive: "turi tur\u0117ti daugiau kaip"
        }
      }
    }
  };
  function getSizing(origin, unitType, inclusive, targetShouldBe) {
    const result = Sizable[origin] ?? null;
    if (result === null)
      return result;
    return {
      unit: result.unit[unitType],
      verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"]
    };
  }
  const FormatDictionary = {
    regex: "\u012Fvestis",
    email: "el. pa\u0161to adresas",
    url: "URL",
    emoji: "jaustukas",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO data ir laikas",
    date: "ISO data",
    time: "ISO laikas",
    duration: "ISO trukm\u0117",
    ipv4: "IPv4 adresas",
    ipv6: "IPv6 adresas",
    cidrv4: "IPv4 tinklo prefiksas (CIDR)",
    cidrv6: "IPv6 tinklo prefiksas (CIDR)",
    base64: "base64 u\u017Ekoduota eilut\u0117",
    base64url: "base64url u\u017Ekoduota eilut\u0117",
    json_string: "JSON eilut\u0117",
    e164: "E.164 numeris",
    jwt: "JWT",
    template_literal: "\u012Fvestis"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "skai\u010Dius",
    bigint: "sveikasis skai\u010Dius",
    string: "eilut\u0117",
    boolean: "login\u0117 reik\u0161m\u0117",
    undefined: "neapibr\u0117\u017Eta reik\u0161m\u0117",
    function: "funkcija",
    symbol: "simbolis",
    array: "masyvas",
    object: "objektas",
    null: "nulin\u0117 reik\u0161m\u0117"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue2.expected}`;
        }
        return `Gautas tipas ${received}, o tik\u0117tasi - ${expected}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Privalo b\u016Bti ${stringifyPrimitive(issue2.values[0])}`;
        return `Privalo b\u016Bti vienas i\u0161 ${joinValues(issue2.values, "|")} pasirinkim\u0173`;
      case "too_big": {
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.maximum)), issue2.inclusive ?? false, "smaller");
        if (sizing?.verb)
          return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.maximum.toString()} ${sizing.unit ?? "element\u0173"}`;
        const adj = issue2.inclusive ? "ne didesnis kaip" : "ma\u017Eesnis kaip";
        return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.maximum.toString()} ${sizing?.unit}`;
      }
      case "too_small": {
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.minimum)), issue2.inclusive ?? false, "bigger");
        if (sizing?.verb)
          return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.minimum.toString()} ${sizing.unit ?? "element\u0173"}`;
        const adj = issue2.inclusive ? "ne ma\u017Eesnis kaip" : "didesnis kaip";
        return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.minimum.toString()} ${sizing?.unit}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Eilut\u0117 privalo prasid\u0117ti "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Eilut\u0117 privalo pasibaigti "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Eilut\u0117 privalo \u012Ftraukti "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Eilut\u0117 privalo atitikti ${_issue.pattern}`;
        return `Neteisingas ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Skai\u010Dius privalo b\u016Bti ${issue2.divisor} kartotinis.`;
      case "unrecognized_keys":
        return `Neatpa\u017Eint${issue2.keys.length > 1 ? "i" : "as"} rakt${issue2.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return "Rastas klaidingas raktas";
      case "invalid_union":
        return "Klaidinga \u012Fvestis";
      case "invalid_element": {
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`;
      }
      default:
        return "Klaidinga \u012Fvestis";
    }
  };
};
function lt_default() {
  return {
    localeError: error28()
  };
}

// node_modules/zod/v4/locales/mk.js
var error29 = () => {
  const Sizable = {
    string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" },
    file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" },
    array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" },
    set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0432\u043D\u0435\u0441",
    email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",
    url: "URL",
    emoji: "\u0435\u043C\u043E\u045F\u0438",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",
    date: "ISO \u0434\u0430\u0442\u0443\u043C",
    time: "ISO \u0432\u0440\u0435\u043C\u0435",
    duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",
    ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",
    ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",
    cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433",
    cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433",
    base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",
    base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",
    json_string: "JSON \u043D\u0438\u0437\u0430",
    e164: "E.164 \u0431\u0440\u043E\u0458",
    jwt: "JWT",
    template_literal: "\u0432\u043D\u0435\u0441"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0431\u0440\u043E\u0458",
    array: "\u043D\u0438\u0437\u0430"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`;
        }
        return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;
        return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`;
        return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`;
        return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`;
      case "invalid_union":
        return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";
      case "invalid_element":
        return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`;
      default:
        return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`;
    }
  };
};
function mk_default() {
  return {
    localeError: error29()
  };
}

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

// node_modules/zod/v4/locales/nl.js
var error31 = () => {
  const Sizable = {
    string: { unit: "tekens", verb: "heeft" },
    file: { unit: "bytes", verb: "heeft" },
    array: { unit: "elementen", verb: "heeft" },
    set: { unit: "elementen", verb: "heeft" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "invoer",
    email: "emailadres",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO datum en tijd",
    date: "ISO datum",
    time: "ISO tijd",
    duration: "ISO duur",
    ipv4: "IPv4-adres",
    ipv6: "IPv6-adres",
    cidrv4: "IPv4-bereik",
    cidrv6: "IPv6-bereik",
    base64: "base64-gecodeerde tekst",
    base64url: "base64 URL-gecodeerde tekst",
    json_string: "JSON string",
    e164: "E.164-nummer",
    jwt: "JWT",
    template_literal: "invoer"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "getal"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ongeldige invoer: verwacht instanceof ${issue2.expected}, ontving ${received}`;
        }
        return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`;
        return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        const longName = issue2.origin === "date" ? "laat" : issue2.origin === "string" ? "lang" : "groot";
        if (sizing)
          return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementen"} ${sizing.verb}`;
        return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} is`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        const shortName = issue2.origin === "date" ? "vroeg" : issue2.origin === "string" ? "kort" : "klein";
        if (sizing) {
          return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`;
        }
        return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`;
        }
        if (_issue.format === "ends_with")
          return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`;
        if (_issue.format === "includes")
          return `Ongeldige tekst: moet "${_issue.includes}" bevatten`;
        if (_issue.format === "regex")
          return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`;
        return `Ongeldig: ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`;
      case "unrecognized_keys":
        return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Ongeldige key in ${issue2.origin}`;
      case "invalid_union":
        return "Ongeldige invoer";
      case "invalid_element":
        return `Ongeldige waarde in ${issue2.origin}`;
      default:
        return `Ongeldige invoer`;
    }
  };
};
function nl_default() {
  return {
    localeError: error31()
  };
}

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

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

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

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

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

// node_modules/zod/v4/locales/ro.js
var error37 = () => {
  const Sizable = {
    string: { unit: "caractere", verb: "s\u0103 aib\u0103" },
    file: { unit: "octe\u021Bi", verb: "s\u0103 aib\u0103" },
    array: { unit: "elemente", verb: "s\u0103 aib\u0103" },
    set: { unit: "elemente", verb: "s\u0103 aib\u0103" },
    map: { unit: "intr\u0103ri", verb: "s\u0103 aib\u0103" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "intrare",
    email: "adres\u0103 de email",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "dat\u0103 \u0219i or\u0103 ISO",
    date: "dat\u0103 ISO",
    time: "or\u0103 ISO",
    duration: "durat\u0103 ISO",
    ipv4: "adres\u0103 IPv4",
    ipv6: "adres\u0103 IPv6",
    mac: "adres\u0103 MAC",
    cidrv4: "interval IPv4",
    cidrv6: "interval IPv6",
    base64: "\u0219ir codat base64",
    base64url: "\u0219ir codat base64url",
    json_string: "\u0219ir JSON",
    e164: "num\u0103r E.164",
    jwt: "JWT",
    template_literal: "intrare"
  };
  const TypeDictionary = {
    nan: "NaN",
    string: "\u0219ir",
    number: "num\u0103r",
    boolean: "boolean",
    function: "func\u021Bie",
    array: "matrice",
    object: "obiect",
    undefined: "nedefinit",
    symbol: "simbol",
    bigint: "num\u0103r mare",
    void: "void",
    never: "never",
    map: "hart\u0103",
    set: "set"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        return `Intrare invalid\u0103: a\u0219teptat ${expected}, primit ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Intrare invalid\u0103: a\u0219teptat ${stringifyPrimitive(issue2.values[0])}`;
        return `Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Prea mare: a\u0219teptat ca ${issue2.origin ?? "valoarea"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemente"}`;
        return `Prea mare: a\u0219teptat ca ${issue2.origin ?? "valoarea"} s\u0103 fie ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Prea mic: a\u0219teptat ca ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Prea mic: a\u0219teptat ca ${issue2.origin} s\u0103 fie ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u0218ir invalid: trebuie s\u0103 \xEEnceap\u0103 cu "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `\u0218ir invalid: trebuie s\u0103 se termine cu "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u0218ir invalid: trebuie s\u0103 includ\u0103 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u0218ir invalid: trebuie s\u0103 se potriveasc\u0103 cu modelul ${_issue.pattern}`;
        return `Format invalid: ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Chei nerecunoscute: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Cheie invalid\u0103 \xEEn ${issue2.origin}`;
      case "invalid_union":
        return "Intrare invalid\u0103";
      case "invalid_element":
        return `Valoare invalid\u0103 \xEEn ${issue2.origin}`;
      default:
        return `Intrare invalid\u0103`;
    }
  };
};
function ro_default() {
  return {
    localeError: error37()
  };
}

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

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

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

// node_modules/zod/v4/locales/ta.js
var error41 = () => {
  const Sizable = {
    string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" },
    file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" },
    array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" },
    set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",
    email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",
    date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF",
    time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",
    duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",
    ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
    ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
    cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",
    cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",
    base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",
    base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",
    json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD",
    e164: "E.164 \u0B8E\u0BA3\u0BCD",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0B8E\u0BA3\u0BCD",
    array: "\u0B85\u0BA3\u0BBF",
    null: "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`;
        }
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`;
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        }
        return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        }
        return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        if (_issue.format === "ends_with")
          return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        if (_issue.format === "includes")
          return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        if (_issue.format === "regex")
          return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
      case "unrecognized_keys":
        return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;
      case "invalid_union":
        return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";
      case "invalid_element":
        return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;
      default:
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`;
    }
  };
};
function ta_default() {
  return {
    localeError: error41()
  };
}

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

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

// node_modules/zod/v4/locales/uk.js
var error44 = () => {
  const Sizable = {
    string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" },
    file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" },
    array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" },
    set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",
    email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",
    url: "URL",
    emoji: "\u0435\u043C\u043E\u0434\u0437\u0456",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",
    date: "\u0434\u0430\u0442\u0430 ISO",
    time: "\u0447\u0430\u0441 ISO",
    duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",
    ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",
    ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",
    cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",
    cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",
    base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",
    base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",
    json_string: "\u0440\u044F\u0434\u043E\u043A JSON",
    e164: "\u043D\u043E\u043C\u0435\u0440 E.164",
    jwt: "JWT",
    template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0447\u0438\u0441\u043B\u043E",
    array: "\u043C\u0430\u0441\u0438\u0432"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`;
        }
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`;
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`;
        return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`;
      case "invalid_union":
        return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";
      case "invalid_element":
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`;
      default:
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`;
    }
  };
};
function uk_default() {
  return {
    localeError: error44()
  };
}

// node_modules/zod/v4/locales/ua.js
function ua_default() {
  return uk_default();
}

// node_modules/zod/v4/locales/ur.js
var error45 = () => {
  const Sizable = {
    string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" },
    file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" },
    array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" },
    set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0627\u0646 \u067E\u0679",
    email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",
    url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",
    emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC",
    uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
    uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",
    uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",
    nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",
    guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
    cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
    cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",
    ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",
    xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",
    ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
    datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",
    date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",
    time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",
    duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",
    ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",
    ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",
    cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",
    cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",
    base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",
    base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",
    json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",
    e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631",
    jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",
    template_literal: "\u0627\u0646 \u067E\u0679"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0646\u0645\u0628\u0631",
    array: "\u0622\u0631\u06D2",
    null: "\u0646\u0644"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;
        }
        return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
        return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;
        return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;
        }
        return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
        }
        if (_issue.format === "ends_with")
          return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
        if (_issue.format === "includes")
          return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
        if (_issue.format === "regex")
          return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
        return `\u063A\u0644\u0637 ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
      case "unrecognized_keys":
        return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue2.keys, "\u060C ")}`;
      case "invalid_key":
        return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;
      case "invalid_union":
        return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";
      case "invalid_element":
        return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;
      default:
        return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`;
    }
  };
};
function ur_default() {
  return {
    localeError: error45()
  };
}

// node_modules/zod/v4/locales/uz.js
var error46 = () => {
  const Sizable = {
    string: { unit: "belgi", verb: "bo\u2018lishi kerak" },
    file: { unit: "bayt", verb: "bo\u2018lishi kerak" },
    array: { unit: "element", verb: "bo\u2018lishi kerak" },
    set: { unit: "element", verb: "bo\u2018lishi kerak" },
    map: { unit: "yozuv", verb: "bo\u2018lishi kerak" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "kirish",
    email: "elektron pochta manzili",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO sana va vaqti",
    date: "ISO sana",
    time: "ISO vaqt",
    duration: "ISO davomiylik",
    ipv4: "IPv4 manzil",
    ipv6: "IPv6 manzil",
    mac: "MAC manzil",
    cidrv4: "IPv4 diapazon",
    cidrv6: "IPv6 diapazon",
    base64: "base64 kodlangan satr",
    base64url: "base64url kodlangan satr",
    json_string: "JSON satr",
    e164: "E.164 raqam",
    jwt: "JWT",
    template_literal: "kirish"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "raqam",
    array: "massiv"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue2.expected}, qabul qilingan ${received}`;
        }
        return `Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Noto\u2018g\u2018ri kirish: kutilgan ${stringifyPrimitive(issue2.values[0])}`;
        return `Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`;
        return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`;
        }
        return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Noto\u2018g\u2018ri satr: "${_issue.prefix}" bilan boshlanishi kerak`;
        if (_issue.format === "ends_with")
          return `Noto\u2018g\u2018ri satr: "${_issue.suffix}" bilan tugashi kerak`;
        if (_issue.format === "includes")
          return `Noto\u2018g\u2018ri satr: "${_issue.includes}" ni o\u2018z ichiga olishi kerak`;
        if (_issue.format === "regex")
          return `Noto\u2018g\u2018ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`;
        return `Noto\u2018g\u2018ri ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Noto\u2018g\u2018ri raqam: ${issue2.divisor} ning karralisi bo\u2018lishi kerak`;
      case "unrecognized_keys":
        return `Noma\u2019lum kalit${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} dagi kalit noto\u2018g\u2018ri`;
      case "invalid_union":
        return "Noto\u2018g\u2018ri kirish";
      case "invalid_element":
        return `${issue2.origin} da noto\u2018g\u2018ri qiymat`;
      default:
        return `Noto\u2018g\u2018ri kirish`;
    }
  };
};
function uz_default() {
  return {
    localeError: error46()
  };
}

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

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

// node_modules/zod/v4/locales/zh-TW.js
var error49 = () => {
  const Sizable = {
    string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" },
    file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" },
    array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" },
    set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u8F38\u5165",
    email: "\u90F5\u4EF6\u5730\u5740",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \u65E5\u671F\u6642\u9593",
    date: "ISO \u65E5\u671F",
    time: "ISO \u6642\u9593",
    duration: "ISO \u671F\u9593",
    ipv4: "IPv4 \u4F4D\u5740",
    ipv6: "IPv6 \u4F4D\u5740",
    cidrv4: "IPv4 \u7BC4\u570D",
    cidrv6: "IPv6 \u7BC4\u570D",
    base64: "base64 \u7DE8\u78BC\u5B57\u4E32",
    base64url: "base64url \u7DE8\u78BC\u5B57\u4E32",
    json_string: "JSON \u5B57\u4E32",
    e164: "E.164 \u6578\u503C",
    jwt: "JWT",
    template_literal: "\u8F38\u5165"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${received}`;
        }
        return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${expected}\uFF0C\u4F46\u6536\u5230 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`;
        return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`;
        return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`;
        }
        if (_issue.format === "ends_with")
          return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`;
        if (_issue.format === "includes")
          return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`;
        return `\u7121\u6548\u7684 ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`;
      case "unrecognized_keys":
        return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue2.keys, "\u3001")}`;
      case "invalid_key":
        return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;
      case "invalid_union":
        return "\u7121\u6548\u7684\u8F38\u5165\u503C";
      case "invalid_element":
        return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;
      default:
        return `\u7121\u6548\u7684\u8F38\u5165\u503C`;
    }
  };
};
function zh_TW_default() {
  return {
    localeError: error49()
  };
}

// node_modules/zod/v4/locales/yo.js
var error50 = () => {
  const Sizable = {
    string: { unit: "\xE0mi", verb: "n\xED" },
    file: { unit: "bytes", verb: "n\xED" },
    array: { unit: "nkan", verb: "n\xED" },
    set: { unit: "nkan", verb: "n\xED" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9",
    email: "\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "\xE0k\xF3k\xF2 ISO",
    date: "\u1ECDj\u1ECD\u0301 ISO",
    time: "\xE0k\xF3k\xF2 ISO",
    duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO",
    ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4",
    ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6",
    cidrv4: "\xE0gb\xE8gb\xE8 IPv4",
    cidrv6: "\xE0gb\xE8gb\xE8 IPv6",
    base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64",
    base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url",
    json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON",
    e164: "n\u1ECD\u0301mb\xE0 E.164",
    jwt: "JWT",
    template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "n\u1ECD\u0301mb\xE0",
    array: "akop\u1ECD"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${issue2.expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`;
        }
        return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${stringifyPrimitive(issue2.values[0])}`;
        return `\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin ?? "iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`;
        return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.maximum}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`;
        return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.minimum}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${_issue.pattern}`;
        return `A\u1E63\xEC\u1E63e: ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${issue2.divisor}`;
      case "unrecognized_keys":
        return `B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`;
      case "invalid_union":
        return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";
      case "invalid_element":
        return `Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`;
      default:
        return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";
    }
  };
};
function yo_default() {
  return {
    localeError: error50()
  };
}

// node_modules/zod/v4/core/registries.js
var _a2;
var $output = /* @__PURE__ */ Symbol("ZodOutput");
var $input = /* @__PURE__ */ Symbol("ZodInput");
var $ZodRegistry = class {
  constructor() {
    this._map = /* @__PURE__ */ new WeakMap();
    this._idmap = /* @__PURE__ */ new Map();
  }
  add(schema, ..._meta) {
    const meta3 = _meta[0];
    this._map.set(schema, meta3);
    if (meta3 && typeof meta3 === "object" && "id" in meta3) {
      this._idmap.set(meta3.id, schema);
    }
    return this;
  }
  clear() {
    this._map = /* @__PURE__ */ new WeakMap();
    this._idmap = /* @__PURE__ */ new Map();
    return this;
  }
  remove(schema) {
    const meta3 = this._map.get(schema);
    if (meta3 && typeof meta3 === "object" && "id" in meta3) {
      this._idmap.delete(meta3.id);
    }
    this._map.delete(schema);
    return this;
  }
  get(schema) {
    const p = schema._zod.parent;
    if (p) {
      const pm = { ...this.get(p) ?? {} };
      delete pm.id;
      const f3 = { ...pm, ...this._map.get(schema) };
      return Object.keys(f3).length ? f3 : void 0;
    }
    return this._map.get(schema);
  }
  has(schema) {
    return this._map.has(schema);
  }
};
function registry() {
  return new $ZodRegistry();
}
(_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry());
var globalRegistry = globalThis.__zod_globalRegistry;

// node_modules/zod/v4/core/api.js
// @__NO_SIDE_EFFECTS__
function _string(Class2, params) {
  return new Class2({
    type: "string",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedString(Class2, params) {
  return new Class2({
    type: "string",
    coerce: true,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _email(Class2, params) {
  return new Class2({
    type: "string",
    format: "email",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _guid(Class2, params) {
  return new Class2({
    type: "string",
    format: "guid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uuid(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uuidv4(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v4",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uuidv6(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v6",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uuidv7(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v7",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _url(Class2, params) {
  return new Class2({
    type: "string",
    format: "url",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _emoji2(Class2, params) {
  return new Class2({
    type: "string",
    format: "emoji",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _nanoid(Class2, params) {
  return new Class2({
    type: "string",
    format: "nanoid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _cuid(Class2, params) {
  return new Class2({
    type: "string",
    format: "cuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _cuid2(Class2, params) {
  return new Class2({
    type: "string",
    format: "cuid2",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _ulid(Class2, params) {
  return new Class2({
    type: "string",
    format: "ulid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _xid(Class2, params) {
  return new Class2({
    type: "string",
    format: "xid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _ksuid(Class2, params) {
  return new Class2({
    type: "string",
    format: "ksuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _ipv4(Class2, params) {
  return new Class2({
    type: "string",
    format: "ipv4",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _ipv6(Class2, params) {
  return new Class2({
    type: "string",
    format: "ipv6",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _mac(Class2, params) {
  return new Class2({
    type: "string",
    format: "mac",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _cidrv4(Class2, params) {
  return new Class2({
    type: "string",
    format: "cidrv4",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _cidrv6(Class2, params) {
  return new Class2({
    type: "string",
    format: "cidrv6",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _base64(Class2, params) {
  return new Class2({
    type: "string",
    format: "base64",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _base64url(Class2, params) {
  return new Class2({
    type: "string",
    format: "base64url",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _e164(Class2, params) {
  return new Class2({
    type: "string",
    format: "e164",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _jwt(Class2, params) {
  return new Class2({
    type: "string",
    format: "jwt",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
var TimePrecision = {
  Any: null,
  Minute: -1,
  Second: 0,
  Millisecond: 3,
  Microsecond: 6
};
// @__NO_SIDE_EFFECTS__
function _isoDateTime(Class2, params) {
  return new Class2({
    type: "string",
    format: "datetime",
    check: "string_format",
    offset: false,
    local: false,
    precision: null,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _isoDate(Class2, params) {
  return new Class2({
    type: "string",
    format: "date",
    check: "string_format",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _isoTime(Class2, params) {
  return new Class2({
    type: "string",
    format: "time",
    check: "string_format",
    precision: null,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _isoDuration(Class2, params) {
  return new Class2({
    type: "string",
    format: "duration",
    check: "string_format",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _number(Class2, params) {
  return new Class2({
    type: "number",
    checks: [],
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedNumber(Class2, params) {
  return new Class2({
    type: "number",
    coerce: true,
    checks: [],
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _int(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "safeint",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _float32(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "float32",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _float64(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "float64",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _int32(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "int32",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uint32(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "uint32",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _boolean(Class2, params) {
  return new Class2({
    type: "boolean",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedBoolean(Class2, params) {
  return new Class2({
    type: "boolean",
    coerce: true,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _bigint(Class2, params) {
  return new Class2({
    type: "bigint",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedBigint(Class2, params) {
  return new Class2({
    type: "bigint",
    coerce: true,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _int64(Class2, params) {
  return new Class2({
    type: "bigint",
    check: "bigint_format",
    abort: false,
    format: "int64",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uint64(Class2, params) {
  return new Class2({
    type: "bigint",
    check: "bigint_format",
    abort: false,
    format: "uint64",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _symbol(Class2, params) {
  return new Class2({
    type: "symbol",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _undefined2(Class2, params) {
  return new Class2({
    type: "undefined",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _null2(Class2, params) {
  return new Class2({
    type: "null",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _any(Class2) {
  return new Class2({
    type: "any"
  });
}
// @__NO_SIDE_EFFECTS__
function _unknown(Class2) {
  return new Class2({
    type: "unknown"
  });
}
// @__NO_SIDE_EFFECTS__
function _never(Class2, params) {
  return new Class2({
    type: "never",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _void(Class2, params) {
  return new Class2({
    type: "void",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _date(Class2, params) {
  return new Class2({
    type: "date",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedDate(Class2, params) {
  return new Class2({
    type: "date",
    coerce: true,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _nan(Class2, params) {
  return new Class2({
    type: "nan",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _lt(value, params) {
  return new $ZodCheckLessThan({
    check: "less_than",
    ...normalizeParams(params),
    value,
    inclusive: false
  });
}
// @__NO_SIDE_EFFECTS__
function _lte(value, params) {
  return new $ZodCheckLessThan({
    check: "less_than",
    ...normalizeParams(params),
    value,
    inclusive: true
  });
}
// @__NO_SIDE_EFFECTS__
function _gt(value, params) {
  return new $ZodCheckGreaterThan({
    check: "greater_than",
    ...normalizeParams(params),
    value,
    inclusive: false
  });
}
// @__NO_SIDE_EFFECTS__
function _gte(value, params) {
  return new $ZodCheckGreaterThan({
    check: "greater_than",
    ...normalizeParams(params),
    value,
    inclusive: true
  });
}
// @__NO_SIDE_EFFECTS__
function _positive(params) {
  return /* @__PURE__ */ _gt(0, params);
}
// @__NO_SIDE_EFFECTS__
function _negative(params) {
  return /* @__PURE__ */ _lt(0, params);
}
// @__NO_SIDE_EFFECTS__
function _nonpositive(params) {
  return /* @__PURE__ */ _lte(0, params);
}
// @__NO_SIDE_EFFECTS__
function _nonnegative(params) {
  return /* @__PURE__ */ _gte(0, params);
}
// @__NO_SIDE_EFFECTS__
function _multipleOf(value, params) {
  return new $ZodCheckMultipleOf({
    check: "multiple_of",
    ...normalizeParams(params),
    value
  });
}
// @__NO_SIDE_EFFECTS__
function _maxSize(maximum, params) {
  return new $ZodCheckMaxSize({
    check: "max_size",
    ...normalizeParams(params),
    maximum
  });
}
// @__NO_SIDE_EFFECTS__
function _minSize(minimum, params) {
  return new $ZodCheckMinSize({
    check: "min_size",
    ...normalizeParams(params),
    minimum
  });
}
// @__NO_SIDE_EFFECTS__
function _size(size, params) {
  return new $ZodCheckSizeEquals({
    check: "size_equals",
    ...normalizeParams(params),
    size
  });
}
// @__NO_SIDE_EFFECTS__
function _maxLength(maximum, params) {
  const ch = new $ZodCheckMaxLength({
    check: "max_length",
    ...normalizeParams(params),
    maximum
  });
  return ch;
}
// @__NO_SIDE_EFFECTS__
function _minLength(minimum, params) {
  return new $ZodCheckMinLength({
    check: "min_length",
    ...normalizeParams(params),
    minimum
  });
}
// @__NO_SIDE_EFFECTS__
function _length(length, params) {
  return new $ZodCheckLengthEquals({
    check: "length_equals",
    ...normalizeParams(params),
    length
  });
}
// @__NO_SIDE_EFFECTS__
function _regex(pattern, params) {
  return new $ZodCheckRegex({
    check: "string_format",
    format: "regex",
    ...normalizeParams(params),
    pattern
  });
}
// @__NO_SIDE_EFFECTS__
function _lowercase(params) {
  return new $ZodCheckLowerCase({
    check: "string_format",
    format: "lowercase",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uppercase(params) {
  return new $ZodCheckUpperCase({
    check: "string_format",
    format: "uppercase",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _includes(includes, params) {
  return new $ZodCheckIncludes({
    check: "string_format",
    format: "includes",
    ...normalizeParams(params),
    includes
  });
}
// @__NO_SIDE_EFFECTS__
function _startsWith(prefix, params) {
  return new $ZodCheckStartsWith({
    check: "string_format",
    format: "starts_with",
    ...normalizeParams(params),
    prefix
  });
}
// @__NO_SIDE_EFFECTS__
function _endsWith(suffix, params) {
  return new $ZodCheckEndsWith({
    check: "string_format",
    format: "ends_with",
    ...normalizeParams(params),
    suffix
  });
}
// @__NO_SIDE_EFFECTS__
function _property(property, schema, params) {
  return new $ZodCheckProperty({
    check: "property",
    property,
    schema,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _mime(types3, params) {
  return new $ZodCheckMimeType({
    check: "mime_type",
    mime: types3,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _overwrite(tx) {
  return new $ZodCheckOverwrite({
    check: "overwrite",
    tx
  });
}
// @__NO_SIDE_EFFECTS__
function _normalize(form) {
  return /* @__PURE__ */ _overwrite((input) => input.normalize(form));
}
// @__NO_SIDE_EFFECTS__
function _trim() {
  return /* @__PURE__ */ _overwrite((input) => input.trim());
}
// @__NO_SIDE_EFFECTS__
function _toLowerCase() {
  return /* @__PURE__ */ _overwrite((input) => input.toLowerCase());
}
// @__NO_SIDE_EFFECTS__
function _toUpperCase() {
  return /* @__PURE__ */ _overwrite((input) => input.toUpperCase());
}
// @__NO_SIDE_EFFECTS__
function _slugify() {
  return /* @__PURE__ */ _overwrite((input) => slugify(input));
}
// @__NO_SIDE_EFFECTS__
function _array(Class2, element, params) {
  return new Class2({
    type: "array",
    element,
    // get element() {
    //   return element;
    // },
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _union(Class2, options, params) {
  return new Class2({
    type: "union",
    options,
    ...normalizeParams(params)
  });
}
function _xor(Class2, options, params) {
  return new Class2({
    type: "union",
    options,
    inclusive: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _discriminatedUnion(Class2, discriminator, options, params) {
  return new Class2({
    type: "union",
    options,
    discriminator,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _intersection(Class2, left, right) {
  return new Class2({
    type: "intersection",
    left,
    right
  });
}
// @__NO_SIDE_EFFECTS__
function _tuple(Class2, items, _paramsOrRest, _params) {
  const hasRest = _paramsOrRest instanceof $ZodType;
  const params = hasRest ? _params : _paramsOrRest;
  const rest = hasRest ? _paramsOrRest : null;
  return new Class2({
    type: "tuple",
    items,
    rest,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _record(Class2, keyType, valueType, params) {
  return new Class2({
    type: "record",
    keyType,
    valueType,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _map(Class2, keyType, valueType, params) {
  return new Class2({
    type: "map",
    keyType,
    valueType,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _set(Class2, valueType, params) {
  return new Class2({
    type: "set",
    valueType,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _enum(Class2, values, params) {
  const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
  return new Class2({
    type: "enum",
    entries,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _nativeEnum(Class2, entries, params) {
  return new Class2({
    type: "enum",
    entries,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _literal(Class2, value, params) {
  return new Class2({
    type: "literal",
    values: Array.isArray(value) ? value : [value],
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _file(Class2, params) {
  return new Class2({
    type: "file",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _transform(Class2, fn) {
  return new Class2({
    type: "transform",
    transform: fn
  });
}
// @__NO_SIDE_EFFECTS__
function _optional(Class2, innerType) {
  return new Class2({
    type: "optional",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _nullable(Class2, innerType) {
  return new Class2({
    type: "nullable",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _default(Class2, innerType, defaultValue) {
  return new Class2({
    type: "default",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
    }
  });
}
// @__NO_SIDE_EFFECTS__
function _nonoptional(Class2, innerType, params) {
  return new Class2({
    type: "nonoptional",
    innerType,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _success(Class2, innerType) {
  return new Class2({
    type: "success",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _catch(Class2, innerType, catchValue) {
  return new Class2({
    type: "catch",
    innerType,
    catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
  });
}
// @__NO_SIDE_EFFECTS__
function _pipe(Class2, in_, out) {
  return new Class2({
    type: "pipe",
    in: in_,
    out
  });
}
// @__NO_SIDE_EFFECTS__
function _readonly(Class2, innerType) {
  return new Class2({
    type: "readonly",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _templateLiteral(Class2, parts, params) {
  return new Class2({
    type: "template_literal",
    parts,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _lazy(Class2, getter) {
  return new Class2({
    type: "lazy",
    getter
  });
}
// @__NO_SIDE_EFFECTS__
function _promise(Class2, innerType) {
  return new Class2({
    type: "promise",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _custom(Class2, fn, _params) {
  const norm = normalizeParams(_params);
  norm.abort ?? (norm.abort = true);
  const schema = new Class2({
    type: "custom",
    check: "custom",
    fn,
    ...norm
  });
  return schema;
}
// @__NO_SIDE_EFFECTS__
function _refine(Class2, fn, _params) {
  const schema = new Class2({
    type: "custom",
    check: "custom",
    fn,
    ...normalizeParams(_params)
  });
  return schema;
}
// @__NO_SIDE_EFFECTS__
function _superRefine(fn, params) {
  const ch = /* @__PURE__ */ _check((payload) => {
    payload.addIssue = (issue2) => {
      if (typeof issue2 === "string") {
        payload.issues.push(issue(issue2, payload.value, ch._zod.def));
      } else {
        const _issue = issue2;
        if (_issue.fatal)
          _issue.continue = false;
        _issue.code ?? (_issue.code = "custom");
        _issue.input ?? (_issue.input = payload.value);
        _issue.inst ?? (_issue.inst = ch);
        _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
        payload.issues.push(issue(_issue));
      }
    };
    return fn(payload.value, payload);
  }, params);
  return ch;
}
// @__NO_SIDE_EFFECTS__
function _check(fn, params) {
  const ch = new $ZodCheck({
    check: "custom",
    ...normalizeParams(params)
  });
  ch._zod.check = fn;
  return ch;
}
// @__NO_SIDE_EFFECTS__
function describe(description) {
  const ch = new $ZodCheck({ check: "describe" });
  ch._zod.onattach = [
    (inst) => {
      const existing = globalRegistry.get(inst) ?? {};
      globalRegistry.add(inst, { ...existing, description });
    }
  ];
  ch._zod.check = () => {
  };
  return ch;
}
// @__NO_SIDE_EFFECTS__
function meta(metadata) {
  const ch = new $ZodCheck({ check: "meta" });
  ch._zod.onattach = [
    (inst) => {
      const existing = globalRegistry.get(inst) ?? {};
      globalRegistry.add(inst, { ...existing, ...metadata });
    }
  ];
  ch._zod.check = () => {
  };
  return ch;
}
// @__NO_SIDE_EFFECTS__
function _stringbool(Classes, _params) {
  const params = normalizeParams(_params);
  let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"];
  let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"];
  if (params.case !== "sensitive") {
    truthyArray = truthyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v);
    falsyArray = falsyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v);
  }
  const truthySet = new Set(truthyArray);
  const falsySet = new Set(falsyArray);
  const _Codec = Classes.Codec ?? $ZodCodec;
  const _Boolean = Classes.Boolean ?? $ZodBoolean;
  const _String = Classes.String ?? $ZodString;
  const stringSchema = new _String({ type: "string", error: params.error });
  const booleanSchema = new _Boolean({ type: "boolean", error: params.error });
  const codec2 = new _Codec({
    type: "pipe",
    in: stringSchema,
    out: booleanSchema,
    transform: ((input, payload) => {
      let data = input;
      if (params.case !== "sensitive")
        data = data.toLowerCase();
      if (truthySet.has(data)) {
        return true;
      } else if (falsySet.has(data)) {
        return false;
      } else {
        payload.issues.push({
          code: "invalid_value",
          expected: "stringbool",
          values: [...truthySet, ...falsySet],
          input: payload.value,
          inst: codec2,
          continue: false
        });
        return {};
      }
    }),
    reverseTransform: ((input, _payload) => {
      if (input === true) {
        return truthyArray[0] || "true";
      } else {
        return falsyArray[0] || "false";
      }
    }),
    error: params.error
  });
  return codec2;
}
// @__NO_SIDE_EFFECTS__
function _stringFormat(Class2, format, fnOrRegex, _params = {}) {
  const params = normalizeParams(_params);
  const def = {
    ...normalizeParams(_params),
    check: "string_format",
    type: "string",
    format,
    fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val),
    ...params
  };
  if (fnOrRegex instanceof RegExp) {
    def.pattern = fnOrRegex;
  }
  const inst = new Class2(def);
  return inst;
}

// node_modules/zod/v4/core/to-json-schema.js
function initializeContext(params) {
  let target = params?.target ?? "draft-2020-12";
  if (target === "draft-4")
    target = "draft-04";
  if (target === "draft-7")
    target = "draft-07";
  return {
    processors: params.processors ?? {},
    metadataRegistry: params?.metadata ?? globalRegistry,
    target,
    unrepresentable: params?.unrepresentable ?? "throw",
    override: params?.override ?? (() => {
    }),
    io: params?.io ?? "output",
    counter: 0,
    seen: /* @__PURE__ */ new Map(),
    cycles: params?.cycles ?? "ref",
    reused: params?.reused ?? "inline",
    external: params?.external ?? void 0
  };
}
function process2(schema, ctx, _params = { path: [], schemaPath: [] }) {
  var _a3;
  const def = schema._zod.def;
  const seen = ctx.seen.get(schema);
  if (seen) {
    seen.count++;
    const isCycle = _params.schemaPath.includes(schema);
    if (isCycle) {
      seen.cycle = _params.path;
    }
    return seen.schema;
  }
  const result = { schema: {}, count: 1, cycle: void 0, path: _params.path };
  ctx.seen.set(schema, result);
  const overrideSchema = schema._zod.toJSONSchema?.();
  if (overrideSchema) {
    result.schema = overrideSchema;
  } else {
    const params = {
      ..._params,
      schemaPath: [..._params.schemaPath, schema],
      path: _params.path
    };
    if (schema._zod.processJSONSchema) {
      schema._zod.processJSONSchema(ctx, result.schema, params);
    } else {
      const _json = result.schema;
      const processor = ctx.processors[def.type];
      if (!processor) {
        throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
      }
      processor(schema, ctx, _json, params);
    }
    const parent = schema._zod.parent;
    if (parent) {
      if (!result.ref)
        result.ref = parent;
      process2(parent, ctx, params);
      ctx.seen.get(parent).isParent = true;
    }
  }
  const meta3 = ctx.metadataRegistry.get(schema);
  if (meta3)
    Object.assign(result.schema, meta3);
  if (ctx.io === "input" && isTransforming(schema)) {
    delete result.schema.examples;
    delete result.schema.default;
  }
  if (ctx.io === "input" && "_prefault" in result.schema)
    (_a3 = result.schema).default ?? (_a3.default = result.schema._prefault);
  delete result.schema._prefault;
  const _result = ctx.seen.get(schema);
  return _result.schema;
}
function extractDefs(ctx, schema) {
  const root = ctx.seen.get(schema);
  if (!root)
    throw new Error("Unprocessed schema. This is a bug in Zod.");
  const idToSchema = /* @__PURE__ */ new Map();
  for (const entry of ctx.seen.entries()) {
    const id = ctx.metadataRegistry.get(entry[0])?.id;
    if (id) {
      const existing = idToSchema.get(id);
      if (existing && existing !== entry[0]) {
        throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
      }
      idToSchema.set(id, entry[0]);
    }
  }
  const makeURI = (entry) => {
    const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
    if (ctx.external) {
      const externalId = ctx.external.registry.get(entry[0])?.id;
      const uriGenerator = ctx.external.uri ?? ((id2) => id2);
      if (externalId) {
        return { ref: uriGenerator(externalId) };
      }
      const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
      entry[1].defId = id;
      return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
    }
    if (entry[1] === root) {
      return { ref: "#" };
    }
    const uriPrefix = `#`;
    const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
    const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
    return { defId, ref: defUriPrefix + defId };
  };
  const extractToDef = (entry) => {
    if (entry[1].schema.$ref) {
      return;
    }
    const seen = entry[1];
    const { ref, defId } = makeURI(entry);
    seen.def = { ...seen.schema };
    if (defId)
      seen.defId = defId;
    const schema2 = seen.schema;
    for (const key in schema2) {
      delete schema2[key];
    }
    schema2.$ref = ref;
  };
  if (ctx.cycles === "throw") {
    for (const entry of ctx.seen.entries()) {
      const seen = entry[1];
      if (seen.cycle) {
        throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>

Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);
      }
    }
  }
  for (const entry of ctx.seen.entries()) {
    const seen = entry[1];
    if (schema === entry[0]) {
      extractToDef(entry);
      continue;
    }
    if (ctx.external) {
      const ext = ctx.external.registry.get(entry[0])?.id;
      if (schema !== entry[0] && ext) {
        extractToDef(entry);
        continue;
      }
    }
    const id = ctx.metadataRegistry.get(entry[0])?.id;
    if (id) {
      extractToDef(entry);
      continue;
    }
    if (seen.cycle) {
      extractToDef(entry);
      continue;
    }
    if (seen.count > 1) {
      if (ctx.reused === "ref") {
        extractToDef(entry);
        continue;
      }
    }
  }
}
function finalize(ctx, schema) {
  const root = ctx.seen.get(schema);
  if (!root)
    throw new Error("Unprocessed schema. This is a bug in Zod.");
  const flattenRef = (zodSchema) => {
    const seen = ctx.seen.get(zodSchema);
    if (seen.ref === null)
      return;
    const schema2 = seen.def ?? seen.schema;
    const _cached = { ...schema2 };
    const ref = seen.ref;
    seen.ref = null;
    if (ref) {
      flattenRef(ref);
      const refSeen = ctx.seen.get(ref);
      const refSchema = refSeen.schema;
      if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
        schema2.allOf = schema2.allOf ?? [];
        schema2.allOf.push(refSchema);
      } else {
        Object.assign(schema2, refSchema);
      }
      Object.assign(schema2, _cached);
      const isParentRef = zodSchema._zod.parent === ref;
      if (isParentRef) {
        for (const key in schema2) {
          if (key === "$ref" || key === "allOf")
            continue;
          if (!(key in _cached)) {
            delete schema2[key];
          }
        }
      }
      if (refSchema.$ref && refSeen.def) {
        for (const key in schema2) {
          if (key === "$ref" || key === "allOf")
            continue;
          if (key in refSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(refSeen.def[key])) {
            delete schema2[key];
          }
        }
      }
    }
    const parent = zodSchema._zod.parent;
    if (parent && parent !== ref) {
      flattenRef(parent);
      const parentSeen = ctx.seen.get(parent);
      if (parentSeen?.schema.$ref) {
        schema2.$ref = parentSeen.schema.$ref;
        if (parentSeen.def) {
          for (const key in schema2) {
            if (key === "$ref" || key === "allOf")
              continue;
            if (key in parentSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(parentSeen.def[key])) {
              delete schema2[key];
            }
          }
        }
      }
    }
    ctx.override({
      zodSchema,
      jsonSchema: schema2,
      path: seen.path ?? []
    });
  };
  for (const entry of [...ctx.seen.entries()].reverse()) {
    flattenRef(entry[0]);
  }
  const result = {};
  if (ctx.target === "draft-2020-12") {
    result.$schema = "https://json-schema.org/draft/2020-12/schema";
  } else if (ctx.target === "draft-07") {
    result.$schema = "http://json-schema.org/draft-07/schema#";
  } else if (ctx.target === "draft-04") {
    result.$schema = "http://json-schema.org/draft-04/schema#";
  } else if (ctx.target === "openapi-3.0") {
  } else {
  }
  if (ctx.external?.uri) {
    const id = ctx.external.registry.get(schema)?.id;
    if (!id)
      throw new Error("Schema is missing an `id` property");
    result.$id = ctx.external.uri(id);
  }
  Object.assign(result, root.def ?? root.schema);
  const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
  if (rootMetaId !== void 0 && result.id === rootMetaId)
    delete result.id;
  const defs = ctx.external?.defs ?? {};
  for (const entry of ctx.seen.entries()) {
    const seen = entry[1];
    if (seen.def && seen.defId) {
      if (seen.def.id === seen.defId)
        delete seen.def.id;
      defs[seen.defId] = seen.def;
    }
  }
  if (ctx.external) {
  } else {
    if (Object.keys(defs).length > 0) {
      if (ctx.target === "draft-2020-12") {
        result.$defs = defs;
      } else {
        result.definitions = defs;
      }
    }
  }
  try {
    const finalized = JSON.parse(JSON.stringify(result));
    Object.defineProperty(finalized, "~standard", {
      value: {
        ...schema["~standard"],
        jsonSchema: {
          input: createStandardJSONSchemaMethod(schema, "input", ctx.processors),
          output: createStandardJSONSchemaMethod(schema, "output", ctx.processors)
        }
      },
      enumerable: false,
      writable: false
    });
    return finalized;
  } catch (_err) {
    throw new Error("Error converting schema to JSON.");
  }
}
function isTransforming(_schema, _ctx) {
  const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() };
  if (ctx.seen.has(_schema))
    return false;
  ctx.seen.add(_schema);
  const def = _schema._zod.def;
  if (def.type === "transform")
    return true;
  if (def.type === "array")
    return isTransforming(def.element, ctx);
  if (def.type === "set")
    return isTransforming(def.valueType, ctx);
  if (def.type === "lazy")
    return isTransforming(def.getter(), ctx);
  if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") {
    return isTransforming(def.innerType, ctx);
  }
  if (def.type === "intersection") {
    return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
  }
  if (def.type === "record" || def.type === "map") {
    return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
  }
  if (def.type === "pipe") {
    if (_schema._zod.traits.has("$ZodCodec"))
      return true;
    return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
  }
  if (def.type === "object") {
    for (const key in def.shape) {
      if (isTransforming(def.shape[key], ctx))
        return true;
    }
    return false;
  }
  if (def.type === "union") {
    for (const option of def.options) {
      if (isTransforming(option, ctx))
        return true;
    }
    return false;
  }
  if (def.type === "tuple") {
    for (const item of def.items) {
      if (isTransforming(item, ctx))
        return true;
    }
    if (def.rest && isTransforming(def.rest, ctx))
      return true;
    return false;
  }
  return false;
}
var createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
  const ctx = initializeContext({ ...params, processors });
  process2(schema, ctx);
  extractDefs(ctx, schema);
  return finalize(ctx, schema);
};
var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
  const { libraryOptions, target } = params ?? {};
  const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors });
  process2(schema, ctx);
  extractDefs(ctx, schema);
  return finalize(ctx, schema);
};

// node_modules/zod/v4/core/json-schema-processors.js
var formatMap = {
  guid: "uuid",
  url: "uri",
  datetime: "date-time",
  json_string: "json-string",
  regex: ""
  // do not set
};
var stringProcessor = (schema, ctx, _json, _params) => {
  const json2 = _json;
  json2.type = "string";
  const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag;
  if (typeof minimum === "number")
    json2.minLength = minimum;
  if (typeof maximum === "number")
    json2.maxLength = maximum;
  if (format) {
    json2.format = formatMap[format] ?? format;
    if (json2.format === "")
      delete json2.format;
    if (format === "time") {
      delete json2.format;
    }
  }
  if (contentEncoding)
    json2.contentEncoding = contentEncoding;
  if (patterns && patterns.size > 0) {
    const regexes = [...patterns];
    if (regexes.length === 1)
      json2.pattern = regexes[0].source;
    else if (regexes.length > 1) {
      json2.allOf = [
        ...regexes.map((regex) => ({
          ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {},
          pattern: regex.source
        }))
      ];
    }
  }
};
var numberProcessor = (schema, ctx, _json, _params) => {
  const json2 = _json;
  const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
  if (typeof format === "string" && format.includes("int"))
    json2.type = "integer";
  else
    json2.type = "number";
  const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
  const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
  const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
  if (exMin) {
    if (legacy) {
      json2.minimum = exclusiveMinimum;
      json2.exclusiveMinimum = true;
    } else {
      json2.exclusiveMinimum = exclusiveMinimum;
    }
  } else if (typeof minimum === "number") {
    json2.minimum = minimum;
  }
  if (exMax) {
    if (legacy) {
      json2.maximum = exclusiveMaximum;
      json2.exclusiveMaximum = true;
    } else {
      json2.exclusiveMaximum = exclusiveMaximum;
    }
  } else if (typeof maximum === "number") {
    json2.maximum = maximum;
  }
  if (typeof multipleOf === "number")
    json2.multipleOf = multipleOf;
};
var booleanProcessor = (_schema, _ctx, json2, _params) => {
  json2.type = "boolean";
};
var bigintProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("BigInt cannot be represented in JSON Schema");
  }
};
var symbolProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Symbols cannot be represented in JSON Schema");
  }
};
var nullProcessor = (_schema, ctx, json2, _params) => {
  if (ctx.target === "openapi-3.0") {
    json2.type = "string";
    json2.nullable = true;
    json2.enum = [null];
  } else {
    json2.type = "null";
  }
};
var undefinedProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Undefined cannot be represented in JSON Schema");
  }
};
var voidProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Void cannot be represented in JSON Schema");
  }
};
var neverProcessor = (_schema, _ctx, json2, _params) => {
  json2.not = {};
};
var anyProcessor = (_schema, _ctx, _json, _params) => {
};
var unknownProcessor = (_schema, _ctx, _json, _params) => {
};
var dateProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Date cannot be represented in JSON Schema");
  }
};
var enumProcessor = (schema, _ctx, json2, _params) => {
  const def = schema._zod.def;
  const values = getEnumValues(def.entries);
  if (values.every((v) => typeof v === "number"))
    json2.type = "number";
  if (values.every((v) => typeof v === "string"))
    json2.type = "string";
  json2.enum = values;
};
var literalProcessor = (schema, ctx, json2, _params) => {
  const def = schema._zod.def;
  const vals = [];
  for (const val of def.values) {
    if (val === void 0) {
      if (ctx.unrepresentable === "throw") {
        throw new Error("Literal `undefined` cannot be represented in JSON Schema");
      } else {
      }
    } else if (typeof val === "bigint") {
      if (ctx.unrepresentable === "throw") {
        throw new Error("BigInt literals cannot be represented in JSON Schema");
      } else {
        vals.push(Number(val));
      }
    } else {
      vals.push(val);
    }
  }
  if (vals.length === 0) {
  } else if (vals.length === 1) {
    const val = vals[0];
    json2.type = val === null ? "null" : typeof val;
    if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
      json2.enum = [val];
    } else {
      json2.const = val;
    }
  } else {
    if (vals.every((v) => typeof v === "number"))
      json2.type = "number";
    if (vals.every((v) => typeof v === "string"))
      json2.type = "string";
    if (vals.every((v) => typeof v === "boolean"))
      json2.type = "boolean";
    if (vals.every((v) => v === null))
      json2.type = "null";
    json2.enum = vals;
  }
};
var nanProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("NaN cannot be represented in JSON Schema");
  }
};
var templateLiteralProcessor = (schema, _ctx, json2, _params) => {
  const _json = json2;
  const pattern = schema._zod.pattern;
  if (!pattern)
    throw new Error("Pattern not found in template literal");
  _json.type = "string";
  _json.pattern = pattern.source;
};
var fileProcessor = (schema, _ctx, json2, _params) => {
  const _json = json2;
  const file2 = {
    type: "string",
    format: "binary",
    contentEncoding: "binary"
  };
  const { minimum, maximum, mime } = schema._zod.bag;
  if (minimum !== void 0)
    file2.minLength = minimum;
  if (maximum !== void 0)
    file2.maxLength = maximum;
  if (mime) {
    if (mime.length === 1) {
      file2.contentMediaType = mime[0];
      Object.assign(_json, file2);
    } else {
      Object.assign(_json, file2);
      _json.anyOf = mime.map((m2) => ({ contentMediaType: m2 }));
    }
  } else {
    Object.assign(_json, file2);
  }
};
var successProcessor = (_schema, _ctx, json2, _params) => {
  json2.type = "boolean";
};
var customProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Custom types cannot be represented in JSON Schema");
  }
};
var functionProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Function types cannot be represented in JSON Schema");
  }
};
var transformProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Transforms cannot be represented in JSON Schema");
  }
};
var mapProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Map cannot be represented in JSON Schema");
  }
};
var setProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Set cannot be represented in JSON Schema");
  }
};
var arrayProcessor = (schema, ctx, _json, params) => {
  const json2 = _json;
  const def = schema._zod.def;
  const { minimum, maximum } = schema._zod.bag;
  if (typeof minimum === "number")
    json2.minItems = minimum;
  if (typeof maximum === "number")
    json2.maxItems = maximum;
  json2.type = "array";
  json2.items = process2(def.element, ctx, {
    ...params,
    path: [...params.path, "items"]
  });
};
var objectProcessor = (schema, ctx, _json, params) => {
  const json2 = _json;
  const def = schema._zod.def;
  json2.type = "object";
  json2.properties = {};
  const shape = def.shape;
  for (const key in shape) {
    json2.properties[key] = process2(shape[key], ctx, {
      ...params,
      path: [...params.path, "properties", key]
    });
  }
  const allKeys = new Set(Object.keys(shape));
  const requiredKeys = new Set([...allKeys].filter((key) => {
    const v = def.shape[key]._zod;
    if (ctx.io === "input") {
      return v.optin === void 0;
    } else {
      return v.optout === void 0;
    }
  }));
  if (requiredKeys.size > 0) {
    json2.required = Array.from(requiredKeys);
  }
  if (def.catchall?._zod.def.type === "never") {
    json2.additionalProperties = false;
  } else if (!def.catchall) {
    if (ctx.io === "output")
      json2.additionalProperties = false;
  } else if (def.catchall) {
    json2.additionalProperties = process2(def.catchall, ctx, {
      ...params,
      path: [...params.path, "additionalProperties"]
    });
  }
};
var unionProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  const isExclusive = def.inclusive === false;
  const options = def.options.map((x2, i2) => process2(x2, ctx, {
    ...params,
    path: [...params.path, isExclusive ? "oneOf" : "anyOf", i2]
  }));
  if (isExclusive) {
    json2.oneOf = options;
  } else {
    json2.anyOf = options;
  }
};
var intersectionProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  const a = process2(def.left, ctx, {
    ...params,
    path: [...params.path, "allOf", 0]
  });
  const b = process2(def.right, ctx, {
    ...params,
    path: [...params.path, "allOf", 1]
  });
  const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
  const allOf = [
    ...isSimpleIntersection(a) ? a.allOf : [a],
    ...isSimpleIntersection(b) ? b.allOf : [b]
  ];
  json2.allOf = allOf;
};
var tupleProcessor = (schema, ctx, _json, params) => {
  const json2 = _json;
  const def = schema._zod.def;
  json2.type = "array";
  const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items";
  const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems";
  const prefixItems = def.items.map((x2, i2) => process2(x2, ctx, {
    ...params,
    path: [...params.path, prefixPath, i2]
  }));
  const rest = def.rest ? process2(def.rest, ctx, {
    ...params,
    path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []]
  }) : null;
  if (ctx.target === "draft-2020-12") {
    json2.prefixItems = prefixItems;
    if (rest) {
      json2.items = rest;
    }
  } else if (ctx.target === "openapi-3.0") {
    json2.items = {
      anyOf: prefixItems
    };
    if (rest) {
      json2.items.anyOf.push(rest);
    }
    json2.minItems = prefixItems.length;
    if (!rest) {
      json2.maxItems = prefixItems.length;
    }
  } else {
    json2.items = prefixItems;
    if (rest) {
      json2.additionalItems = rest;
    }
  }
  const { minimum, maximum } = schema._zod.bag;
  if (typeof minimum === "number")
    json2.minItems = minimum;
  if (typeof maximum === "number")
    json2.maxItems = maximum;
};
var recordProcessor = (schema, ctx, _json, params) => {
  const json2 = _json;
  const def = schema._zod.def;
  json2.type = "object";
  const keyType = def.keyType;
  const keyBag = keyType._zod.bag;
  const patterns = keyBag?.patterns;
  if (def.mode === "loose" && patterns && patterns.size > 0) {
    const valueSchema = process2(def.valueType, ctx, {
      ...params,
      path: [...params.path, "patternProperties", "*"]
    });
    json2.patternProperties = {};
    for (const pattern of patterns) {
      json2.patternProperties[pattern.source] = valueSchema;
    }
  } else {
    if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
      json2.propertyNames = process2(def.keyType, ctx, {
        ...params,
        path: [...params.path, "propertyNames"]
      });
    }
    json2.additionalProperties = process2(def.valueType, ctx, {
      ...params,
      path: [...params.path, "additionalProperties"]
    });
  }
  const keyValues = keyType._zod.values;
  if (keyValues) {
    const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number");
    if (validKeyValues.length > 0) {
      json2.required = validKeyValues;
    }
  }
};
var nullableProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  const inner = process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  if (ctx.target === "openapi-3.0") {
    seen.ref = def.innerType;
    json2.nullable = true;
  } else {
    json2.anyOf = [inner, { type: "null" }];
  }
};
var nonoptionalProcessor = (schema, ctx, _json, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
};
var defaultProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  json2.default = JSON.parse(JSON.stringify(def.defaultValue));
};
var prefaultProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  if (ctx.io === "input")
    json2._prefault = JSON.parse(JSON.stringify(def.defaultValue));
};
var catchProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  let catchValue;
  try {
    catchValue = def.catchValue(void 0);
  } catch {
    throw new Error("Dynamic catch values are not supported in JSON Schema");
  }
  json2.default = catchValue;
};
var pipeProcessor = (schema, ctx, _json, params) => {
  const def = schema._zod.def;
  const inIsTransform = def.in._zod.traits.has("$ZodTransform");
  const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out;
  process2(innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = innerType;
};
var readonlyProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  json2.readOnly = true;
};
var promiseProcessor = (schema, ctx, _json, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
};
var optionalProcessor = (schema, ctx, _json, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
};
var lazyProcessor = (schema, ctx, _json, params) => {
  const innerType = schema._zod.innerType;
  process2(innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = innerType;
};
var allProcessors = {
  string: stringProcessor,
  number: numberProcessor,
  boolean: booleanProcessor,
  bigint: bigintProcessor,
  symbol: symbolProcessor,
  null: nullProcessor,
  undefined: undefinedProcessor,
  void: voidProcessor,
  never: neverProcessor,
  any: anyProcessor,
  unknown: unknownProcessor,
  date: dateProcessor,
  enum: enumProcessor,
  literal: literalProcessor,
  nan: nanProcessor,
  template_literal: templateLiteralProcessor,
  file: fileProcessor,
  success: successProcessor,
  custom: customProcessor,
  function: functionProcessor,
  transform: transformProcessor,
  map: mapProcessor,
  set: setProcessor,
  array: arrayProcessor,
  object: objectProcessor,
  union: unionProcessor,
  intersection: intersectionProcessor,
  tuple: tupleProcessor,
  record: recordProcessor,
  nullable: nullableProcessor,
  nonoptional: nonoptionalProcessor,
  default: defaultProcessor,
  prefault: prefaultProcessor,
  catch: catchProcessor,
  pipe: pipeProcessor,
  readonly: readonlyProcessor,
  promise: promiseProcessor,
  optional: optionalProcessor,
  lazy: lazyProcessor
};
function toJSONSchema(input, params) {
  if ("_idmap" in input) {
    const registry2 = input;
    const ctx2 = initializeContext({ ...params, processors: allProcessors });
    const defs = {};
    for (const entry of registry2._idmap.entries()) {
      const [_, schema] = entry;
      process2(schema, ctx2);
    }
    const schemas = {};
    const external = {
      registry: registry2,
      uri: params?.uri,
      defs
    };
    ctx2.external = external;
    for (const entry of registry2._idmap.entries()) {
      const [key, schema] = entry;
      extractDefs(ctx2, schema);
      schemas[key] = finalize(ctx2, schema);
    }
    if (Object.keys(defs).length > 0) {
      const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions";
      schemas.__shared = {
        [defsSegment]: defs
      };
    }
    return { schemas };
  }
  const ctx = initializeContext({ ...params, processors: allProcessors });
  process2(input, ctx);
  extractDefs(ctx, input);
  return finalize(ctx, input);
}

// node_modules/zod/v4/core/json-schema-generator.js
var JSONSchemaGenerator = class {
  /** @deprecated Access via ctx instead */
  get metadataRegistry() {
    return this.ctx.metadataRegistry;
  }
  /** @deprecated Access via ctx instead */
  get target() {
    return this.ctx.target;
  }
  /** @deprecated Access via ctx instead */
  get unrepresentable() {
    return this.ctx.unrepresentable;
  }
  /** @deprecated Access via ctx instead */
  get override() {
    return this.ctx.override;
  }
  /** @deprecated Access via ctx instead */
  get io() {
    return this.ctx.io;
  }
  /** @deprecated Access via ctx instead */
  get counter() {
    return this.ctx.counter;
  }
  set counter(value) {
    this.ctx.counter = value;
  }
  /** @deprecated Access via ctx instead */
  get seen() {
    return this.ctx.seen;
  }
  constructor(params) {
    let normalizedTarget = params?.target ?? "draft-2020-12";
    if (normalizedTarget === "draft-4")
      normalizedTarget = "draft-04";
    if (normalizedTarget === "draft-7")
      normalizedTarget = "draft-07";
    this.ctx = initializeContext({
      processors: allProcessors,
      target: normalizedTarget,
      ...params?.metadata && { metadata: params.metadata },
      ...params?.unrepresentable && { unrepresentable: params.unrepresentable },
      ...params?.override && { override: params.override },
      ...params?.io && { io: params.io }
    });
  }
  /**
   * Process a schema to prepare it for JSON Schema generation.
   * This must be called before emit().
   */
  process(schema, _params = { path: [], schemaPath: [] }) {
    return process2(schema, this.ctx, _params);
  }
  /**
   * Emit the final JSON Schema after processing.
   * Must call process() first.
   */
  emit(schema, _params) {
    if (_params) {
      if (_params.cycles)
        this.ctx.cycles = _params.cycles;
      if (_params.reused)
        this.ctx.reused = _params.reused;
      if (_params.external)
        this.ctx.external = _params.external;
    }
    extractDefs(this.ctx, schema);
    const result = finalize(this.ctx, schema);
    const { "~standard": _, ...plainResult } = result;
    return plainResult;
  }
};

// node_modules/zod/v4/core/json-schema.js
var json_schema_exports = {};

// node_modules/zod/v4/classic/schemas.js
var schemas_exports2 = {};
__export(schemas_exports2, {
  ZodAny: () => ZodAny,
  ZodArray: () => ZodArray,
  ZodBase64: () => ZodBase64,
  ZodBase64URL: () => ZodBase64URL,
  ZodBigInt: () => ZodBigInt,
  ZodBigIntFormat: () => ZodBigIntFormat,
  ZodBoolean: () => ZodBoolean,
  ZodCIDRv4: () => ZodCIDRv4,
  ZodCIDRv6: () => ZodCIDRv6,
  ZodCUID: () => ZodCUID,
  ZodCUID2: () => ZodCUID2,
  ZodCatch: () => ZodCatch,
  ZodCodec: () => ZodCodec,
  ZodCustom: () => ZodCustom,
  ZodCustomStringFormat: () => ZodCustomStringFormat,
  ZodDate: () => ZodDate,
  ZodDefault: () => ZodDefault,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
  ZodE164: () => ZodE164,
  ZodEmail: () => ZodEmail,
  ZodEmoji: () => ZodEmoji,
  ZodEnum: () => ZodEnum,
  ZodExactOptional: () => ZodExactOptional,
  ZodFile: () => ZodFile,
  ZodFunction: () => ZodFunction,
  ZodGUID: () => ZodGUID,
  ZodIPv4: () => ZodIPv4,
  ZodIPv6: () => ZodIPv6,
  ZodIntersection: () => ZodIntersection,
  ZodJWT: () => ZodJWT,
  ZodKSUID: () => ZodKSUID,
  ZodLazy: () => ZodLazy,
  ZodLiteral: () => ZodLiteral,
  ZodMAC: () => ZodMAC,
  ZodMap: () => ZodMap,
  ZodNaN: () => ZodNaN,
  ZodNanoID: () => ZodNanoID,
  ZodNever: () => ZodNever,
  ZodNonOptional: () => ZodNonOptional,
  ZodNull: () => ZodNull,
  ZodNullable: () => ZodNullable,
  ZodNumber: () => ZodNumber,
  ZodNumberFormat: () => ZodNumberFormat,
  ZodObject: () => ZodObject,
  ZodOptional: () => ZodOptional,
  ZodPipe: () => ZodPipe,
  ZodPrefault: () => ZodPrefault,
  ZodPreprocess: () => ZodPreprocess,
  ZodPromise: () => ZodPromise,
  ZodReadonly: () => ZodReadonly,
  ZodRecord: () => ZodRecord,
  ZodSet: () => ZodSet,
  ZodString: () => ZodString,
  ZodStringFormat: () => ZodStringFormat,
  ZodSuccess: () => ZodSuccess,
  ZodSymbol: () => ZodSymbol,
  ZodTemplateLiteral: () => ZodTemplateLiteral,
  ZodTransform: () => ZodTransform,
  ZodTuple: () => ZodTuple,
  ZodType: () => ZodType,
  ZodULID: () => ZodULID,
  ZodURL: () => ZodURL,
  ZodUUID: () => ZodUUID,
  ZodUndefined: () => ZodUndefined,
  ZodUnion: () => ZodUnion,
  ZodUnknown: () => ZodUnknown,
  ZodVoid: () => ZodVoid,
  ZodXID: () => ZodXID,
  ZodXor: () => ZodXor,
  _ZodString: () => _ZodString,
  _default: () => _default2,
  _function: () => _function,
  any: () => any,
  array: () => array,
  base64: () => base642,
  base64url: () => base64url2,
  bigint: () => bigint2,
  boolean: () => boolean2,
  catch: () => _catch2,
  check: () => check,
  cidrv4: () => cidrv42,
  cidrv6: () => cidrv62,
  codec: () => codec,
  cuid: () => cuid3,
  cuid2: () => cuid22,
  custom: () => custom,
  date: () => date3,
  describe: () => describe2,
  discriminatedUnion: () => discriminatedUnion,
  e164: () => e1642,
  email: () => email2,
  emoji: () => emoji2,
  enum: () => _enum2,
  exactOptional: () => exactOptional,
  file: () => file,
  float32: () => float32,
  float64: () => float64,
  function: () => _function,
  guid: () => guid2,
  hash: () => hash,
  hex: () => hex2,
  hostname: () => hostname2,
  httpUrl: () => httpUrl,
  instanceof: () => _instanceof,
  int: () => int,
  int32: () => int32,
  int64: () => int64,
  intersection: () => intersection,
  invertCodec: () => invertCodec,
  ipv4: () => ipv42,
  ipv6: () => ipv62,
  json: () => json,
  jwt: () => jwt,
  keyof: () => keyof,
  ksuid: () => ksuid2,
  lazy: () => lazy,
  literal: () => literal,
  looseObject: () => looseObject,
  looseRecord: () => looseRecord,
  mac: () => mac2,
  map: () => map,
  meta: () => meta2,
  nan: () => nan,
  nanoid: () => nanoid2,
  nativeEnum: () => nativeEnum,
  never: () => never,
  nonoptional: () => nonoptional,
  null: () => _null3,
  nullable: () => nullable,
  nullish: () => nullish2,
  number: () => number2,
  object: () => object,
  optional: () => optional,
  partialRecord: () => partialRecord,
  pipe: () => pipe,
  prefault: () => prefault,
  preprocess: () => preprocess,
  promise: () => promise,
  readonly: () => readonly,
  record: () => record,
  refine: () => refine,
  set: () => set,
  strictObject: () => strictObject,
  string: () => string2,
  stringFormat: () => stringFormat,
  stringbool: () => stringbool,
  success: () => success,
  superRefine: () => superRefine,
  symbol: () => symbol,
  templateLiteral: () => templateLiteral,
  transform: () => transform,
  tuple: () => tuple,
  uint32: () => uint32,
  uint64: () => uint64,
  ulid: () => ulid2,
  undefined: () => _undefined3,
  union: () => union,
  unknown: () => unknown,
  url: () => url,
  uuid: () => uuid2,
  uuidv4: () => uuidv4,
  uuidv6: () => uuidv6,
  uuidv7: () => uuidv7,
  void: () => _void2,
  xid: () => xid2,
  xor: () => xor
});

// node_modules/zod/v4/classic/checks.js
var checks_exports2 = {};
__export(checks_exports2, {
  endsWith: () => _endsWith,
  gt: () => _gt,
  gte: () => _gte,
  includes: () => _includes,
  length: () => _length,
  lowercase: () => _lowercase,
  lt: () => _lt,
  lte: () => _lte,
  maxLength: () => _maxLength,
  maxSize: () => _maxSize,
  mime: () => _mime,
  minLength: () => _minLength,
  minSize: () => _minSize,
  multipleOf: () => _multipleOf,
  negative: () => _negative,
  nonnegative: () => _nonnegative,
  nonpositive: () => _nonpositive,
  normalize: () => _normalize,
  overwrite: () => _overwrite,
  positive: () => _positive,
  property: () => _property,
  regex: () => _regex,
  size: () => _size,
  slugify: () => _slugify,
  startsWith: () => _startsWith,
  toLowerCase: () => _toLowerCase,
  toUpperCase: () => _toUpperCase,
  trim: () => _trim,
  uppercase: () => _uppercase
});

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

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

// node_modules/zod/v4/classic/parse.js
var parse2 = /* @__PURE__ */ _parse(ZodRealError);
var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError);
var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
var encode2 = /* @__PURE__ */ _encode(ZodRealError);
var decode2 = /* @__PURE__ */ _decode(ZodRealError);
var encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError);
var decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError);
var safeEncode2 = /* @__PURE__ */ _safeEncode(ZodRealError);
var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError);
var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);

// node_modules/zod/v4/classic/schemas.js
var _installedGroups = /* @__PURE__ */ new WeakMap();
function _installLazyMethods(inst, group, methods) {
  const proto = Object.getPrototypeOf(inst);
  let installed = _installedGroups.get(proto);
  if (!installed) {
    installed = /* @__PURE__ */ new Set();
    _installedGroups.set(proto, installed);
  }
  if (installed.has(group))
    return;
  installed.add(group);
  for (const key in methods) {
    const fn = methods[key];
    Object.defineProperty(proto, key, {
      configurable: true,
      enumerable: false,
      get() {
        const bound = fn.bind(this);
        Object.defineProperty(this, key, {
          configurable: true,
          writable: true,
          enumerable: true,
          value: bound
        });
        return bound;
      },
      set(v) {
        Object.defineProperty(this, key, {
          configurable: true,
          writable: true,
          enumerable: true,
          value: v
        });
      }
    });
  }
}
var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
  $ZodType.init(inst, def);
  Object.assign(inst["~standard"], {
    jsonSchema: {
      input: createStandardJSONSchemaMethod(inst, "input"),
      output: createStandardJSONSchemaMethod(inst, "output")
    }
  });
  inst.toJSONSchema = createToJSONSchemaMethod(inst, {});
  inst.def = def;
  inst.type = def.type;
  Object.defineProperty(inst, "_def", { value: def });
  inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse });
  inst.safeParse = (data, params) => safeParse2(inst, data, params);
  inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync });
  inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params);
  inst.spa = inst.safeParseAsync;
  inst.encode = (data, params) => encode2(inst, data, params);
  inst.decode = (data, params) => decode2(inst, data, params);
  inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params);
  inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params);
  inst.safeEncode = (data, params) => safeEncode2(inst, data, params);
  inst.safeDecode = (data, params) => safeDecode2(inst, data, params);
  inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params);
  inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params);
  _installLazyMethods(inst, "ZodType", {
    check(...chks) {
      const def2 = this.def;
      return this.clone(util_exports.mergeDefs(def2, {
        checks: [
          ...def2.checks ?? [],
          ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
        ]
      }), { parent: true });
    },
    with(...chks) {
      return this.check(...chks);
    },
    clone(def2, params) {
      return clone(this, def2, params);
    },
    brand() {
      return this;
    },
    register(reg, meta3) {
      reg.add(this, meta3);
      return this;
    },
    refine(check2, params) {
      return this.check(refine(check2, params));
    },
    superRefine(refinement, params) {
      return this.check(superRefine(refinement, params));
    },
    overwrite(fn) {
      return this.check(_overwrite(fn));
    },
    optional() {
      return optional(this);
    },
    exactOptional() {
      return exactOptional(this);
    },
    nullable() {
      return nullable(this);
    },
    nullish() {
      return optional(nullable(this));
    },
    nonoptional(params) {
      return nonoptional(this, params);
    },
    array() {
      return array(this);
    },
    or(arg) {
      return union([this, arg]);
    },
    and(arg) {
      return intersection(this, arg);
    },
    transform(tx) {
      return pipe(this, transform(tx));
    },
    default(d) {
      return _default2(this, d);
    },
    prefault(d) {
      return prefault(this, d);
    },
    catch(params) {
      return _catch2(this, params);
    },
    pipe(target) {
      return pipe(this, target);
    },
    readonly() {
      return readonly(this);
    },
    describe(description) {
      const cl = this.clone();
      globalRegistry.add(cl, { description });
      return cl;
    },
    meta(...args) {
      if (args.length === 0)
        return globalRegistry.get(this);
      const cl = this.clone();
      globalRegistry.add(cl, args[0]);
      return cl;
    },
    isOptional() {
      return this.safeParse(void 0).success;
    },
    isNullable() {
      return this.safeParse(null).success;
    },
    apply(fn) {
      return fn(this);
    }
  });
  Object.defineProperty(inst, "description", {
    get() {
      return globalRegistry.get(inst)?.description;
    },
    configurable: true
  });
  return inst;
});
var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
  $ZodString.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => stringProcessor(inst, ctx, json2, params);
  const bag = inst._zod.bag;
  inst.format = bag.format ?? null;
  inst.minLength = bag.minimum ?? null;
  inst.maxLength = bag.maximum ?? null;
  _installLazyMethods(inst, "_ZodString", {
    regex(...args) {
      return this.check(_regex(...args));
    },
    includes(...args) {
      return this.check(_includes(...args));
    },
    startsWith(...args) {
      return this.check(_startsWith(...args));
    },
    endsWith(...args) {
      return this.check(_endsWith(...args));
    },
    min(...args) {
      return this.check(_minLength(...args));
    },
    max(...args) {
      return this.check(_maxLength(...args));
    },
    length(...args) {
      return this.check(_length(...args));
    },
    nonempty(...args) {
      return this.check(_minLength(1, ...args));
    },
    lowercase(params) {
      return this.check(_lowercase(params));
    },
    uppercase(params) {
      return this.check(_uppercase(params));
    },
    trim() {
      return this.check(_trim());
    },
    normalize(...args) {
      return this.check(_normalize(...args));
    },
    toLowerCase() {
      return this.check(_toLowerCase());
    },
    toUpperCase() {
      return this.check(_toUpperCase());
    },
    slugify() {
      return this.check(_slugify());
    }
  });
});
var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
  $ZodString.init(inst, def);
  _ZodString.init(inst, def);
  inst.email = (params) => inst.check(_email(ZodEmail, params));
  inst.url = (params) => inst.check(_url(ZodURL, params));
  inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
  inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params));
  inst.guid = (params) => inst.check(_guid(ZodGUID, params));
  inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
  inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
  inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
  inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
  inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
  inst.guid = (params) => inst.check(_guid(ZodGUID, params));
  inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
  inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
  inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
  inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
  inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
  inst.xid = (params) => inst.check(_xid(ZodXID, params));
  inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
  inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
  inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
  inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
  inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
  inst.e164 = (params) => inst.check(_e164(ZodE164, params));
  inst.datetime = (params) => inst.check(datetime2(params));
  inst.date = (params) => inst.check(date2(params));
  inst.time = (params) => inst.check(time2(params));
  inst.duration = (params) => inst.check(duration2(params));
});
function string2(params) {
  return _string(ZodString, params);
}
var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  _ZodString.init(inst, def);
});
var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
  $ZodEmail.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function email2(params) {
  return _email(ZodEmail, params);
}
var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {
  $ZodGUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function guid2(params) {
  return _guid(ZodGUID, params);
}
var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {
  $ZodUUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function uuid2(params) {
  return _uuid(ZodUUID, params);
}
function uuidv4(params) {
  return _uuidv4(ZodUUID, params);
}
function uuidv6(params) {
  return _uuidv6(ZodUUID, params);
}
function uuidv7(params) {
  return _uuidv7(ZodUUID, params);
}
var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
  $ZodURL.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function url(params) {
  return _url(ZodURL, params);
}
function httpUrl(params) {
  return _url(ZodURL, {
    protocol: regexes_exports.httpProtocol,
    hostname: regexes_exports.domain,
    ...util_exports.normalizeParams(params)
  });
}
var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
  $ZodEmoji.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function emoji2(params) {
  return _emoji2(ZodEmoji, params);
}
var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {
  $ZodNanoID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function nanoid2(params) {
  return _nanoid(ZodNanoID, params);
}
var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {
  $ZodCUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function cuid3(params) {
  return _cuid(ZodCUID, params);
}
var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {
  $ZodCUID2.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function cuid22(params) {
  return _cuid2(ZodCUID2, params);
}
var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {
  $ZodULID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function ulid2(params) {
  return _ulid(ZodULID, params);
}
var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {
  $ZodXID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function xid2(params) {
  return _xid(ZodXID, params);
}
var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {
  $ZodKSUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function ksuid2(params) {
  return _ksuid(ZodKSUID, params);
}
var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {
  $ZodIPv4.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function ipv42(params) {
  return _ipv4(ZodIPv4, params);
}
var ZodMAC = /* @__PURE__ */ $constructor("ZodMAC", (inst, def) => {
  $ZodMAC.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function mac2(params) {
  return _mac(ZodMAC, params);
}
var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {
  $ZodIPv6.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function ipv62(params) {
  return _ipv6(ZodIPv6, params);
}
var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {
  $ZodCIDRv4.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function cidrv42(params) {
  return _cidrv4(ZodCIDRv4, params);
}
var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {
  $ZodCIDRv6.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function cidrv62(params) {
  return _cidrv6(ZodCIDRv6, params);
}
var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {
  $ZodBase64.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function base642(params) {
  return _base64(ZodBase64, params);
}
var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {
  $ZodBase64URL.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function base64url2(params) {
  return _base64url(ZodBase64URL, params);
}
var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {
  $ZodE164.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function e1642(params) {
  return _e164(ZodE164, params);
}
var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {
  $ZodJWT.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function jwt(params) {
  return _jwt(ZodJWT, params);
}
var ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => {
  $ZodCustomStringFormat.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function stringFormat(format, fnOrRegex, _params = {}) {
  return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);
}
function hostname2(_params) {
  return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params);
}
function hex2(_params) {
  return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params);
}
function hash(alg, params) {
  const enc = params?.enc ?? "hex";
  const format = `${alg}_${enc}`;
  const regex = regexes_exports[format];
  if (!regex)
    throw new Error(`Unrecognized hash format: ${format}`);
  return _stringFormat(ZodCustomStringFormat, format, regex, params);
}
var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
  $ZodNumber.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => numberProcessor(inst, ctx, json2, params);
  _installLazyMethods(inst, "ZodNumber", {
    gt(value, params) {
      return this.check(_gt(value, params));
    },
    gte(value, params) {
      return this.check(_gte(value, params));
    },
    min(value, params) {
      return this.check(_gte(value, params));
    },
    lt(value, params) {
      return this.check(_lt(value, params));
    },
    lte(value, params) {
      return this.check(_lte(value, params));
    },
    max(value, params) {
      return this.check(_lte(value, params));
    },
    int(params) {
      return this.check(int(params));
    },
    safe(params) {
      return this.check(int(params));
    },
    positive(params) {
      return this.check(_gt(0, params));
    },
    nonnegative(params) {
      return this.check(_gte(0, params));
    },
    negative(params) {
      return this.check(_lt(0, params));
    },
    nonpositive(params) {
      return this.check(_lte(0, params));
    },
    multipleOf(value, params) {
      return this.check(_multipleOf(value, params));
    },
    step(value, params) {
      return this.check(_multipleOf(value, params));
    },
    finite() {
      return this;
    }
  });
  const bag = inst._zod.bag;
  inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
  inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
  inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5);
  inst.isFinite = true;
  inst.format = bag.format ?? null;
});
function number2(params) {
  return _number(ZodNumber, params);
}
var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
  $ZodNumberFormat.init(inst, def);
  ZodNumber.init(inst, def);
});
function int(params) {
  return _int(ZodNumberFormat, params);
}
function float32(params) {
  return _float32(ZodNumberFormat, params);
}
function float64(params) {
  return _float64(ZodNumberFormat, params);
}
function int32(params) {
  return _int32(ZodNumberFormat, params);
}
function uint32(params) {
  return _uint32(ZodNumberFormat, params);
}
var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => {
  $ZodBoolean.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => booleanProcessor(inst, ctx, json2, params);
});
function boolean2(params) {
  return _boolean(ZodBoolean, params);
}
var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => {
  $ZodBigInt.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => bigintProcessor(inst, ctx, json2, params);
  inst.gte = (value, params) => inst.check(_gte(value, params));
  inst.min = (value, params) => inst.check(_gte(value, params));
  inst.gt = (value, params) => inst.check(_gt(value, params));
  inst.gte = (value, params) => inst.check(_gte(value, params));
  inst.min = (value, params) => inst.check(_gte(value, params));
  inst.lt = (value, params) => inst.check(_lt(value, params));
  inst.lte = (value, params) => inst.check(_lte(value, params));
  inst.max = (value, params) => inst.check(_lte(value, params));
  inst.positive = (params) => inst.check(_gt(BigInt(0), params));
  inst.negative = (params) => inst.check(_lt(BigInt(0), params));
  inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params));
  inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params));
  inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
  const bag = inst._zod.bag;
  inst.minValue = bag.minimum ?? null;
  inst.maxValue = bag.maximum ?? null;
  inst.format = bag.format ?? null;
});
function bigint2(params) {
  return _bigint(ZodBigInt, params);
}
var ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => {
  $ZodBigIntFormat.init(inst, def);
  ZodBigInt.init(inst, def);
});
function int64(params) {
  return _int64(ZodBigIntFormat, params);
}
function uint64(params) {
  return _uint64(ZodBigIntFormat, params);
}
var ZodSymbol = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => {
  $ZodSymbol.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => symbolProcessor(inst, ctx, json2, params);
});
function symbol(params) {
  return _symbol(ZodSymbol, params);
}
var ZodUndefined = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => {
  $ZodUndefined.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => undefinedProcessor(inst, ctx, json2, params);
});
function _undefined3(params) {
  return _undefined2(ZodUndefined, params);
}
var ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => {
  $ZodNull.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => nullProcessor(inst, ctx, json2, params);
});
function _null3(params) {
  return _null2(ZodNull, params);
}
var ZodAny = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => {
  $ZodAny.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => anyProcessor(inst, ctx, json2, params);
});
function any() {
  return _any(ZodAny);
}
var ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
  $ZodUnknown.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => unknownProcessor(inst, ctx, json2, params);
});
function unknown() {
  return _unknown(ZodUnknown);
}
var ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
  $ZodNever.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => neverProcessor(inst, ctx, json2, params);
});
function never(params) {
  return _never(ZodNever, params);
}
var ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => {
  $ZodVoid.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => voidProcessor(inst, ctx, json2, params);
});
function _void2(params) {
  return _void(ZodVoid, params);
}
var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => {
  $ZodDate.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => dateProcessor(inst, ctx, json2, params);
  inst.min = (value, params) => inst.check(_gte(value, params));
  inst.max = (value, params) => inst.check(_lte(value, params));
  const c = inst._zod.bag;
  inst.minDate = c.minimum ? new Date(c.minimum) : null;
  inst.maxDate = c.maximum ? new Date(c.maximum) : null;
});
function date3(params) {
  return _date(ZodDate, params);
}
var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
  $ZodArray.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => arrayProcessor(inst, ctx, json2, params);
  inst.element = def.element;
  _installLazyMethods(inst, "ZodArray", {
    min(n, params) {
      return this.check(_minLength(n, params));
    },
    nonempty(params) {
      return this.check(_minLength(1, params));
    },
    max(n, params) {
      return this.check(_maxLength(n, params));
    },
    length(n, params) {
      return this.check(_length(n, params));
    },
    unwrap() {
      return this.element;
    }
  });
});
function array(element, params) {
  return _array(ZodArray, element, params);
}
function keyof(schema) {
  const shape = schema._zod.def.shape;
  return _enum2(Object.keys(shape));
}
var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
  $ZodObjectJIT.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => objectProcessor(inst, ctx, json2, params);
  util_exports.defineLazy(inst, "shape", () => {
    return def.shape;
  });
  _installLazyMethods(inst, "ZodObject", {
    keyof() {
      return _enum2(Object.keys(this._zod.def.shape));
    },
    catchall(catchall) {
      return this.clone({ ...this._zod.def, catchall });
    },
    passthrough() {
      return this.clone({ ...this._zod.def, catchall: unknown() });
    },
    loose() {
      return this.clone({ ...this._zod.def, catchall: unknown() });
    },
    strict() {
      return this.clone({ ...this._zod.def, catchall: never() });
    },
    strip() {
      return this.clone({ ...this._zod.def, catchall: void 0 });
    },
    extend(incoming) {
      return util_exports.extend(this, incoming);
    },
    safeExtend(incoming) {
      return util_exports.safeExtend(this, incoming);
    },
    merge(other) {
      return util_exports.merge(this, other);
    },
    pick(mask) {
      return util_exports.pick(this, mask);
    },
    omit(mask) {
      return util_exports.omit(this, mask);
    },
    partial(...args) {
      return util_exports.partial(ZodOptional, this, args[0]);
    },
    required(...args) {
      return util_exports.required(ZodNonOptional, this, args[0]);
    }
  });
});
function object(shape, params) {
  const def = {
    type: "object",
    shape: shape ?? {},
    ...util_exports.normalizeParams(params)
  };
  return new ZodObject(def);
}
function strictObject(shape, params) {
  return new ZodObject({
    type: "object",
    shape,
    catchall: never(),
    ...util_exports.normalizeParams(params)
  });
}
function looseObject(shape, params) {
  return new ZodObject({
    type: "object",
    shape,
    catchall: unknown(),
    ...util_exports.normalizeParams(params)
  });
}
var ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
  $ZodUnion.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params);
  inst.options = def.options;
});
function union(options, params) {
  return new ZodUnion({
    type: "union",
    options,
    ...util_exports.normalizeParams(params)
  });
}
var ZodXor = /* @__PURE__ */ $constructor("ZodXor", (inst, def) => {
  ZodUnion.init(inst, def);
  $ZodXor.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params);
  inst.options = def.options;
});
function xor(options, params) {
  return new ZodXor({
    type: "union",
    options,
    inclusive: false,
    ...util_exports.normalizeParams(params)
  });
}
var ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => {
  ZodUnion.init(inst, def);
  $ZodDiscriminatedUnion.init(inst, def);
});
function discriminatedUnion(discriminator, options, params) {
  return new ZodDiscriminatedUnion({
    type: "union",
    options,
    discriminator,
    ...util_exports.normalizeParams(params)
  });
}
var ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {
  $ZodIntersection.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor(inst, ctx, json2, params);
});
function intersection(left, right) {
  return new ZodIntersection({
    type: "intersection",
    left,
    right
  });
}
var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => {
  $ZodTuple.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => tupleProcessor(inst, ctx, json2, params);
  inst.rest = (rest) => inst.clone({
    ...inst._zod.def,
    rest
  });
});
function tuple(items, _paramsOrRest, _params) {
  const hasRest = _paramsOrRest instanceof $ZodType;
  const params = hasRest ? _params : _paramsOrRest;
  const rest = hasRest ? _paramsOrRest : null;
  return new ZodTuple({
    type: "tuple",
    items,
    rest,
    ...util_exports.normalizeParams(params)
  });
}
var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
  $ZodRecord.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => recordProcessor(inst, ctx, json2, params);
  inst.keyType = def.keyType;
  inst.valueType = def.valueType;
});
function record(keyType, valueType, params) {
  if (!valueType || !valueType._zod) {
    return new ZodRecord({
      type: "record",
      keyType: string2(),
      valueType: keyType,
      ...util_exports.normalizeParams(valueType)
    });
  }
  return new ZodRecord({
    type: "record",
    keyType,
    valueType,
    ...util_exports.normalizeParams(params)
  });
}
function partialRecord(keyType, valueType, params) {
  const k = clone(keyType);
  k._zod.values = void 0;
  return new ZodRecord({
    type: "record",
    keyType: k,
    valueType,
    ...util_exports.normalizeParams(params)
  });
}
function looseRecord(keyType, valueType, params) {
  return new ZodRecord({
    type: "record",
    keyType,
    valueType,
    mode: "loose",
    ...util_exports.normalizeParams(params)
  });
}
var ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => {
  $ZodMap.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => mapProcessor(inst, ctx, json2, params);
  inst.keyType = def.keyType;
  inst.valueType = def.valueType;
  inst.min = (...args) => inst.check(_minSize(...args));
  inst.nonempty = (params) => inst.check(_minSize(1, params));
  inst.max = (...args) => inst.check(_maxSize(...args));
  inst.size = (...args) => inst.check(_size(...args));
});
function map(keyType, valueType, params) {
  return new ZodMap({
    type: "map",
    keyType,
    valueType,
    ...util_exports.normalizeParams(params)
  });
}
var ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => {
  $ZodSet.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => setProcessor(inst, ctx, json2, params);
  inst.min = (...args) => inst.check(_minSize(...args));
  inst.nonempty = (params) => inst.check(_minSize(1, params));
  inst.max = (...args) => inst.check(_maxSize(...args));
  inst.size = (...args) => inst.check(_size(...args));
});
function set(valueType, params) {
  return new ZodSet({
    type: "set",
    valueType,
    ...util_exports.normalizeParams(params)
  });
}
var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
  $ZodEnum.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => enumProcessor(inst, ctx, json2, params);
  inst.enum = def.entries;
  inst.options = Object.values(def.entries);
  const keys = new Set(Object.keys(def.entries));
  inst.extract = (values, params) => {
    const newEntries = {};
    for (const value of values) {
      if (keys.has(value)) {
        newEntries[value] = def.entries[value];
      } else
        throw new Error(`Key ${value} not found in enum`);
    }
    return new ZodEnum({
      ...def,
      checks: [],
      ...util_exports.normalizeParams(params),
      entries: newEntries
    });
  };
  inst.exclude = (values, params) => {
    const newEntries = { ...def.entries };
    for (const value of values) {
      if (keys.has(value)) {
        delete newEntries[value];
      } else
        throw new Error(`Key ${value} not found in enum`);
    }
    return new ZodEnum({
      ...def,
      checks: [],
      ...util_exports.normalizeParams(params),
      entries: newEntries
    });
  };
});
function _enum2(values, params) {
  const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
  return new ZodEnum({
    type: "enum",
    entries,
    ...util_exports.normalizeParams(params)
  });
}
function nativeEnum(entries, params) {
  return new ZodEnum({
    type: "enum",
    entries,
    ...util_exports.normalizeParams(params)
  });
}
var ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
  $ZodLiteral.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => literalProcessor(inst, ctx, json2, params);
  inst.values = new Set(def.values);
  Object.defineProperty(inst, "value", {
    get() {
      if (def.values.length > 1) {
        throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
      }
      return def.values[0];
    }
  });
});
function literal(value, params) {
  return new ZodLiteral({
    type: "literal",
    values: Array.isArray(value) ? value : [value],
    ...util_exports.normalizeParams(params)
  });
}
var ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => {
  $ZodFile.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => fileProcessor(inst, ctx, json2, params);
  inst.min = (size, params) => inst.check(_minSize(size, params));
  inst.max = (size, params) => inst.check(_maxSize(size, params));
  inst.mime = (types3, params) => inst.check(_mime(Array.isArray(types3) ? types3 : [types3], params));
});
function file(params) {
  return _file(ZodFile, params);
}
var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
  $ZodTransform.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => transformProcessor(inst, ctx, json2, params);
  inst._zod.parse = (payload, _ctx) => {
    if (_ctx.direction === "backward") {
      throw new $ZodEncodeError(inst.constructor.name);
    }
    payload.addIssue = (issue2) => {
      if (typeof issue2 === "string") {
        payload.issues.push(util_exports.issue(issue2, payload.value, def));
      } else {
        const _issue = issue2;
        if (_issue.fatal)
          _issue.continue = false;
        _issue.code ?? (_issue.code = "custom");
        _issue.input ?? (_issue.input = payload.value);
        _issue.inst ?? (_issue.inst = inst);
        payload.issues.push(util_exports.issue(_issue));
      }
    };
    const output = def.transform(payload.value, payload);
    if (output instanceof Promise) {
      return output.then((output2) => {
        payload.value = output2;
        payload.fallback = true;
        return payload;
      });
    }
    payload.value = output;
    payload.fallback = true;
    return payload;
  };
});
function transform(fn) {
  return new ZodTransform({
    type: "transform",
    transform: fn
  });
}
var ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
  $ZodOptional.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function optional(innerType) {
  return new ZodOptional({
    type: "optional",
    innerType
  });
}
var ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => {
  $ZodExactOptional.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function exactOptional(innerType) {
  return new ZodExactOptional({
    type: "optional",
    innerType
  });
}
var ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
  $ZodNullable.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => nullableProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function nullable(innerType) {
  return new ZodNullable({
    type: "nullable",
    innerType
  });
}
function nullish2(innerType) {
  return optional(nullable(innerType));
}
var ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {
  $ZodDefault.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => defaultProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
  inst.removeDefault = inst.unwrap;
});
function _default2(innerType, defaultValue) {
  return new ZodDefault({
    type: "default",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue);
    }
  });
}
var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
  $ZodPrefault.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => prefaultProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function prefault(innerType, defaultValue) {
  return new ZodPrefault({
    type: "prefault",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue);
    }
  });
}
var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
  $ZodNonOptional.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => nonoptionalProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function nonoptional(innerType, params) {
  return new ZodNonOptional({
    type: "nonoptional",
    innerType,
    ...util_exports.normalizeParams(params)
  });
}
var ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => {
  $ZodSuccess.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => successProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function success(innerType) {
  return new ZodSuccess({
    type: "success",
    innerType
  });
}
var ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
  $ZodCatch.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => catchProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
  inst.removeCatch = inst.unwrap;
});
function _catch2(innerType, catchValue) {
  return new ZodCatch({
    type: "catch",
    innerType,
    catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
  });
}
var ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => {
  $ZodNaN.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => nanProcessor(inst, ctx, json2, params);
});
function nan(params) {
  return _nan(ZodNaN, params);
}
var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
  $ZodPipe.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => pipeProcessor(inst, ctx, json2, params);
  inst.in = def.in;
  inst.out = def.out;
});
function pipe(in_, out) {
  return new ZodPipe({
    type: "pipe",
    in: in_,
    out
    // ...util.normalizeParams(params),
  });
}
var ZodCodec = /* @__PURE__ */ $constructor("ZodCodec", (inst, def) => {
  ZodPipe.init(inst, def);
  $ZodCodec.init(inst, def);
});
function codec(in_, out, params) {
  return new ZodCodec({
    type: "pipe",
    in: in_,
    out,
    transform: params.decode,
    reverseTransform: params.encode
  });
}
function invertCodec(codec2) {
  const def = codec2._zod.def;
  return new ZodCodec({
    type: "pipe",
    in: def.out,
    out: def.in,
    transform: def.reverseTransform,
    reverseTransform: def.transform
  });
}
var ZodPreprocess = /* @__PURE__ */ $constructor("ZodPreprocess", (inst, def) => {
  ZodPipe.init(inst, def);
  $ZodPreprocess.init(inst, def);
});
var ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
  $ZodReadonly.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => readonlyProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function readonly(innerType) {
  return new ZodReadonly({
    type: "readonly",
    innerType
  });
}
var ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => {
  $ZodTemplateLiteral.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => templateLiteralProcessor(inst, ctx, json2, params);
});
function templateLiteral(parts, params) {
  return new ZodTemplateLiteral({
    type: "template_literal",
    parts,
    ...util_exports.normalizeParams(params)
  });
}
var ZodLazy = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => {
  $ZodLazy.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => lazyProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.getter();
});
function lazy(getter) {
  return new ZodLazy({
    type: "lazy",
    getter
  });
}
var ZodPromise = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => {
  $ZodPromise.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => promiseProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function promise(innerType) {
  return new ZodPromise({
    type: "promise",
    innerType
  });
}
var ZodFunction = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => {
  $ZodFunction.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => functionProcessor(inst, ctx, json2, params);
});
function _function(params) {
  return new ZodFunction({
    type: "function",
    input: Array.isArray(params?.input) ? tuple(params?.input) : params?.input ?? array(unknown()),
    output: params?.output ?? unknown()
  });
}
var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
  $ZodCustom.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => customProcessor(inst, ctx, json2, params);
});
function check(fn) {
  const ch = new $ZodCheck({
    check: "custom"
    // ...util.normalizeParams(params),
  });
  ch._zod.check = fn;
  return ch;
}
function custom(fn, _params) {
  return _custom(ZodCustom, fn ?? (() => true), _params);
}
function refine(fn, _params = {}) {
  return _refine(ZodCustom, fn, _params);
}
function superRefine(fn, params) {
  return _superRefine(fn, params);
}
var describe2 = describe;
var meta2 = meta;
function _instanceof(cls, params = {}) {
  const inst = new ZodCustom({
    type: "custom",
    check: "custom",
    fn: (data) => data instanceof cls,
    abort: true,
    ...util_exports.normalizeParams(params)
  });
  inst._zod.bag.Class = cls;
  inst._zod.check = (payload) => {
    if (!(payload.value instanceof cls)) {
      payload.issues.push({
        code: "invalid_type",
        expected: cls.name,
        input: payload.value,
        inst,
        path: [...inst._zod.def.path ?? []]
      });
    }
  };
  return inst;
}
var stringbool = (...args) => _stringbool({
  Codec: ZodCodec,
  Boolean: ZodBoolean,
  String: ZodString
}, ...args);
function json(params) {
  const jsonSchema = lazy(() => {
    return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema), record(string2(), jsonSchema)]);
  });
  return jsonSchema;
}
function preprocess(fn, schema) {
  return new ZodPreprocess({
    type: "pipe",
    in: transform(fn),
    out: schema
  });
}

// node_modules/zod/v4/classic/compat.js
var ZodIssueCode = {
  invalid_type: "invalid_type",
  too_big: "too_big",
  too_small: "too_small",
  invalid_format: "invalid_format",
  not_multiple_of: "not_multiple_of",
  unrecognized_keys: "unrecognized_keys",
  invalid_union: "invalid_union",
  invalid_key: "invalid_key",
  invalid_element: "invalid_element",
  invalid_value: "invalid_value",
  custom: "custom"
};
function setErrorMap(map2) {
  config({
    customError: map2
  });
}
function getErrorMap() {
  return config().customError;
}
var ZodFirstPartyTypeKind;
/* @__PURE__ */ (function(ZodFirstPartyTypeKind3) {
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));

// node_modules/zod/v4/classic/from-json-schema.js
var z = {
  ...schemas_exports2,
  ...checks_exports2,
  iso: iso_exports
};
var RECOGNIZED_KEYS = /* @__PURE__ */ new Set([
  // Schema identification
  "$schema",
  "$ref",
  "$defs",
  "definitions",
  // Core schema keywords
  "$id",
  "id",
  "$comment",
  "$anchor",
  "$vocabulary",
  "$dynamicRef",
  "$dynamicAnchor",
  // Type
  "type",
  "enum",
  "const",
  // Composition
  "anyOf",
  "oneOf",
  "allOf",
  "not",
  // Object
  "properties",
  "required",
  "additionalProperties",
  "patternProperties",
  "propertyNames",
  "minProperties",
  "maxProperties",
  // Array
  "items",
  "prefixItems",
  "additionalItems",
  "minItems",
  "maxItems",
  "uniqueItems",
  "contains",
  "minContains",
  "maxContains",
  // String
  "minLength",
  "maxLength",
  "pattern",
  "format",
  // Number
  "minimum",
  "maximum",
  "exclusiveMinimum",
  "exclusiveMaximum",
  "multipleOf",
  // Already handled metadata
  "description",
  "default",
  // Content
  "contentEncoding",
  "contentMediaType",
  "contentSchema",
  // Unsupported (error-throwing)
  "unevaluatedItems",
  "unevaluatedProperties",
  "if",
  "then",
  "else",
  "dependentSchemas",
  "dependentRequired",
  // OpenAPI
  "nullable",
  "readOnly"
]);
function detectVersion(schema, defaultTarget) {
  const $schema = schema.$schema;
  if ($schema === "https://json-schema.org/draft/2020-12/schema") {
    return "draft-2020-12";
  }
  if ($schema === "http://json-schema.org/draft-07/schema#") {
    return "draft-7";
  }
  if ($schema === "http://json-schema.org/draft-04/schema#") {
    return "draft-4";
  }
  return defaultTarget ?? "draft-2020-12";
}
function resolveRef(ref, ctx) {
  if (!ref.startsWith("#")) {
    throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
  }
  const path = ref.slice(1).split("/").filter(Boolean);
  if (path.length === 0) {
    return ctx.rootSchema;
  }
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
  if (path[0] === defsKey) {
    const key = path[1];
    if (!key || !ctx.defs[key]) {
      throw new Error(`Reference not found: ${ref}`);
    }
    return ctx.defs[key];
  }
  throw new Error(`Reference not found: ${ref}`);
}
function convertBaseSchema(schema, ctx) {
  if (schema.not !== void 0) {
    if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) {
      return z.never();
    }
    throw new Error("not is not supported in Zod (except { not: {} } for never)");
  }
  if (schema.unevaluatedItems !== void 0) {
    throw new Error("unevaluatedItems is not supported");
  }
  if (schema.unevaluatedProperties !== void 0) {
    throw new Error("unevaluatedProperties is not supported");
  }
  if (schema.if !== void 0 || schema.then !== void 0 || schema.else !== void 0) {
    throw new Error("Conditional schemas (if/then/else) are not supported");
  }
  if (schema.dependentSchemas !== void 0 || schema.dependentRequired !== void 0) {
    throw new Error("dependentSchemas and dependentRequired are not supported");
  }
  if (schema.$ref) {
    const refPath = schema.$ref;
    if (ctx.refs.has(refPath)) {
      return ctx.refs.get(refPath);
    }
    if (ctx.processing.has(refPath)) {
      return z.lazy(() => {
        if (!ctx.refs.has(refPath)) {
          throw new Error(`Circular reference not resolved: ${refPath}`);
        }
        return ctx.refs.get(refPath);
      });
    }
    ctx.processing.add(refPath);
    const resolved = resolveRef(refPath, ctx);
    const zodSchema2 = convertSchema(resolved, ctx);
    ctx.refs.set(refPath, zodSchema2);
    ctx.processing.delete(refPath);
    return zodSchema2;
  }
  if (schema.enum !== void 0) {
    const enumValues = schema.enum;
    if (ctx.version === "openapi-3.0" && schema.nullable === true && enumValues.length === 1 && enumValues[0] === null) {
      return z.null();
    }
    if (enumValues.length === 0) {
      return z.never();
    }
    if (enumValues.length === 1) {
      return z.literal(enumValues[0]);
    }
    if (enumValues.every((v) => typeof v === "string")) {
      return z.enum(enumValues);
    }
    const literalSchemas = enumValues.map((v) => z.literal(v));
    if (literalSchemas.length < 2) {
      return literalSchemas[0];
    }
    return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]);
  }
  if (schema.const !== void 0) {
    return z.literal(schema.const);
  }
  const type = schema.type;
  if (Array.isArray(type)) {
    const typeSchemas = type.map((t2) => {
      const typeSchema = { ...schema, type: t2 };
      return convertBaseSchema(typeSchema, ctx);
    });
    if (typeSchemas.length === 0) {
      return z.never();
    }
    if (typeSchemas.length === 1) {
      return typeSchemas[0];
    }
    return z.union(typeSchemas);
  }
  if (!type) {
    return z.any();
  }
  let zodSchema;
  switch (type) {
    case "string": {
      let stringSchema = z.string();
      if (schema.format) {
        const format = schema.format;
        if (format === "email") {
          stringSchema = stringSchema.check(z.email());
        } else if (format === "uri" || format === "uri-reference") {
          stringSchema = stringSchema.check(z.url());
        } else if (format === "uuid" || format === "guid") {
          stringSchema = stringSchema.check(z.uuid());
        } else if (format === "date-time") {
          stringSchema = stringSchema.check(z.iso.datetime());
        } else if (format === "date") {
          stringSchema = stringSchema.check(z.iso.date());
        } else if (format === "time") {
          stringSchema = stringSchema.check(z.iso.time());
        } else if (format === "duration") {
          stringSchema = stringSchema.check(z.iso.duration());
        } else if (format === "ipv4") {
          stringSchema = stringSchema.check(z.ipv4());
        } else if (format === "ipv6") {
          stringSchema = stringSchema.check(z.ipv6());
        } else if (format === "mac") {
          stringSchema = stringSchema.check(z.mac());
        } else if (format === "cidr") {
          stringSchema = stringSchema.check(z.cidrv4());
        } else if (format === "cidr-v6") {
          stringSchema = stringSchema.check(z.cidrv6());
        } else if (format === "base64") {
          stringSchema = stringSchema.check(z.base64());
        } else if (format === "base64url") {
          stringSchema = stringSchema.check(z.base64url());
        } else if (format === "e164") {
          stringSchema = stringSchema.check(z.e164());
        } else if (format === "jwt") {
          stringSchema = stringSchema.check(z.jwt());
        } else if (format === "emoji") {
          stringSchema = stringSchema.check(z.emoji());
        } else if (format === "nanoid") {
          stringSchema = stringSchema.check(z.nanoid());
        } else if (format === "cuid") {
          stringSchema = stringSchema.check(z.cuid());
        } else if (format === "cuid2") {
          stringSchema = stringSchema.check(z.cuid2());
        } else if (format === "ulid") {
          stringSchema = stringSchema.check(z.ulid());
        } else if (format === "xid") {
          stringSchema = stringSchema.check(z.xid());
        } else if (format === "ksuid") {
          stringSchema = stringSchema.check(z.ksuid());
        }
      }
      if (typeof schema.minLength === "number") {
        stringSchema = stringSchema.min(schema.minLength);
      }
      if (typeof schema.maxLength === "number") {
        stringSchema = stringSchema.max(schema.maxLength);
      }
      if (schema.pattern) {
        stringSchema = stringSchema.regex(new RegExp(schema.pattern));
      }
      zodSchema = stringSchema;
      break;
    }
    case "number":
    case "integer": {
      let numberSchema = type === "integer" ? z.number().int() : z.number();
      if (typeof schema.minimum === "number") {
        numberSchema = numberSchema.min(schema.minimum);
      }
      if (typeof schema.maximum === "number") {
        numberSchema = numberSchema.max(schema.maximum);
      }
      if (typeof schema.exclusiveMinimum === "number") {
        numberSchema = numberSchema.gt(schema.exclusiveMinimum);
      } else if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") {
        numberSchema = numberSchema.gt(schema.minimum);
      }
      if (typeof schema.exclusiveMaximum === "number") {
        numberSchema = numberSchema.lt(schema.exclusiveMaximum);
      } else if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") {
        numberSchema = numberSchema.lt(schema.maximum);
      }
      if (typeof schema.multipleOf === "number") {
        numberSchema = numberSchema.multipleOf(schema.multipleOf);
      }
      zodSchema = numberSchema;
      break;
    }
    case "boolean": {
      zodSchema = z.boolean();
      break;
    }
    case "null": {
      zodSchema = z.null();
      break;
    }
    case "object": {
      const shape = {};
      const properties = schema.properties || {};
      const requiredSet = new Set(schema.required || []);
      for (const [key, propSchema] of Object.entries(properties)) {
        const propZodSchema = convertSchema(propSchema, ctx);
        shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional();
      }
      if (schema.propertyNames) {
        const keySchema = convertSchema(schema.propertyNames, ctx);
        const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any();
        if (Object.keys(shape).length === 0) {
          zodSchema = z.record(keySchema, valueSchema);
          break;
        }
        const objectSchema2 = z.object(shape).passthrough();
        const recordSchema = z.looseRecord(keySchema, valueSchema);
        zodSchema = z.intersection(objectSchema2, recordSchema);
        break;
      }
      if (schema.patternProperties) {
        const patternProps = schema.patternProperties;
        const patternKeys = Object.keys(patternProps);
        const looseRecords = [];
        for (const pattern of patternKeys) {
          const patternValue = convertSchema(patternProps[pattern], ctx);
          const keySchema = z.string().regex(new RegExp(pattern));
          looseRecords.push(z.looseRecord(keySchema, patternValue));
        }
        const schemasToIntersect = [];
        if (Object.keys(shape).length > 0) {
          schemasToIntersect.push(z.object(shape).passthrough());
        }
        schemasToIntersect.push(...looseRecords);
        if (schemasToIntersect.length === 0) {
          zodSchema = z.object({}).passthrough();
        } else if (schemasToIntersect.length === 1) {
          zodSchema = schemasToIntersect[0];
        } else {
          let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]);
          for (let i2 = 2; i2 < schemasToIntersect.length; i2++) {
            result = z.intersection(result, schemasToIntersect[i2]);
          }
          zodSchema = result;
        }
        break;
      }
      const objectSchema = z.object(shape);
      if (schema.additionalProperties === false) {
        zodSchema = objectSchema.strict();
      } else if (typeof schema.additionalProperties === "object") {
        zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx));
      } else {
        zodSchema = objectSchema.passthrough();
      }
      break;
    }
    case "array": {
      const prefixItems = schema.prefixItems;
      const items = schema.items;
      if (prefixItems && Array.isArray(prefixItems)) {
        const tupleItems = prefixItems.map((item) => convertSchema(item, ctx));
        const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0;
        if (rest) {
          zodSchema = z.tuple(tupleItems).rest(rest);
        } else {
          zodSchema = z.tuple(tupleItems);
        }
        if (typeof schema.minItems === "number") {
          zodSchema = zodSchema.check(z.minLength(schema.minItems));
        }
        if (typeof schema.maxItems === "number") {
          zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
        }
      } else if (Array.isArray(items)) {
        const tupleItems = items.map((item) => convertSchema(item, ctx));
        const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : void 0;
        if (rest) {
          zodSchema = z.tuple(tupleItems).rest(rest);
        } else {
          zodSchema = z.tuple(tupleItems);
        }
        if (typeof schema.minItems === "number") {
          zodSchema = zodSchema.check(z.minLength(schema.minItems));
        }
        if (typeof schema.maxItems === "number") {
          zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
        }
      } else if (items !== void 0) {
        const element = convertSchema(items, ctx);
        let arraySchema = z.array(element);
        if (typeof schema.minItems === "number") {
          arraySchema = arraySchema.min(schema.minItems);
        }
        if (typeof schema.maxItems === "number") {
          arraySchema = arraySchema.max(schema.maxItems);
        }
        zodSchema = arraySchema;
      } else {
        zodSchema = z.array(z.any());
      }
      break;
    }
    default:
      throw new Error(`Unsupported type: ${type}`);
  }
  return zodSchema;
}
function convertSchema(schema, ctx) {
  if (typeof schema === "boolean") {
    return schema ? z.any() : z.never();
  }
  let baseSchema = convertBaseSchema(schema, ctx);
  const hasExplicitType = schema.type || schema.enum !== void 0 || schema.const !== void 0;
  if (schema.anyOf && Array.isArray(schema.anyOf)) {
    const options = schema.anyOf.map((s2) => convertSchema(s2, ctx));
    const anyOfUnion = z.union(options);
    baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion;
  }
  if (schema.oneOf && Array.isArray(schema.oneOf)) {
    const options = schema.oneOf.map((s2) => convertSchema(s2, ctx));
    const oneOfUnion = z.xor(options);
    baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion;
  }
  if (schema.allOf && Array.isArray(schema.allOf)) {
    if (schema.allOf.length === 0) {
      baseSchema = hasExplicitType ? baseSchema : z.any();
    } else {
      let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx);
      const startIdx = hasExplicitType ? 0 : 1;
      for (let i2 = startIdx; i2 < schema.allOf.length; i2++) {
        result = z.intersection(result, convertSchema(schema.allOf[i2], ctx));
      }
      baseSchema = result;
    }
  }
  if (schema.nullable === true && ctx.version === "openapi-3.0") {
    baseSchema = z.nullable(baseSchema);
  }
  if (schema.readOnly === true) {
    baseSchema = z.readonly(baseSchema);
  }
  if (schema.default !== void 0) {
    baseSchema = baseSchema.default(schema.default);
  }
  const extraMeta = {};
  const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"];
  for (const key of coreMetadataKeys) {
    if (key in schema) {
      extraMeta[key] = schema[key];
    }
  }
  const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"];
  for (const key of contentMetadataKeys) {
    if (key in schema) {
      extraMeta[key] = schema[key];
    }
  }
  for (const key of Object.keys(schema)) {
    if (!RECOGNIZED_KEYS.has(key)) {
      extraMeta[key] = schema[key];
    }
  }
  if (Object.keys(extraMeta).length > 0) {
    ctx.registry.add(baseSchema, extraMeta);
  }
  if (schema.description) {
    baseSchema = baseSchema.describe(schema.description);
  }
  return baseSchema;
}
function fromJSONSchema(schema, params) {
  if (typeof schema === "boolean") {
    return schema ? z.any() : z.never();
  }
  let normalized;
  try {
    normalized = JSON.parse(JSON.stringify(schema));
  } catch {
    throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
  }
  const version2 = detectVersion(normalized, params?.defaultTarget);
  const defs = normalized.$defs || normalized.definitions || {};
  const ctx = {
    version: version2,
    defs,
    refs: /* @__PURE__ */ new Map(),
    processing: /* @__PURE__ */ new Set(),
    rootSchema: normalized,
    registry: params?.registry ?? globalRegistry
  };
  return convertSchema(normalized, ctx);
}

// node_modules/zod/v4/classic/coerce.js
var coerce_exports = {};
__export(coerce_exports, {
  bigint: () => bigint3,
  boolean: () => boolean3,
  date: () => date4,
  number: () => number3,
  string: () => string3
});
function string3(params) {
  return _coercedString(ZodString, params);
}
function number3(params) {
  return _coercedNumber(ZodNumber, params);
}
function boolean3(params) {
  return _coercedBoolean(ZodBoolean, params);
}
function bigint3(params) {
  return _coercedBigint(ZodBigInt, params);
}
function date4(params) {
  return _coercedDate(ZodDate, params);
}

// node_modules/zod/v4/classic/external.js
config(en_default());

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

// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
var STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024;
var ReadBuffer = class {
  constructor(options) {
    this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE;
  }
  append(chunk) {
    const newSize = (this._buffer?.length ?? 0) + chunk.length;
    if (newSize > this._maxBufferSize) {
      this.clear();
      throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);
    }
    this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
  }
  readMessage() {
    if (!this._buffer) {
      return null;
    }
    const index = this._buffer.indexOf("\n");
    if (index === -1) {
      return null;
    }
    const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, "");
    this._buffer = this._buffer.subarray(index + 1);
    return deserializeMessage(line);
  }
  clear() {
    this._buffer = void 0;
  }
};
function deserializeMessage(line) {
  return JSONRPCMessageSchema.parse(JSON.parse(line));
}
function serializeMessage(message) {
  return JSON.stringify(message) + "\n";
}

// node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
var StdioServerTransport = class {
  constructor(_stdin = import_node_process.default.stdin, _stdout = import_node_process.default.stdout, options) {
    this._stdin = _stdin;
    this._stdout = _stdout;
    this._started = false;
    this._ondata = (chunk) => {
      try {
        this._readBuffer.append(chunk);
        this.processReadBuffer();
      } catch (error51) {
        this.onerror?.(error51);
        this.close().catch(() => {
        });
      }
    };
    this._onerror = (error51) => {
      this.onerror?.(error51);
    };
    this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize });
  }
  /**
   * Starts listening for messages on stdin.
   */
  async start() {
    if (this._started) {
      throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");
    }
    this._started = true;
    this._stdin.on("data", this._ondata);
    this._stdin.on("error", this._onerror);
  }
  processReadBuffer() {
    while (true) {
      try {
        const message = this._readBuffer.readMessage();
        if (message === null) {
          break;
        }
        this.onmessage?.(message);
      } catch (error51) {
        this.onerror?.(error51);
      }
    }
  }
  async close() {
    this._stdin.off("data", this._ondata);
    this._stdin.off("error", this._onerror);
    const remainingDataListeners = this._stdin.listenerCount("data");
    if (remainingDataListeners === 0) {
      this._stdin.pause();
    }
    this._readBuffer.clear();
    this.onclose?.();
  }
  send(message) {
    return new Promise((resolve2) => {
      const json2 = serializeMessage(message);
      if (this._stdout.write(json2)) {
        resolve2();
      } else {
        this._stdout.once("drain", resolve2);
      }
    });
  }
};

// node_modules/@kirbah/mcp-youtube/dist/services/cache.service.js
var import_crypto = require("crypto");

// node_modules/@kirbah/mcp-youtube/dist/utils/objectUtils.js
function omitPaths(obj, paths) {
  const newObj = JSON.parse(JSON.stringify(obj));
  for (const path of paths) {
    const parts = path.split(".");
    let current = newObj;
    for (let i2 = 0; i2 < parts.length - 1; i2++) {
      const part = parts[i2];
      if (current && typeof current === "object" && part in current) {
        current = current[part];
      } else {
        current = null;
        break;
      }
    }
    if (current && typeof current === "object") {
      delete current[parts[parts.length - 1]];
    }
  }
  return newObj;
}

// node_modules/@kirbah/mcp-youtube/dist/services/database.service.js
var import_mongodb = __toESM(require_lib3(), 1);
var import_promises = __toESM(require("node:dns/promises"), 1);
var DATABASE_NAME = "youtube_niche_analysis";
var connectionPromise = null;
var mongoClient = null;
var _connectionString = null;
function initializeDatabase(connectionString) {
  if (!connectionString) {
    throw new Error("MongoDB connection string is required for database initialization.");
  }
  try {
    import_promises.default.setServers(["8.8.8.8", "1.1.1.1"]);
  } catch (err) {
    console.warn("Failed to set DNS servers:", err);
  }
  _connectionString = connectionString;
}
function getClientPromise() {
  if (!connectionPromise) {
    if (!_connectionString) {
      return Promise.reject(new Error("Database not initialized. Call initializeDatabase() first."));
    }
    const client = new import_mongodb.MongoClient(_connectionString);
    connectionPromise = client.connect().then((connectedClient) => {
      mongoClient = connectedClient;
      return connectedClient;
    }).catch((err) => {
      connectionPromise = null;
      throw err;
    });
  }
  return connectionPromise;
}
async function getDb() {
  const client = await getClientPromise();
  return client.db(DATABASE_NAME);
}
async function disconnectFromDatabase() {
  if (mongoClient) {
    await mongoClient.close();
    mongoClient = null;
    connectionPromise = null;
  }
}

// node_modules/@kirbah/mcp-youtube/dist/services/cache.service.js
var CacheService = class {
  CACHE_COLLECTION_PREFIX = "yt_cache_";
  mdbMcpConnectionString;
  constructor(mdbMcpConnectionString) {
    this.mdbMcpConnectionString = mdbMcpConnectionString;
  }
  /**
   * The core generic caching method. It attempts to retrieve data from the cache using a key.
   * If the data is not found or is expired, it executes the provided `operation` function,
   * stores the result back in the cache, and then returns it.
   *
   * @template T The type of data being cached.
   * @param key The unique key for this cache entry (e.g., a 'videoId' or a generated hash).
   * @param operation An async function that returns the fresh data (type T) to be cached on a miss.
   * @param ttlSeconds The Time-To-Live for this cache entry, in seconds.
   * @param collectionName A descriptive name for the MongoDB collection where this data will be stored (e.g., "video_details").
   * @param params Optional: Parameters used to generate the hashed keys and stored in cache as params.
   * @param pathsToExclude Optional: An array of string paths (e.g., "snippet.thumbnails") to exclude from the cached data.
   * @returns A promise that resolves to the data, either from the cache or freshly generated.
   */
  async getOrSet(key, operation, ttlSeconds, collectionName, params, pathsToExclude) {
    if (!this.mdbMcpConnectionString) {
      return operation();
    }
    const db = await getDb();
    const collection = db.collection(`${this.CACHE_COLLECTION_PREFIX}${collectionName}`);
    const cachedResult = await collection.findOne({
      _id: key,
      expiresAt: { $gt: /* @__PURE__ */ new Date() }
    });
    if (cachedResult) {
      return cachedResult.data;
    }
    const freshData = await operation();
    if (freshData === null || freshData === void 0) {
      return freshData;
    }
    const dataToCache = pathsToExclude && pathsToExclude.length > 0 ? omitPaths(freshData, pathsToExclude) : freshData;
    const expiresAt = new Date(Date.now() + ttlSeconds * 1e3);
    const cacheDocument = {
      _id: key,
      data: dataToCache,
      // Storing the (potentially) smaller object
      expiresAt
    };
    if (params) {
      cacheDocument.params = params;
    }
    await collection.updateOne({ _id: key }, { $set: cacheDocument }, { upsert: true });
    return dataToCache;
  }
  /**
   * A helper utility to create a consistent, unique hash key from a function's name and its arguments.
   * This is ideal for caching the results of complex queries (like video searches) where the
   * combination of all parameters determines the result.
   *
   * @param operationName A unique name for the operation being cached (e.g., "searchVideos").
   * @param args An object containing all the arguments for the operation.
   * @returns A cryptographic SHA256 hash string to be used as a cache key.
   */
  createOperationKey(operationName, args) {
    const sortedArgs = Object.keys(args).sort().reduce((obj, key) => {
      const value = args[key];
      if (value !== void 0) {
        obj[key] = value;
      }
      return obj;
    }, {});
    const keyString = `${operationName}:${JSON.stringify(sortedArgs)}`;
    return (0, import_crypto.createHash)("sha256").update(keyString).digest("hex");
  }
};

// node_modules/@kirbah/mcp-youtube/dist/services/youtube.service.js
var import_googleapis = __toESM(require_googleapis_shim(), 1);

// node_modules/@kirbah/mcp-youtube/dist/utils/engagementCalculator.js
function calculateLikeToViewRatio(viewCount, likeCount) {
  try {
    const views = parseInt(String(viewCount || "0"));
    const likes = parseInt(String(likeCount || "0"));
    if (isNaN(views) || isNaN(likes) || views <= 0) {
      return 0;
    }
    const rawRatio = Math.max(0, likes) / views;
    return Number(rawRatio.toFixed(5));
  } catch (error51) {
    console.error("Error in calculateLikeToViewRatio:", {
      viewCount,
      likeCount,
      error: error51
    });
    return 0;
  }
}
function calculateCommentToViewRatio(viewCount, commentCount) {
  try {
    const views = parseInt(String(viewCount || "0"));
    const comments = parseInt(String(commentCount || "0"));
    if (isNaN(views) || isNaN(comments) || views <= 0) {
      return 0;
    }
    const rawRatio = Math.max(0, comments) / views;
    return Number(rawRatio.toFixed(5));
  } catch (error51) {
    console.error("Error in calculateCommentToViewRatio:", {
      viewCount,
      commentCount,
      error: error51
    });
    return 0;
  }
}

// node_modules/@kirbah/mcp-youtube/dist/errors/api.errors.js
var AppError = class extends Error {
  details;
  constructor(message, details) {
    super(message);
    this.name = this.constructor.name;
    this.details = details;
    Error.captureStackTrace(this, this.constructor);
  }
};
var YouTubeApiError = class extends AppError {
  constructor(message, originalError) {
    const details = hasResponseData(originalError) ? originalError.response.data : originalError;
    super(message, details);
    this.name = "YouTubeApiError";
  }
};
var hasResponseData = (error51) => {
  return error51 !== null && typeof error51 === "object" && "response" in error51 && error51.response !== null && typeof error51.response === "object" && "data" in error51.response;
};
var MissingApiKeyError = class extends AppError {
  constructor() {
    super("This tool requires a YouTube API Key. Please add YOUTUBE_API_KEY to your MCP client configuration to unlock this feature. See the project README for setup instructions.");
    this.name = "MissingApiKeyError";
  }
};

// node_modules/@kirbah/mcp-youtube/dist/utils/numberParser.js
function parseYouTubeNumber(value) {
  if (value === null || value === void 0 || value === "") {
    return 0;
  }
  const parsed = parseInt(String(value), 10);
  return isNaN(parsed) ? 0 : parsed;
}

// node_modules/@kirbah/mcp-youtube/dist/utils/textUtils.js
var formatDescription = (description, descriptionDetail) => {
  if (descriptionDetail === "NONE")
    return void 0;
  if (description === null || description === void 0)
    return void 0;
  const maxLength = descriptionDetail === "SNIPPET" ? 150 : 500;
  if (description.length <= maxLength)
    return description;
  return description.substring(0, maxLength) + "...";
};

// node_modules/@kirbah/mcp-youtube/dist/config/cache.config.js
var ONE_HOUR = 3600;
var ONE_DAY = 24 * ONE_HOUR;
var ONE_WEEK = 7 * ONE_DAY;
var ONE_MONTH = 30 * ONE_DAY;
var ONE_YEAR = 365 * ONE_DAY;
var CACHE_TTLS = {
  // For data that changes frequently, like trending videos.
  DYNAMIC: ONE_DAY,
  // For standard entity data that can be updated, like video details or search results.
  STANDARD: ONE_WEEK,
  // For semi-static data that changes infrequently, like a channel's top videos.
  SEMI_STATIC: ONE_MONTH,
  // For truly static data that rarely or never changes, like video categories.
  STATIC: ONE_YEAR
};
var CACHE_COLLECTIONS = {
  TRANSCRIPTS: "transcripts",
  VIDEO_DETAILS: "video_details",
  CHANNEL_TOP_VIDEOS: "channel_top_videos",
  CHANNEL_RECENT_TOP_VIDEOS: "channel_recent_top_videos",
  VIDEO_SEARCHES: "video_searches",
  VIDEO_CATEGORIES: "video_categories",
  CHANNEL_STATS: "channel_stats",
  TRENDING_VIDEOS: "trending_videos",
  VIDEO_COMMENTS: "video_comments"
};

// node_modules/@kirbah/mcp-youtube/dist/services/youtube.service.js
var API_COSTS = {
  // Read-operations
  "search.list": 100,
  "videos.list": 1,
  "channels.list": 1,
  "videoCategories.list": 1,
  "commentThreads.list": 1,
  "comments.list": 1
};
var YoutubeService = class {
  youtube;
  cacheService;
  MAX_RESULTS_PER_PAGE = 50;
  ABSOLUTE_MAX_RESULTS = 500;
  apiCreditsUsed = 0;
  apiKey;
  constructor(apiKey, cacheService) {
    this.apiKey = apiKey;
    this.cacheService = cacheService;
    if (apiKey) {
      this.youtube = import_googleapis.google.youtube({
        version: "v3",
        auth: apiKey
      });
    } else {
      this.youtube = {};
    }
  }
  getApiCreditsUsed() {
    return this.apiCreditsUsed;
  }
  resetApiCreditsUsed() {
    this.apiCreditsUsed = 0;
  }
  async trackCost(operation, cost) {
    if (!this.apiKey) {
      throw new MissingApiKeyError();
    }
    this.apiCreditsUsed += cost;
    return operation();
  }
  calculatePublishedAfter(recency) {
    const now = /* @__PURE__ */ new Date();
    let millisecondsToSubtract;
    switch (recency) {
      case "pastHour":
        millisecondsToSubtract = 60 * 60 * 1e3;
        break;
      case "pastDay":
        millisecondsToSubtract = 24 * 60 * 60 * 1e3;
        break;
      case "pastWeek":
        millisecondsToSubtract = 7 * 24 * 60 * 60 * 1e3;
        break;
      case "pastMonth":
        millisecondsToSubtract = 30 * 24 * 60 * 60 * 1e3;
        break;
      case "pastQuarter":
        millisecondsToSubtract = 90 * 24 * 60 * 60 * 1e3;
        break;
      case "pastYear":
        millisecondsToSubtract = 365 * 24 * 60 * 60 * 1e3;
        break;
      default:
        return "";
    }
    const targetTime = new Date(now.getTime() - millisecondsToSubtract);
    if (["pastMonth", "pastQuarter", "pastYear"].includes(recency)) {
      targetTime.setDate(1);
    }
    return targetTime.toISOString();
  }
  async getVideo(options) {
    const { videoId, parts = ["snippet"] } = options;
    const cacheKey = videoId;
    const operation = async () => {
      try {
        const response = await this.trackCost(() => this.youtube.videos.list({ part: parts, id: [videoId] }), API_COSTS["videos.list"]);
        return response.data.items?.[0] ?? null;
      } catch (error51) {
        if (error51 instanceof AppError)
          throw error51;
        throw new YouTubeApiError(`YouTube API call for getVideo failed for videoId: ${videoId}`, error51);
      }
    };
    return this.cacheService.getOrSet(cacheKey, operation, CACHE_TTLS.STANDARD, CACHE_COLLECTIONS.VIDEO_DETAILS, options, ["snippet.thumbnails"]);
  }
  async searchVideos(options) {
    const cacheKey = this.cacheService.createOperationKey("searchVideos", options);
    const operation = async () => {
      try {
        const { query, maxResults = 10, order = "relevance", type = "video", channelId, videoDuration, publishedAfter, recency, regionCode } = options;
        const results = [];
        let nextPageToken = void 0;
        const targetResults = Math.min(maxResults, this.ABSOLUTE_MAX_RESULTS);
        let calculatedPublishedAfter = publishedAfter;
        if (recency && recency !== "any") {
          calculatedPublishedAfter = this.calculatePublishedAfter(recency);
        }
        while (results.length < targetResults) {
          const searchParams = {
            part: ["snippet"],
            q: query,
            maxResults: Math.min(this.MAX_RESULTS_PER_PAGE, targetResults - results.length),
            type: [type],
            order,
            pageToken: nextPageToken
          };
          if (channelId) {
            searchParams.channelId = channelId;
          }
          if (videoDuration && videoDuration !== "any") {
            searchParams.videoDuration = videoDuration;
          }
          if (calculatedPublishedAfter) {
            searchParams.publishedAfter = calculatedPublishedAfter;
          }
          if (regionCode) {
            searchParams.regionCode = regionCode;
          }
          const response = await this.trackCost(() => this.youtube.search.list(searchParams), API_COSTS["search.list"]);
          const searchResponse = response.data;
          if (!searchResponse.items?.length) {
            break;
          }
          results.push(...searchResponse.items);
          nextPageToken = searchResponse.nextPageToken || void 0;
          if (!nextPageToken) {
            break;
          }
        }
        return results.slice(0, targetResults);
      } catch (error51) {
        if (error51 instanceof AppError)
          throw error51;
        throw new YouTubeApiError(`YouTube API call for searchVideos failed`, error51);
      }
    };
    return this.cacheService.getOrSet(cacheKey, operation, CACHE_TTLS.STANDARD, CACHE_COLLECTIONS.VIDEO_DETAILS, options, ["snippet.thumbnails"]);
  }
  async batchFetchChannelStatistics(channelIds) {
    const results = /* @__PURE__ */ new Map();
    if (channelIds.length === 0) {
      return results;
    }
    try {
      const batchSize = 50;
      const promises = [];
      for (let i2 = 0; i2 < channelIds.length; i2 += batchSize) {
        const batch = channelIds.slice(i2, i2 + batchSize);
        const promise2 = this.trackCost(() => this.youtube.channels.list({
          part: ["snippet", "statistics"],
          id: batch
        }), API_COSTS["channels.list"]);
        promises.push(promise2);
      }
      const outcomes = await Promise.allSettled(promises);
      for (const outcome of outcomes) {
        if (outcome.status === "fulfilled") {
          const response = outcome.value;
          if (response.data.items) {
            for (const channel of response.data.items) {
              if (channel.id) {
                results.set(channel.id, channel);
              }
            }
          }
        } else {
          if (outcome.reason instanceof AppError)
            throw outcome.reason;
          console.error("A batch in batchFetchChannelStatistics failed:", outcome.reason);
        }
      }
      if (results.size === 0 && channelIds.length > 0) {
        throw new Error("All batches failed to retrieve channel statistics.");
      }
    } catch (error51) {
      if (error51 instanceof AppError)
        throw error51;
      throw new YouTubeApiError(`API call for batchFetchChannelStatistics failed`, error51);
    }
    return results;
  }
  async getChannelStatistics(channelId) {
    const cacheKey = channelId;
    const operation = async () => {
      try {
        const response = await this.trackCost(() => this.youtube.channels.list({
          part: ["snippet", "statistics"],
          id: [channelId]
        }), API_COSTS["channels.list"]);
        if (!response.data.items?.length) {
          throw new Error("Channel not found.");
        }
        const channel = response.data.items[0];
        return {
          channelId,
          title: channel.snippet?.title,
          subscriberCount: parseYouTubeNumber(channel.statistics?.subscriberCount),
          viewCount: parseYouTubeNumber(channel.statistics?.viewCount),
          videoCount: parseYouTubeNumber(channel.statistics?.videoCount),
          createdAt: channel.snippet?.publishedAt
        };
      } catch (error51) {
        if (error51 instanceof AppError)
          throw error51;
        throw new YouTubeApiError(`YouTube API call for getChannelStatistics failed for channelId: ${channelId}`, error51);
      }
    };
    return this.cacheService.getOrSet(cacheKey, operation, CACHE_TTLS.STANDARD, CACHE_COLLECTIONS.CHANNEL_STATS);
  }
  async fetchChannelRecentTopVideos(channelId, publishedAfter) {
    const cacheKey = this.cacheService.createOperationKey("fetchChannelRecentTopVideos", { channelId, publishedAfter });
    const operation = async () => {
      try {
        const searchResponse = await this.trackCost(() => this.youtube.search.list({
          channelId,
          part: ["snippet"],
          order: "viewCount",
          maxResults: 50,
          publishedAfter,
          type: ["video"]
        }), API_COSTS["search.list"]);
        const videoIds = searchResponse.data.items?.map((item) => item.id?.videoId).filter((id) => id !== void 0) || [];
        if (videoIds.length === 0) {
          return [];
        }
        const videosResponse = await this.trackCost(() => this.youtube.videos.list({
          part: ["statistics", "contentDetails"],
          id: videoIds
        }), API_COSTS["videos.list"]);
        return videosResponse.data.items || [];
      } catch (error51) {
        if (error51 instanceof AppError)
          throw error51;
        throw new YouTubeApiError(`YouTube API call for fetchChannelRecentTopVideos failed for channelId: ${channelId} and publishedAfter: ${publishedAfter}`, error51);
      }
    };
    return this.cacheService.getOrSet(cacheKey, operation, CACHE_TTLS.SEMI_STATIC, CACHE_COLLECTIONS.CHANNEL_RECENT_TOP_VIDEOS, { channelId, publishedAfter });
  }
  async getChannelTopVideos(options) {
    const cacheKey = this.cacheService.createOperationKey("getChannelTopVideos", options);
    const operation = async () => {
      try {
        const { channelId, maxResults = 10, includeTags = false, descriptionDetail = "NONE" } = options;
        const searchResults = [];
        let nextPageToken = void 0;
        const targetResults = Math.min(maxResults, this.ABSOLUTE_MAX_RESULTS);
        while (searchResults.length < targetResults) {
          const response = await this.trackCost(() => this.youtube.search.list({
            part: ["id"],
            channelId,
            maxResults: Math.min(this.MAX_RESULTS_PER_PAGE, targetResults - searchResults.length),
            order: "viewCount",
            type: ["video"],
            pageToken: nextPageToken
          }), API_COSTS["search.list"]);
          const searchResponse = response.data;
          if (!searchResponse.items?.length) {
            break;
          }
          searchResults.push(...searchResponse.items);
          nextPageToken = searchResponse.nextPageToken || void 0;
          if (!nextPageToken) {
            break;
          }
        }
        if (!searchResults.length) {
          throw new Error("No videos found.");
        }
        const videoIds = searchResults.map((item) => item.id?.videoId).filter((id) => id !== void 0);
        const videoDetails = [];
        const detailPromises = [];
        for (let i2 = 0; i2 < videoIds.length; i2 += this.MAX_RESULTS_PER_PAGE) {
          const batch = videoIds.slice(i2, i2 + this.MAX_RESULTS_PER_PAGE);
          const promise2 = this.trackCost(() => this.youtube.videos.list({
            part: ["snippet", "statistics", "contentDetails"],
            id: batch
          }), API_COSTS["videos.list"]);
          detailPromises.push(promise2);
        }
        const detailOutcomes = await Promise.allSettled(detailPromises);
        for (const outcome of detailOutcomes) {
          if (outcome.status === "fulfilled") {
            const response = outcome.value;
            if (response.data.items) {
              videoDetails.push(...response.data.items);
            }
          } else {
            if (outcome.reason instanceof AppError)
              throw outcome.reason;
            console.error("A video details batch in getChannelTopVideos failed:", outcome.reason);
          }
        }
        if (videoDetails.length === 0 && videoIds.length > 0) {
          throw new Error("All batches failed to retrieve video details.");
        }
        return videoDetails.slice(0, targetResults).map((video) => {
          const viewCount = parseYouTubeNumber(video.statistics?.viewCount);
          const likeCount = parseYouTubeNumber(video.statistics?.likeCount);
          const commentCount = parseYouTubeNumber(video.statistics?.commentCount);
          const formattedDescription = formatDescription(video.snippet?.description, descriptionDetail);
          const baseVideo = {
            id: video.id,
            title: video.snippet?.title,
            publishedAt: video.snippet?.publishedAt,
            duration: video.contentDetails?.duration,
            viewCount,
            likeCount,
            commentCount,
            likeToViewRatio: calculateLikeToViewRatio(viewCount, likeCount),
            commentToViewRatio: calculateCommentToViewRatio(viewCount, commentCount),
            categoryId: video.snippet?.categoryId ?? null,
            defaultLanguage: video.snippet?.defaultLanguage ?? null
          };
          const videoWithDescription = formattedDescription !== void 0 ? { ...baseVideo, description: formattedDescription } : baseVideo;
          return includeTags ? { ...videoWithDescription, tags: video.snippet?.tags ?? [] } : videoWithDescription;
        });
      } catch (error51) {
        if (error51 instanceof AppError)
          throw error51;
        throw new YouTubeApiError(`YouTube API call for getChannelTopVideos failed for channelId: ${options.channelId}`, error51);
      }
    };
    return this.cacheService.getOrSet(cacheKey, operation, CACHE_TTLS.SEMI_STATIC, CACHE_COLLECTIONS.CHANNEL_TOP_VIDEOS, options);
  }
  async getTrendingVideos(options) {
    const cacheKey = this.cacheService.createOperationKey("getTrendingVideos", options);
    const operation = async () => {
      try {
        const { regionCode = "US", categoryId, maxResults = 10 } = options;
        const params = {
          part: ["snippet", "statistics", "contentDetails"],
          chart: "mostPopular",
          regionCode,
          maxResults
        };
        if (categoryId) {
          params.videoCategoryId = categoryId;
        }
        const response = await this.trackCost(() => this.youtube.videos.list(params), API_COSTS["videos.list"]);
        return response.data.items?.map((video) => {
          const viewCount = parseYouTubeNumber(video.statistics?.viewCount);
          const likeCount = parseYouTubeNumber(video.statistics?.likeCount);
          const commentCount = parseYouTubeNumber(video.statistics?.commentCount);
          return {
            id: video.id,
            title: video.snippet?.title,
            channelId: video.snippet?.channelId,
            channelTitle: video.snippet?.channelTitle,
            publishedAt: video.snippet?.publishedAt,
            duration: video.contentDetails?.duration,
            viewCount,
            likeCount,
            commentCount,
            likeToViewRatio: calculateLikeToViewRatio(viewCount, likeCount),
            commentToViewRatio: calculateCommentToViewRatio(viewCount, commentCount)
          };
        }) || [];
      } catch (error51) {
        if (error51 instanceof AppError)
          throw error51;
        throw new YouTubeApiError(`YouTube API call for getTrendingVideos failed`, error51);
      }
    };
    return this.cacheService.getOrSet(cacheKey, operation, CACHE_TTLS.DYNAMIC, CACHE_COLLECTIONS.TRENDING_VIDEOS, options);
  }
  async getVideoComments(options) {
    const cacheKey = this.cacheService.createOperationKey("getVideoComments", options);
    const operation = async () => {
      try {
        const { videoId, maxResults, order, maxReplies = 0, commentDetail } = options;
        const commentThreadsResponse = await this.trackCost(() => this.youtube.commentThreads.list({
          part: ["snippet"],
          videoId,
          maxResults,
          order
        }), API_COSTS["commentThreads.list"]);
        const topLevelComments = commentThreadsResponse.data.items || [];
        let allReplies = [];
        if (maxReplies > 0 && topLevelComments.length > 0) {
          const replyPromises = topLevelComments.map((commentThread) => {
            const parentId = commentThread.id;
            if (!parentId)
              return Promise.resolve([]);
            return this.trackCost(() => this.youtube.comments.list({
              part: ["snippet"],
              parentId,
              maxResults: maxReplies
            }), API_COSTS["comments.list"]).then((res) => res.data.items || []);
          });
          allReplies = await Promise.all(replyPromises);
        }
        return topLevelComments.map((commentThread, index) => {
          const topLevelSnippet = commentThread.snippet?.topLevelComment?.snippet;
          const replies = allReplies[index] || [];
          const leanReplies = replies.map((reply) => {
            const replySnippet = reply.snippet;
            return {
              replyId: reply.id ?? "",
              author: replySnippet?.authorDisplayName ?? "",
              text: commentDetail === "SNIPPET" ? replySnippet?.textDisplay?.substring(0, 200) || "" : replySnippet?.textDisplay || "",
              publishedAt: replySnippet?.publishedAt ?? "",
              likeCount: replySnippet?.likeCount || 0
            };
          });
          return {
            commentId: commentThread.id ?? "",
            author: topLevelSnippet?.authorDisplayName ?? "",
            text: commentDetail === "SNIPPET" ? topLevelSnippet?.textDisplay?.substring(0, 200) || "" : topLevelSnippet?.textDisplay || "",
            publishedAt: topLevelSnippet?.publishedAt ?? "",
            likeCount: topLevelSnippet?.likeCount || 0,
            replies: leanReplies
          };
        });
      } catch (error51) {
        if (error51 && typeof error51 === "object" && "response" in error51 && error51.response && typeof error51.response === "object" && "status" in error51.response && error51.response.status === 403) {
          const errorData = error51.response.data;
          if (errorData?.error?.errors?.[0]?.reason === "commentsDisabled") {
            return [];
          }
        }
        if (error51 instanceof AppError)
          throw error51;
        throw new YouTubeApiError(`YouTube API call for getVideoComments failed for videoId: ${options.videoId}`, error51);
      }
    };
    return this.cacheService.getOrSet(cacheKey, operation, CACHE_TTLS.DYNAMIC, CACHE_COLLECTIONS.VIDEO_COMMENTS, options);
  }
  async getVideoCategories(regionCode = "US") {
    const cacheKey = this.cacheService.createOperationKey("getVideoCategories", {
      regionCode
    });
    const operation = async () => {
      try {
        const response = await this.trackCost(() => this.youtube.videoCategories.list({
          part: ["snippet"],
          regionCode
        }), API_COSTS["videoCategories.list"]);
        const categories = response.data.items?.map((category) => ({
          id: category.id,
          title: category.snippet?.title
        }));
        return categories || [];
      } catch (error51) {
        if (error51 instanceof AppError)
          throw error51;
        throw new YouTubeApiError(`YouTube API call for getVideoCategories failed for regionCode: ${regionCode}`, error51);
      }
    };
    return this.cacheService.getOrSet(cacheKey, operation, CACHE_TTLS.STATIC, CACHE_COLLECTIONS.VIDEO_CATEGORIES, { regionCode });
  }
};

// node_modules/youtube-transcript-plus/dist/youtube-transcript-plus.mjs
function __awaiter(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e2) {
        reject(e2);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e2) {
        reject(e2);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
var DEFAULT_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
var RE_YOUTUBE = /(?:v=|\/|v\/|embed\/|watch\?.*v=|youtu\.be\/|\/v\/|e\/|watch\?.*vi?=|\/embed\/|\/v\/|vi?\/|watch\?.*vi?=|youtu\.be\/|\/vi?\/|\/e\/)([a-zA-Z0-9_-]{11})/i;
var RE_XML_TRANSCRIPT = /<text start="([^"]*)" dur="([^"]*)">([^<]*)<\/text>/g;
var YoutubeTranscriptTooManyRequestError = class extends Error {
  constructor() {
    super("YouTube is receiving too many requests from your IP address. Please try again later or use a proxy. If the issue persists, consider reducing the frequency of requests.");
    this.name = "YoutubeTranscriptTooManyRequestError";
  }
};
var YoutubeTranscriptVideoUnavailableError = class extends Error {
  constructor(videoId) {
    super(`The video with ID "${videoId}" is no longer available or has been removed. Please check the video URL or ID and try again.`);
    this.name = "YoutubeTranscriptVideoUnavailableError";
    this.videoId = videoId;
  }
};
var YoutubeTranscriptDisabledError = class extends Error {
  constructor(videoId) {
    super(`Transcripts are disabled for the video with ID "${videoId}". This may be due to the video owner disabling captions or the video not supporting transcripts.`);
    this.name = "YoutubeTranscriptDisabledError";
    this.videoId = videoId;
  }
};
var YoutubeTranscriptNotAvailableError = class extends Error {
  constructor(videoId) {
    super(`No transcripts are available for the video with ID "${videoId}". This may be because the video does not have captions or the captions are not accessible.`);
    this.name = "YoutubeTranscriptNotAvailableError";
    this.videoId = videoId;
  }
};
var YoutubeTranscriptNotAvailableLanguageError = class extends Error {
  constructor(lang, availableLangs, videoId) {
    super(`No transcripts are available in "${lang}" for the video with ID "${videoId}". Available languages: ${availableLangs.join(", ")}. Please try a different language.`);
    this.name = "YoutubeTranscriptNotAvailableLanguageError";
    this.videoId = videoId;
    this.lang = lang;
    this.availableLangs = availableLangs;
  }
};
var YoutubeTranscriptInvalidLangError = class extends Error {
  constructor(lang) {
    super(`Invalid language code "${lang}". Please provide a valid BCP 47 language code (e.g., "en", "fr", "pt-BR").`);
    this.name = "YoutubeTranscriptInvalidLangError";
    this.lang = lang;
  }
};
var YoutubeTranscriptInvalidVideoIdError = class extends Error {
  constructor() {
    super('Invalid YouTube video ID or URL. Please provide a valid video ID or URL. Example: "dQw4w9WgXcQ" or "https://www.youtube.com/watch?v=dQw4w9WgXcQ".');
    this.name = "YoutubeTranscriptInvalidVideoIdError";
  }
};
var RE_VIDEO_ID = /^[a-zA-Z0-9_-]{11}$/;
var RE_BCP47_LANG = /^[a-zA-Z]{2,3}(-[a-zA-Z0-9]{2,8})*$/;
var XML_ENTITIES = {
  "&amp;": "&",
  "&lt;": "<",
  "&gt;": ">",
  "&quot;": '"',
  "&#39;": "'",
  "&apos;": "'"
};
var RE_XML_ENTITY = /&(?:amp|lt|gt|quot|apos|#39);/g;
function decodeXmlEntities(text) {
  return text.replace(RE_XML_ENTITY, (match) => {
    var _a3;
    return (_a3 = XML_ENTITIES[match]) !== null && _a3 !== void 0 ? _a3 : match;
  });
}
function retrieveVideoId(videoId) {
  if (RE_VIDEO_ID.test(videoId)) {
    return videoId;
  }
  const matchId = videoId.match(RE_YOUTUBE);
  if (matchId && matchId.length) {
    return matchId[1];
  }
  throw new YoutubeTranscriptInvalidVideoIdError();
}
function validateLang(lang) {
  if (!RE_BCP47_LANG.test(lang)) {
    throw new YoutubeTranscriptInvalidLangError(lang);
  }
}
function defaultFetch(params) {
  return __awaiter(this, void 0, void 0, function* () {
    const { url: url2, lang, userAgent, method = "GET", body, headers = {}, signal } = params;
    const fetchHeaders = Object.assign(Object.assign({ "User-Agent": userAgent || DEFAULT_USER_AGENT }, lang && { "Accept-Language": lang }), headers);
    const fetchOptions = {
      method,
      headers: fetchHeaders,
      signal
    };
    if (body && method === "POST") {
      fetchOptions.body = body;
    }
    return fetch(url2, fetchOptions);
  });
}
function isRetryableStatus(status) {
  return status === 429 || status >= 500 && status <= 599;
}
function sleep(ms, signal) {
  return new Promise((resolve2, reject) => {
    signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
    const timer = setTimeout(resolve2, ms);
    if (signal) {
      const onAbort = () => {
        clearTimeout(timer);
        reject(signal.reason);
      };
      signal.addEventListener("abort", onAbort, { once: true });
    }
  });
}
function fetchWithRetry(fetchFn, retries, retryDelay, signal) {
  return __awaiter(this, void 0, void 0, function* () {
    for (let attempt = 0; attempt <= retries; attempt++) {
      signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
      const response = yield fetchFn();
      if (!isRetryableStatus(response.status) || attempt === retries) {
        return response;
      }
      const delay = retryDelay * Math.pow(2, attempt);
      yield sleep(delay, signal);
    }
    throw new Error("Unexpected: retry loop exited without returning");
  });
}
var YoutubeTranscript = class _YoutubeTranscript {
  constructor(config2) {
    this.config = config2;
  }
  /**
   * Fetch caption tracks and the player response from the Innertube player API.
   * Shared logic used by both fetchTranscript and listLanguages.
   */
  _fetchCaptionTracks(identifier, lang) {
    return __awaiter(this, void 0, void 0, function* () {
      var _a3, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
      const userAgent = (_b = (_a3 = this.config) === null || _a3 === void 0 ? void 0 : _a3.userAgent) !== null && _b !== void 0 ? _b : DEFAULT_USER_AGENT;
      const protocol = ((_c = this.config) === null || _c === void 0 ? void 0 : _c.disableHttps) ? "http" : "https";
      const retries = (_e = (_d = this.config) === null || _d === void 0 ? void 0 : _d.retries) !== null && _e !== void 0 ? _e : 0;
      const retryDelay = (_g = (_f = this.config) === null || _f === void 0 ? void 0 : _f.retryDelay) !== null && _g !== void 0 ? _g : 1e3;
      const signal = (_h = this.config) === null || _h === void 0 ? void 0 : _h.signal;
      const watchUrl = `${protocol}://www.youtube.com/watch?v=${identifier}`;
      const watchFetchParams = { url: watchUrl, lang, userAgent, signal };
      const videoPageResponse = yield fetchWithRetry(() => {
        var _a4;
        return ((_a4 = this.config) === null || _a4 === void 0 ? void 0 : _a4.videoFetch) ? this.config.videoFetch(watchFetchParams) : defaultFetch(watchFetchParams);
      }, retries, retryDelay, signal);
      if (!videoPageResponse.ok) {
        throw new YoutubeTranscriptVideoUnavailableError(identifier);
      }
      const videoPageBody = yield videoPageResponse.text();
      if (videoPageBody.includes('class="g-recaptcha"')) {
        throw new YoutubeTranscriptTooManyRequestError();
      }
      const apiKeyMatch = videoPageBody.match(/"INNERTUBE_API_KEY":"([^"]+)"/) || videoPageBody.match(/INNERTUBE_API_KEY\\":\\"([^\\"]+)\\"/);
      if (!apiKeyMatch) {
        throw new YoutubeTranscriptNotAvailableError(identifier);
      }
      const apiKey = apiKeyMatch[1];
      const playerEndpoint = `${protocol}://www.youtube.com/youtubei/v1/player?key=${apiKey}`;
      const playerBody = {
        context: {
          client: {
            clientName: "ANDROID",
            clientVersion: "20.10.38"
          }
        },
        videoId: identifier
      };
      const playerFetchParams = {
        url: playerEndpoint,
        method: "POST",
        lang,
        userAgent,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(playerBody),
        signal
      };
      const playerRes = yield fetchWithRetry(() => {
        var _a4;
        return ((_a4 = this.config) === null || _a4 === void 0 ? void 0 : _a4.playerFetch) ? this.config.playerFetch(playerFetchParams) : defaultFetch(playerFetchParams);
      }, retries, retryDelay, signal);
      if (!playerRes.ok) {
        throw new YoutubeTranscriptVideoUnavailableError(identifier);
      }
      const playerJson = yield playerRes.json();
      const tracklist = (_k = (_j = playerJson.captions) === null || _j === void 0 ? void 0 : _j.playerCaptionsTracklistRenderer) !== null && _k !== void 0 ? _k : playerJson.playerCaptionsTracklistRenderer;
      const tracks = tracklist === null || tracklist === void 0 ? void 0 : tracklist.captionTracks;
      const isPlayableOk = ((_l = playerJson.playabilityStatus) === null || _l === void 0 ? void 0 : _l.status) === "OK";
      if (!playerJson.captions || !tracklist) {
        if (isPlayableOk) {
          throw new YoutubeTranscriptDisabledError(identifier);
        }
        throw new YoutubeTranscriptNotAvailableError(identifier);
      }
      if (!Array.isArray(tracks) || tracks.length === 0) {
        throw new YoutubeTranscriptDisabledError(identifier);
      }
      return { tracks, playerJson };
    });
  }
  /**
   * Extract VideoDetails from the Innertube player response.
   */
  _extractVideoDetails(playerJson, identifier) {
    var _a3, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
    const raw = playerJson.videoDetails;
    return {
      videoId: (_a3 = raw === null || raw === void 0 ? void 0 : raw.videoId) !== null && _a3 !== void 0 ? _a3 : identifier,
      title: (_b = raw === null || raw === void 0 ? void 0 : raw.title) !== null && _b !== void 0 ? _b : "",
      author: (_c = raw === null || raw === void 0 ? void 0 : raw.author) !== null && _c !== void 0 ? _c : "",
      channelId: (_d = raw === null || raw === void 0 ? void 0 : raw.channelId) !== null && _d !== void 0 ? _d : "",
      lengthSeconds: parseInt((_e = raw === null || raw === void 0 ? void 0 : raw.lengthSeconds) !== null && _e !== void 0 ? _e : "0", 10),
      viewCount: parseInt((_f = raw === null || raw === void 0 ? void 0 : raw.viewCount) !== null && _f !== void 0 ? _f : "0", 10),
      description: (_g = raw === null || raw === void 0 ? void 0 : raw.shortDescription) !== null && _g !== void 0 ? _g : "",
      keywords: (_h = raw === null || raw === void 0 ? void 0 : raw.keywords) !== null && _h !== void 0 ? _h : [],
      thumbnails: (_k = (_j = raw === null || raw === void 0 ? void 0 : raw.thumbnail) === null || _j === void 0 ? void 0 : _j.thumbnails) !== null && _k !== void 0 ? _k : [],
      isLiveContent: (_l = raw === null || raw === void 0 ? void 0 : raw.isLiveContent) !== null && _l !== void 0 ? _l : false
    };
  }
  /**
   * Fetch the transcript for a YouTube video.
   *
   * When `videoDetails` is set to `true` in the config, returns a {@link TranscriptResult}
   * containing both video metadata and transcript segments. Otherwise returns an array of
   * {@link TranscriptSegment} objects.
   *
   * **Note:** The instance method returns a union type because `videoDetails` is set at
   * construction time. For automatic type narrowing, use the static method or the
   * `fetchTranscript` convenience export instead.
   *
   * @param videoId - A YouTube video ID (11 characters) or full YouTube URL.
   * @returns An array of transcript segments, or a TranscriptResult if `videoDetails` is enabled.
   * @throws {@link YoutubeTranscriptInvalidVideoIdError} if the video ID/URL is invalid.
   * @throws {@link YoutubeTranscriptVideoUnavailableError} if the video is unavailable.
   * @throws {@link YoutubeTranscriptDisabledError} if transcripts are disabled.
   * @throws {@link YoutubeTranscriptNotAvailableError} if no transcript is available.
   * @throws {@link YoutubeTranscriptNotAvailableLanguageError} if the requested language is unavailable.
   * @throws {@link YoutubeTranscriptTooManyRequestError} if rate-limited by YouTube.
   */
  fetchTranscript(videoId) {
    return __awaiter(this, void 0, void 0, function* () {
      var _a3, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
      const identifier = retrieveVideoId(videoId);
      const lang = (_a3 = this.config) === null || _a3 === void 0 ? void 0 : _a3.lang;
      if (lang) {
        validateLang(lang);
      }
      const userAgent = (_c = (_b = this.config) === null || _b === void 0 ? void 0 : _b.userAgent) !== null && _c !== void 0 ? _c : DEFAULT_USER_AGENT;
      const includeDetails = ((_d = this.config) === null || _d === void 0 ? void 0 : _d.videoDetails) === true;
      const cache = (_e = this.config) === null || _e === void 0 ? void 0 : _e.cache;
      const cacheTTL = (_f = this.config) === null || _f === void 0 ? void 0 : _f.cacheTTL;
      const cacheKey = includeDetails ? `yt:transcript+details:${identifier}:${lang !== null && lang !== void 0 ? lang : ""}` : `yt:transcript:${identifier}:${lang !== null && lang !== void 0 ? lang : ""}`;
      if (cache) {
        const cached2 = yield cache.get(cacheKey);
        if (cached2) {
          try {
            return JSON.parse(cached2);
          } catch (_p) {
          }
        }
      }
      const { tracks, playerJson } = yield this._fetchCaptionTracks(identifier, lang);
      const selectedTrack = lang ? tracks.find((t2) => t2.languageCode === lang) : tracks[0];
      if (!selectedTrack) {
        const available = tracks.map((t2) => t2.languageCode).filter(Boolean);
        throw new YoutubeTranscriptNotAvailableLanguageError(lang, available, identifier);
      }
      const transcriptBaseURL = (_g = selectedTrack.baseUrl) !== null && _g !== void 0 ? _g : selectedTrack.url;
      if (!transcriptBaseURL) {
        throw new YoutubeTranscriptNotAvailableError(identifier);
      }
      let transcriptURL = transcriptBaseURL;
      transcriptURL = transcriptURL.replace(/&fmt=[^&]+/, "");
      if ((_h = this.config) === null || _h === void 0 ? void 0 : _h.disableHttps) {
        transcriptURL = transcriptURL.replace(/^https:\/\//, "http://");
      }
      const retries = (_k = (_j = this.config) === null || _j === void 0 ? void 0 : _j.retries) !== null && _k !== void 0 ? _k : 0;
      const retryDelay = (_m = (_l = this.config) === null || _l === void 0 ? void 0 : _l.retryDelay) !== null && _m !== void 0 ? _m : 1e3;
      const signal = (_o = this.config) === null || _o === void 0 ? void 0 : _o.signal;
      const transcriptFetchParams = { url: transcriptURL, lang, userAgent, signal };
      const transcriptResponse = yield fetchWithRetry(() => {
        var _a4;
        return ((_a4 = this.config) === null || _a4 === void 0 ? void 0 : _a4.transcriptFetch) ? this.config.transcriptFetch(transcriptFetchParams) : defaultFetch(transcriptFetchParams);
      }, retries, retryDelay, signal);
      if (!transcriptResponse.ok) {
        if (transcriptResponse.status === 429) {
          throw new YoutubeTranscriptTooManyRequestError();
        }
        throw new YoutubeTranscriptNotAvailableError(identifier);
      }
      const transcriptBody = yield transcriptResponse.text();
      const results = [...transcriptBody.matchAll(RE_XML_TRANSCRIPT)];
      const segments = results.map((m2) => ({
        text: decodeXmlEntities(m2[3]),
        duration: parseFloat(m2[2]),
        offset: parseFloat(m2[1]),
        lang: lang !== null && lang !== void 0 ? lang : selectedTrack.languageCode
      }));
      if (segments.length === 0) {
        throw new YoutubeTranscriptNotAvailableError(identifier);
      }
      const result = includeDetails ? { videoDetails: this._extractVideoDetails(playerJson, identifier), segments } : segments;
      if (cache) {
        try {
          yield cache.set(cacheKey, JSON.stringify(result), cacheTTL);
        } catch (_q) {
        }
      }
      return result;
    });
  }
  /**
   * List available caption languages for a YouTube video.
   *
   * Queries the Innertube player API to discover what caption tracks exist,
   * without downloading any transcript data.
   *
   * @param videoId - A YouTube video ID (11 characters) or full YouTube URL.
   * @returns An array of available caption track info objects.
   * @throws {@link YoutubeTranscriptInvalidVideoIdError} if the video ID/URL is invalid.
   * @throws {@link YoutubeTranscriptVideoUnavailableError} if the video is unavailable.
   * @throws {@link YoutubeTranscriptDisabledError} if transcripts are disabled.
   * @throws {@link YoutubeTranscriptNotAvailableError} if no captions are available.
   * @throws {@link YoutubeTranscriptTooManyRequestError} if rate-limited by YouTube.
   *
   * @example
   * ```typescript
   * const yt = new YoutubeTranscript();
   * const languages = await yt.listLanguages('dQw4w9WgXcQ');
   * // [
   * //   { languageCode: 'en', languageName: 'English', isAutoGenerated: false },
   * //   { languageCode: 'es', languageName: 'Spanish (auto-generated)', isAutoGenerated: true },
   * // ]
   * ```
   */
  listLanguages(videoId) {
    return __awaiter(this, void 0, void 0, function* () {
      const identifier = retrieveVideoId(videoId);
      const { tracks } = yield this._fetchCaptionTracks(identifier);
      return tracks.map((track) => {
        var _a3, _b;
        return {
          languageCode: track.languageCode,
          languageName: (_b = (_a3 = track.name) === null || _a3 === void 0 ? void 0 : _a3.simpleText) !== null && _b !== void 0 ? _b : track.languageCode,
          isAutoGenerated: track.kind === "asr"
        };
      });
    });
  }
  static fetchTranscript(videoId, config2) {
    return __awaiter(this, void 0, void 0, function* () {
      const instance = new _YoutubeTranscript(config2);
      return instance.fetchTranscript(videoId);
    });
  }
  /**
   * Static convenience method to list available caption languages without creating an instance.
   *
   * @param videoId - A YouTube video ID (11 characters) or full YouTube URL.
   * @param config - Optional configuration options.
   * @returns An array of available caption track info objects.
   */
  static listLanguages(videoId, config2) {
    return __awaiter(this, void 0, void 0, function* () {
      const instance = new _YoutubeTranscript(config2);
      return instance.listLanguages(videoId);
    });
  }
};
function fetchTranscript(videoId, config2) {
  return YoutubeTranscript.fetchTranscript(videoId, config2);
}
var listLanguages = YoutubeTranscript.listLanguages;

// node_modules/@kirbah/mcp-youtube/dist/services/transcript.service.js
var TranscriptService = class {
  cacheService;
  constructor(cacheService) {
    this.cacheService = cacheService;
  }
  async getTranscriptSegments(videoId, lang = "en", format = "key_segments") {
    const rawSubtitles = await this.fetchAndCacheRawTranscript(videoId, lang);
    if (!rawSubtitles || rawSubtitles.length === 0) {
      return null;
    }
    if (format === "full_text") {
      return {
        transcript: rawSubtitles.map((sub) => sub.text).join(" ")
      };
    }
    const hook = this.extractHook(rawSubtitles);
    const outro = this.extractOutro(rawSubtitles);
    return { hook, outro };
  }
  async fetchAndCacheRawTranscript(videoId, lang = "en") {
    const cacheKey = this.cacheService.createOperationKey("getTranscript", {
      videoId,
      lang
    });
    const operation = async () => {
      try {
        const transcript = await fetchTranscript(videoId, {
          lang
        });
        return transcript.map((item) => ({
          start: String(item.offset),
          dur: String(item.duration),
          text: item.text
        }));
      } catch (error51) {
        console.error(`[TranscriptService] Failed to fetch transcript for ${videoId} (lang: ${lang}):`, error51 instanceof Error ? error51.message : error51);
        return [];
      }
    };
    return this.cacheService.getOrSet(cacheKey, operation, CACHE_TTLS.STATIC, CACHE_COLLECTIONS.TRANSCRIPTS, { videoId, lang });
  }
  extractHook(subtitles) {
    const HOOK_DURATION_SECONDS = 40;
    let hookText = "";
    for (const sub of subtitles) {
      const startTime = parseFloat(sub.start);
      if (startTime < HOOK_DURATION_SECONDS) {
        hookText += sub.text + " ";
      } else {
        break;
      }
    }
    return hookText.trim();
  }
  extractOutro(subtitles) {
    if (subtitles.length === 0)
      return "";
    const OUTRO_DURATION_SECONDS = 30;
    const lastTimestamp = parseFloat(subtitles[subtitles.length - 1].start);
    const outroStartTime = Math.max(0, lastTimestamp - OUTRO_DURATION_SECONDS);
    const startIndex = subtitles.findIndex((sub) => parseFloat(sub.start) >= outroStartTime);
    if (startIndex === -1) {
      return subtitles.map((s2) => s2.text).join(" ").trim();
    }
    return subtitles.slice(startIndex).map((s2) => s2.text).join(" ").trim();
  }
};

// node_modules/@kirbah/mcp-youtube/dist/container.js
loadEnv();
var container = null;
function initializeContainer({ apiKey, mdbMcpConnectionString }) {
  if (mdbMcpConnectionString) {
    initializeDatabase(mdbMcpConnectionString);
  }
  const cacheService = new CacheService(mdbMcpConnectionString);
  const youtubeService = new YoutubeService(apiKey, cacheService);
  const transcriptService = new TranscriptService(cacheService);
  container = { cacheService, youtubeService, transcriptService };
  return container;
}

// node_modules/@kirbah/mcp-youtube/package.json
var package_default = {
  name: "@kirbah/mcp-youtube",
  version: "1.1.12",
  mcpName: "io.github.kirbah/mcp-youtube",
  description: "YouTube MCP server for token-optimized, structured data using the YouTube Data API v3.",
  main: "dist/index.js",
  type: "module",
  bin: {
    "mcp-youtube": "dist/index.js"
  },
  files: [
    "dist",
    "README.md",
    "LICENSE"
  ],
  scripts: {
    build: "tsc",
    start: "node dist/index.js",
    "start:client": "tsx ./src/index.ts",
    inspector: "npx @modelcontextprotocol/inspector tsx ./src/index.ts",
    clean: "rimraf dist",
    lint: "node --max-old-space-size=4096 node_modules/eslint/bin/eslint.js .",
    test: "jest",
    format: "prettier --write .",
    "format:check": "prettier --check ."
  },
  keywords: [
    "mcp",
    "youtube",
    "youtube-api",
    "claude",
    "anthropic",
    "model-context-protocol",
    "ai",
    "llm",
    "language-model",
    "tools"
  ],
  author: "Kiryl Bahdanau",
  license: "MIT",
  repository: {
    type: "git",
    url: "git+https://github.com/kirbah/mcp-youtube.git"
  },
  bugs: {
    url: "https://github.com/kirbah/mcp-youtube/issues"
  },
  homepage: "https://github.com/kirbah/mcp-youtube#readme",
  dependencies: {
    "@modelcontextprotocol/sdk": "^1.27.1",
    googleapis: "^171.4.0",
    mongodb: "^7.0.0",
    tsx: "^4.20.4",
    "youtube-transcript-plus": "^2.0.0",
    zod: "^4.1.13"
  },
  devDependencies: {
    "@eslint/js": "^10.0.1",
    "@types/jest": "30.0.0",
    "@types/node": "^25.5.2",
    eslint: "^10.2.0",
    "eslint-config-prettier": "^10.1.8",
    globals: "^17.4.0",
    jest: "30.4.2",
    "jest-junit": "^17.0.0",
    prettier: "^3.6.2",
    rimraf: "^6.0.1",
    "ts-jest": "^29.4.9",
    typescript: "^6.0.3",
    "typescript-eslint": "^8.58.1"
  },
  engines: {
    node: ">=20.12.0"
  },
  publishConfig: {
    access: "public"
  }
};

// node_modules/zod/v3/helpers/util.js
var util;
(function(util2) {
  util2.assertEqual = (_) => {
  };
  function assertIs2(_arg) {
  }
  util2.assertIs = assertIs2;
  function assertNever2(_x) {
    throw new Error();
  }
  util2.assertNever = assertNever2;
  util2.arrayToEnum = (items) => {
    const obj = {};
    for (const item of items) {
      obj[item] = item;
    }
    return obj;
  };
  util2.getValidEnumValues = (obj) => {
    const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
    const filtered = {};
    for (const k of validKeys) {
      filtered[k] = obj[k];
    }
    return util2.objectValues(filtered);
  };
  util2.objectValues = (obj) => {
    return util2.objectKeys(obj).map(function(e2) {
      return obj[e2];
    });
  };
  util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object3) => {
    const keys = [];
    for (const key in object3) {
      if (Object.prototype.hasOwnProperty.call(object3, key)) {
        keys.push(key);
      }
    }
    return keys;
  };
  util2.find = (arr, checker) => {
    for (const item of arr) {
      if (checker(item))
        return item;
    }
    return void 0;
  };
  util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
  function joinValues2(array2, separator = " | ") {
    return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
  }
  util2.joinValues = joinValues2;
  util2.jsonStringifyReplacer = (_, value) => {
    if (typeof value === "bigint") {
      return value.toString();
    }
    return value;
  };
})(util || (util = {}));
var objectUtil;
(function(objectUtil2) {
  objectUtil2.mergeShapes = (first, second) => {
    return {
      ...first,
      ...second
      // second overwrites first
    };
  };
})(objectUtil || (objectUtil = {}));
var ZodParsedType = util.arrayToEnum([
  "string",
  "nan",
  "number",
  "integer",
  "float",
  "boolean",
  "date",
  "bigint",
  "symbol",
  "function",
  "undefined",
  "null",
  "array",
  "object",
  "unknown",
  "promise",
  "void",
  "never",
  "map",
  "set"
]);
var getParsedType2 = (data) => {
  const t2 = typeof data;
  switch (t2) {
    case "undefined":
      return ZodParsedType.undefined;
    case "string":
      return ZodParsedType.string;
    case "number":
      return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
    case "boolean":
      return ZodParsedType.boolean;
    case "function":
      return ZodParsedType.function;
    case "bigint":
      return ZodParsedType.bigint;
    case "symbol":
      return ZodParsedType.symbol;
    case "object":
      if (Array.isArray(data)) {
        return ZodParsedType.array;
      }
      if (data === null) {
        return ZodParsedType.null;
      }
      if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
        return ZodParsedType.promise;
      }
      if (typeof Map !== "undefined" && data instanceof Map) {
        return ZodParsedType.map;
      }
      if (typeof Set !== "undefined" && data instanceof Set) {
        return ZodParsedType.set;
      }
      if (typeof Date !== "undefined" && data instanceof Date) {
        return ZodParsedType.date;
      }
      return ZodParsedType.object;
    default:
      return ZodParsedType.unknown;
  }
};

// node_modules/zod/v3/ZodError.js
var ZodIssueCode2 = util.arrayToEnum([
  "invalid_type",
  "invalid_literal",
  "custom",
  "invalid_union",
  "invalid_union_discriminator",
  "invalid_enum_value",
  "unrecognized_keys",
  "invalid_arguments",
  "invalid_return_type",
  "invalid_date",
  "invalid_string",
  "too_small",
  "too_big",
  "invalid_intersection_types",
  "not_multiple_of",
  "not_finite"
]);
var ZodError2 = class _ZodError extends Error {
  get errors() {
    return this.issues;
  }
  constructor(issues) {
    super();
    this.issues = [];
    this.addIssue = (sub) => {
      this.issues = [...this.issues, sub];
    };
    this.addIssues = (subs = []) => {
      this.issues = [...this.issues, ...subs];
    };
    const actualProto = new.target.prototype;
    if (Object.setPrototypeOf) {
      Object.setPrototypeOf(this, actualProto);
    } else {
      this.__proto__ = actualProto;
    }
    this.name = "ZodError";
    this.issues = issues;
  }
  format(_mapper) {
    const mapper = _mapper || function(issue2) {
      return issue2.message;
    };
    const fieldErrors = { _errors: [] };
    const processError = (error51) => {
      for (const issue2 of error51.issues) {
        if (issue2.code === "invalid_union") {
          issue2.unionErrors.map(processError);
        } else if (issue2.code === "invalid_return_type") {
          processError(issue2.returnTypeError);
        } else if (issue2.code === "invalid_arguments") {
          processError(issue2.argumentsError);
        } else if (issue2.path.length === 0) {
          fieldErrors._errors.push(mapper(issue2));
        } else {
          let curr = fieldErrors;
          let i2 = 0;
          while (i2 < issue2.path.length) {
            const el = issue2.path[i2];
            const terminal = i2 === issue2.path.length - 1;
            if (!terminal) {
              curr[el] = curr[el] || { _errors: [] };
            } else {
              curr[el] = curr[el] || { _errors: [] };
              curr[el]._errors.push(mapper(issue2));
            }
            curr = curr[el];
            i2++;
          }
        }
      }
    };
    processError(this);
    return fieldErrors;
  }
  static assert(value) {
    if (!(value instanceof _ZodError)) {
      throw new Error(`Not a ZodError: ${value}`);
    }
  }
  toString() {
    return this.message;
  }
  get message() {
    return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
  }
  get isEmpty() {
    return this.issues.length === 0;
  }
  flatten(mapper = (issue2) => issue2.message) {
    const fieldErrors = /* @__PURE__ */ Object.create(null);
    const formErrors = [];
    for (const sub of this.issues) {
      if (sub.path.length > 0) {
        const firstEl = sub.path[0];
        fieldErrors[firstEl] = fieldErrors[firstEl] || [];
        fieldErrors[firstEl].push(mapper(sub));
      } else {
        formErrors.push(mapper(sub));
      }
    }
    return { formErrors, fieldErrors };
  }
  get formErrors() {
    return this.flatten();
  }
};
ZodError2.create = (issues) => {
  const error51 = new ZodError2(issues);
  return error51;
};

// node_modules/zod/v3/locales/en.js
var errorMap = (issue2, _ctx) => {
  let message;
  switch (issue2.code) {
    case ZodIssueCode2.invalid_type:
      if (issue2.received === ZodParsedType.undefined) {
        message = "Required";
      } else {
        message = `Expected ${issue2.expected}, received ${issue2.received}`;
      }
      break;
    case ZodIssueCode2.invalid_literal:
      message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`;
      break;
    case ZodIssueCode2.unrecognized_keys:
      message = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`;
      break;
    case ZodIssueCode2.invalid_union:
      message = `Invalid input`;
      break;
    case ZodIssueCode2.invalid_union_discriminator:
      message = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`;
      break;
    case ZodIssueCode2.invalid_enum_value:
      message = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`;
      break;
    case ZodIssueCode2.invalid_arguments:
      message = `Invalid function arguments`;
      break;
    case ZodIssueCode2.invalid_return_type:
      message = `Invalid function return type`;
      break;
    case ZodIssueCode2.invalid_date:
      message = `Invalid date`;
      break;
    case ZodIssueCode2.invalid_string:
      if (typeof issue2.validation === "object") {
        if ("includes" in issue2.validation) {
          message = `Invalid input: must include "${issue2.validation.includes}"`;
          if (typeof issue2.validation.position === "number") {
            message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`;
          }
        } else if ("startsWith" in issue2.validation) {
          message = `Invalid input: must start with "${issue2.validation.startsWith}"`;
        } else if ("endsWith" in issue2.validation) {
          message = `Invalid input: must end with "${issue2.validation.endsWith}"`;
        } else {
          util.assertNever(issue2.validation);
        }
      } else if (issue2.validation !== "regex") {
        message = `Invalid ${issue2.validation}`;
      } else {
        message = "Invalid";
      }
      break;
    case ZodIssueCode2.too_small:
      if (issue2.type === "array")
        message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`;
      else if (issue2.type === "string")
        message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`;
      else if (issue2.type === "number")
        message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;
      else if (issue2.type === "bigint")
        message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;
      else if (issue2.type === "date")
        message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode2.too_big:
      if (issue2.type === "array")
        message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`;
      else if (issue2.type === "string")
        message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`;
      else if (issue2.type === "number")
        message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;
      else if (issue2.type === "bigint")
        message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;
      else if (issue2.type === "date")
        message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode2.custom:
      message = `Invalid input`;
      break;
    case ZodIssueCode2.invalid_intersection_types:
      message = `Intersection results could not be merged`;
      break;
    case ZodIssueCode2.not_multiple_of:
      message = `Number must be a multiple of ${issue2.multipleOf}`;
      break;
    case ZodIssueCode2.not_finite:
      message = "Number must be finite";
      break;
    default:
      message = _ctx.defaultError;
      util.assertNever(issue2);
  }
  return { message };
};
var en_default2 = errorMap;

// node_modules/zod/v3/errors.js
var overrideErrorMap = en_default2;
function getErrorMap2() {
  return overrideErrorMap;
}

// node_modules/zod/v3/helpers/parseUtil.js
var makeIssue = (params) => {
  const { data, path, errorMaps, issueData } = params;
  const fullPath = [...path, ...issueData.path || []];
  const fullIssue = {
    ...issueData,
    path: fullPath
  };
  if (issueData.message !== void 0) {
    return {
      ...issueData,
      path: fullPath,
      message: issueData.message
    };
  }
  let errorMessage = "";
  const maps = errorMaps.filter((m2) => !!m2).slice().reverse();
  for (const map2 of maps) {
    errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message;
  }
  return {
    ...issueData,
    path: fullPath,
    message: errorMessage
  };
};
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap2();
  const issue2 = makeIssue({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      // contextual error map is first priority
      ctx.schemaErrorMap,
      // then schema-bound map if available
      overrideMap,
      // then global override map
      overrideMap === en_default2 ? void 0 : en_default2
      // then global default map
    ].filter((x2) => !!x2)
  });
  ctx.common.issues.push(issue2);
}
var ParseStatus = class _ParseStatus {
  constructor() {
    this.value = "valid";
  }
  dirty() {
    if (this.value === "valid")
      this.value = "dirty";
  }
  abort() {
    if (this.value !== "aborted")
      this.value = "aborted";
  }
  static mergeArray(status, results) {
    const arrayValue = [];
    for (const s2 of results) {
      if (s2.status === "aborted")
        return INVALID;
      if (s2.status === "dirty")
        status.dirty();
      arrayValue.push(s2.value);
    }
    return { status: status.value, value: arrayValue };
  }
  static async mergeObjectAsync(status, pairs) {
    const syncPairs = [];
    for (const pair of pairs) {
      const key = await pair.key;
      const value = await pair.value;
      syncPairs.push({
        key,
        value
      });
    }
    return _ParseStatus.mergeObjectSync(status, syncPairs);
  }
  static mergeObjectSync(status, pairs) {
    const finalObject = {};
    for (const pair of pairs) {
      const { key, value } = pair;
      if (key.status === "aborted")
        return INVALID;
      if (value.status === "aborted")
        return INVALID;
      if (key.status === "dirty")
        status.dirty();
      if (value.status === "dirty")
        status.dirty();
      if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
        finalObject[key.value] = value.value;
      }
    }
    return { status: status.value, value: finalObject };
  }
};
var INVALID = Object.freeze({
  status: "aborted"
});
var DIRTY = (value) => ({ status: "dirty", value });
var OK = (value) => ({ status: "valid", value });
var isAborted = (x2) => x2.status === "aborted";
var isDirty = (x2) => x2.status === "dirty";
var isValid = (x2) => x2.status === "valid";
var isAsync = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise;

// node_modules/zod/v3/helpers/errorUtil.js
var errorUtil;
(function(errorUtil2) {
  errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
})(errorUtil || (errorUtil = {}));

// node_modules/zod/v3/types.js
var ParseInputLazyPath = class {
  constructor(parent, value, path, key) {
    this._cachedPath = [];
    this.parent = parent;
    this.data = value;
    this._path = path;
    this._key = key;
  }
  get path() {
    if (!this._cachedPath.length) {
      if (Array.isArray(this._key)) {
        this._cachedPath.push(...this._path, ...this._key);
      } else {
        this._cachedPath.push(...this._path, this._key);
      }
    }
    return this._cachedPath;
  }
};
var handleResult = (ctx, result) => {
  if (isValid(result)) {
    return { success: true, data: result.value };
  } else {
    if (!ctx.common.issues.length) {
      throw new Error("Validation failed but no issues detected.");
    }
    return {
      success: false,
      get error() {
        if (this._error)
          return this._error;
        const error51 = new ZodError2(ctx.common.issues);
        this._error = error51;
        return this._error;
      }
    };
  }
};
function processCreateParams(params) {
  if (!params)
    return {};
  const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
  if (errorMap2 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap2)
    return { errorMap: errorMap2, description };
  const customMap = (iss, ctx) => {
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message ?? ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: message ?? required_error ?? ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: message ?? invalid_type_error ?? ctx.defaultError };
  };
  return { errorMap: customMap, description };
}
var ZodType2 = class {
  get description() {
    return this._def.description;
  }
  _getType(input) {
    return getParsedType2(input.data);
  }
  _getOrReturnCtx(input, ctx) {
    return ctx || {
      common: input.parent.common,
      data: input.data,
      parsedType: getParsedType2(input.data),
      schemaErrorMap: this._def.errorMap,
      path: input.path,
      parent: input.parent
    };
  }
  _processInputParams(input) {
    return {
      status: new ParseStatus(),
      ctx: {
        common: input.parent.common,
        data: input.data,
        parsedType: getParsedType2(input.data),
        schemaErrorMap: this._def.errorMap,
        path: input.path,
        parent: input.parent
      }
    };
  }
  _parseSync(input) {
    const result = this._parse(input);
    if (isAsync(result)) {
      throw new Error("Synchronous parse encountered promise.");
    }
    return result;
  }
  _parseAsync(input) {
    const result = this._parse(input);
    return Promise.resolve(result);
  }
  parse(data, params) {
    const result = this.safeParse(data, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  safeParse(data, params) {
    const ctx = {
      common: {
        issues: [],
        async: params?.async ?? false,
        contextualErrorMap: params?.errorMap
      },
      path: params?.path || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType2(data)
    };
    const result = this._parseSync({ data, path: ctx.path, parent: ctx });
    return handleResult(ctx, result);
  }
  "~validate"(data) {
    const ctx = {
      common: {
        issues: [],
        async: !!this["~standard"].async
      },
      path: [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType2(data)
    };
    if (!this["~standard"].async) {
      try {
        const result = this._parseSync({ data, path: [], parent: ctx });
        return isValid(result) ? {
          value: result.value
        } : {
          issues: ctx.common.issues
        };
      } catch (err) {
        if (err?.message?.toLowerCase()?.includes("encountered")) {
          this["~standard"].async = true;
        }
        ctx.common = {
          issues: [],
          async: true
        };
      }
    }
    return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
      value: result.value
    } : {
      issues: ctx.common.issues
    });
  }
  async parseAsync(data, params) {
    const result = await this.safeParseAsync(data, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  async safeParseAsync(data, params) {
    const ctx = {
      common: {
        issues: [],
        contextualErrorMap: params?.errorMap,
        async: true
      },
      path: params?.path || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType2(data)
    };
    const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
    const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
    return handleResult(ctx, result);
  }
  refine(check2, message) {
    const getIssueProperties = (val) => {
      if (typeof message === "string" || typeof message === "undefined") {
        return { message };
      } else if (typeof message === "function") {
        return message(val);
      } else {
        return message;
      }
    };
    return this._refinement((val, ctx) => {
      const result = check2(val);
      const setError = () => ctx.addIssue({
        code: ZodIssueCode2.custom,
        ...getIssueProperties(val)
      });
      if (typeof Promise !== "undefined" && result instanceof Promise) {
        return result.then((data) => {
          if (!data) {
            setError();
            return false;
          } else {
            return true;
          }
        });
      }
      if (!result) {
        setError();
        return false;
      } else {
        return true;
      }
    });
  }
  refinement(check2, refinementData) {
    return this._refinement((val, ctx) => {
      if (!check2(val)) {
        ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
        return false;
      } else {
        return true;
      }
    });
  }
  _refinement(refinement) {
    return new ZodEffects({
      schema: this,
      typeName: ZodFirstPartyTypeKind2.ZodEffects,
      effect: { type: "refinement", refinement }
    });
  }
  superRefine(refinement) {
    return this._refinement(refinement);
  }
  constructor(def) {
    this.spa = this.safeParseAsync;
    this._def = def;
    this.parse = this.parse.bind(this);
    this.safeParse = this.safeParse.bind(this);
    this.parseAsync = this.parseAsync.bind(this);
    this.safeParseAsync = this.safeParseAsync.bind(this);
    this.spa = this.spa.bind(this);
    this.refine = this.refine.bind(this);
    this.refinement = this.refinement.bind(this);
    this.superRefine = this.superRefine.bind(this);
    this.optional = this.optional.bind(this);
    this.nullable = this.nullable.bind(this);
    this.nullish = this.nullish.bind(this);
    this.array = this.array.bind(this);
    this.promise = this.promise.bind(this);
    this.or = this.or.bind(this);
    this.and = this.and.bind(this);
    this.transform = this.transform.bind(this);
    this.brand = this.brand.bind(this);
    this.default = this.default.bind(this);
    this.catch = this.catch.bind(this);
    this.describe = this.describe.bind(this);
    this.pipe = this.pipe.bind(this);
    this.readonly = this.readonly.bind(this);
    this.isNullable = this.isNullable.bind(this);
    this.isOptional = this.isOptional.bind(this);
    this["~standard"] = {
      version: 1,
      vendor: "zod",
      validate: (data) => this["~validate"](data)
    };
  }
  optional() {
    return ZodOptional2.create(this, this._def);
  }
  nullable() {
    return ZodNullable2.create(this, this._def);
  }
  nullish() {
    return this.nullable().optional();
  }
  array() {
    return ZodArray2.create(this);
  }
  promise() {
    return ZodPromise2.create(this, this._def);
  }
  or(option) {
    return ZodUnion2.create([this, option], this._def);
  }
  and(incoming) {
    return ZodIntersection2.create(this, incoming, this._def);
  }
  transform(transform2) {
    return new ZodEffects({
      ...processCreateParams(this._def),
      schema: this,
      typeName: ZodFirstPartyTypeKind2.ZodEffects,
      effect: { type: "transform", transform: transform2 }
    });
  }
  default(def) {
    const defaultValueFunc = typeof def === "function" ? def : () => def;
    return new ZodDefault2({
      ...processCreateParams(this._def),
      innerType: this,
      defaultValue: defaultValueFunc,
      typeName: ZodFirstPartyTypeKind2.ZodDefault
    });
  }
  brand() {
    return new ZodBranded({
      typeName: ZodFirstPartyTypeKind2.ZodBranded,
      type: this,
      ...processCreateParams(this._def)
    });
  }
  catch(def) {
    const catchValueFunc = typeof def === "function" ? def : () => def;
    return new ZodCatch2({
      ...processCreateParams(this._def),
      innerType: this,
      catchValue: catchValueFunc,
      typeName: ZodFirstPartyTypeKind2.ZodCatch
    });
  }
  describe(description) {
    const This = this.constructor;
    return new This({
      ...this._def,
      description
    });
  }
  pipe(target) {
    return ZodPipeline.create(this, target);
  }
  readonly() {
    return ZodReadonly2.create(this);
  }
  isOptional() {
    return this.safeParse(void 0).success;
  }
  isNullable() {
    return this.safeParse(null).success;
  }
};
var cuidRegex = /^c[^\s-]{8,}$/i;
var cuid2Regex = /^[0-9a-z]+$/;
var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
var nanoidRegex = /^[a-z0-9_-]{21}$/i;
var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
var emojiRegex;
var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
var dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
  let secondsRegexSource = `[0-5]\\d`;
  if (args.precision) {
    secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  }
  const secondsQuantifier = args.precision ? "+" : "?";
  return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
  return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
  let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
  const opts = [];
  opts.push(args.local ? `Z?` : `Z`);
  if (args.offset)
    opts.push(`([+-]\\d{2}:?\\d{2})`);
  regex = `${regex}(${opts.join("|")})`;
  return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version2) {
  if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
function isValidJWT2(jwt2, alg) {
  if (!jwtRegex.test(jwt2))
    return false;
  try {
    const [header] = jwt2.split(".");
    if (!header)
      return false;
    const base643 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base643));
    if (typeof decoded !== "object" || decoded === null)
      return false;
    if ("typ" in decoded && decoded?.typ !== "JWT")
      return false;
    if (!decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch {
    return false;
  }
}
function isValidCidr(ip, version2) {
  if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) {
    return true;
  }
  return false;
}
var ZodString2 = class _ZodString2 extends ZodType2 {
  _parse(input) {
    if (this._def.coerce) {
      input.data = String(input.data);
    }
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.string) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType.string,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const status = new ParseStatus();
    let ctx = void 0;
    for (const check2 of this._def.checks) {
      if (check2.kind === "min") {
        if (input.data.length < check2.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode2.too_small,
            minimum: check2.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "max") {
        if (input.data.length > check2.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode2.too_big,
            maximum: check2.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "length") {
        const tooBig = input.data.length > check2.value;
        const tooSmall = input.data.length < check2.value;
        if (tooBig || tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          if (tooBig) {
            addIssueToContext(ctx, {
              code: ZodIssueCode2.too_big,
              maximum: check2.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check2.message
            });
          } else if (tooSmall) {
            addIssueToContext(ctx, {
              code: ZodIssueCode2.too_small,
              minimum: check2.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check2.message
            });
          }
          status.dirty();
        }
      } else if (check2.kind === "email") {
        if (!emailRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "email",
            code: ZodIssueCode2.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "emoji") {
        if (!emojiRegex) {
          emojiRegex = new RegExp(_emojiRegex, "u");
        }
        if (!emojiRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "emoji",
            code: ZodIssueCode2.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "uuid") {
        if (!uuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "uuid",
            code: ZodIssueCode2.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "nanoid") {
        if (!nanoidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "nanoid",
            code: ZodIssueCode2.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "cuid") {
        if (!cuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid",
            code: ZodIssueCode2.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "cuid2") {
        if (!cuid2Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid2",
            code: ZodIssueCode2.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "ulid") {
        if (!ulidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ulid",
            code: ZodIssueCode2.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "url") {
        try {
          new URL(input.data);
        } catch {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "url",
            code: ZodIssueCode2.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "regex") {
        check2.regex.lastIndex = 0;
        const testResult = check2.regex.test(input.data);
        if (!testResult) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "regex",
            code: ZodIssueCode2.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "trim") {
        input.data = input.data.trim();
      } else if (check2.kind === "includes") {
        if (!input.data.includes(check2.value, check2.position)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode2.invalid_string,
            validation: { includes: check2.value, position: check2.position },
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "toLowerCase") {
        input.data = input.data.toLowerCase();
      } else if (check2.kind === "toUpperCase") {
        input.data = input.data.toUpperCase();
      } else if (check2.kind === "startsWith") {
        if (!input.data.startsWith(check2.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode2.invalid_string,
            validation: { startsWith: check2.value },
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "endsWith") {
        if (!input.data.endsWith(check2.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode2.invalid_string,
            validation: { endsWith: check2.value },
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "datetime") {
        const regex = datetimeRegex(check2);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode2.invalid_string,
            validation: "datetime",
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "date") {
        const regex = dateRegex;
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode2.invalid_string,
            validation: "date",
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "time") {
        const regex = timeRegex(check2);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode2.invalid_string,
            validation: "time",
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "duration") {
        if (!durationRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "duration",
            code: ZodIssueCode2.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "ip") {
        if (!isValidIP(input.data, check2.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ip",
            code: ZodIssueCode2.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "jwt") {
        if (!isValidJWT2(input.data, check2.alg)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "jwt",
            code: ZodIssueCode2.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "cidr") {
        if (!isValidCidr(input.data, check2.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cidr",
            code: ZodIssueCode2.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "base64") {
        if (!base64Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "base64",
            code: ZodIssueCode2.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "base64url") {
        if (!base64urlRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "base64url",
            code: ZodIssueCode2.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check2);
      }
    }
    return { status: status.value, value: input.data };
  }
  _regex(regex, validation, message) {
    return this.refinement((data) => regex.test(data), {
      validation,
      code: ZodIssueCode2.invalid_string,
      ...errorUtil.errToObj(message)
    });
  }
  _addCheck(check2) {
    return new _ZodString2({
      ...this._def,
      checks: [...this._def.checks, check2]
    });
  }
  email(message) {
    return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
  }
  url(message) {
    return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
  }
  emoji(message) {
    return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
  }
  uuid(message) {
    return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
  }
  nanoid(message) {
    return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
  }
  cuid(message) {
    return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
  }
  cuid2(message) {
    return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
  }
  ulid(message) {
    return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
  }
  base64(message) {
    return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
  }
  base64url(message) {
    return this._addCheck({
      kind: "base64url",
      ...errorUtil.errToObj(message)
    });
  }
  jwt(options) {
    return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
  }
  ip(options) {
    return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
  }
  cidr(options) {
    return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
  }
  datetime(options) {
    if (typeof options === "string") {
      return this._addCheck({
        kind: "datetime",
        precision: null,
        offset: false,
        local: false,
        message: options
      });
    }
    return this._addCheck({
      kind: "datetime",
      precision: typeof options?.precision === "undefined" ? null : options?.precision,
      offset: options?.offset ?? false,
      local: options?.local ?? false,
      ...errorUtil.errToObj(options?.message)
    });
  }
  date(message) {
    return this._addCheck({ kind: "date", message });
  }
  time(options) {
    if (typeof options === "string") {
      return this._addCheck({
        kind: "time",
        precision: null,
        message: options
      });
    }
    return this._addCheck({
      kind: "time",
      precision: typeof options?.precision === "undefined" ? null : options?.precision,
      ...errorUtil.errToObj(options?.message)
    });
  }
  duration(message) {
    return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
  }
  regex(regex, message) {
    return this._addCheck({
      kind: "regex",
      regex,
      ...errorUtil.errToObj(message)
    });
  }
  includes(value, options) {
    return this._addCheck({
      kind: "includes",
      value,
      position: options?.position,
      ...errorUtil.errToObj(options?.message)
    });
  }
  startsWith(value, message) {
    return this._addCheck({
      kind: "startsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  endsWith(value, message) {
    return this._addCheck({
      kind: "endsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  min(minLength, message) {
    return this._addCheck({
      kind: "min",
      value: minLength,
      ...errorUtil.errToObj(message)
    });
  }
  max(maxLength, message) {
    return this._addCheck({
      kind: "max",
      value: maxLength,
      ...errorUtil.errToObj(message)
    });
  }
  length(len, message) {
    return this._addCheck({
      kind: "length",
      value: len,
      ...errorUtil.errToObj(message)
    });
  }
  /**
   * Equivalent to `.min(1)`
   */
  nonempty(message) {
    return this.min(1, errorUtil.errToObj(message));
  }
  trim() {
    return new _ZodString2({
      ...this._def,
      checks: [...this._def.checks, { kind: "trim" }]
    });
  }
  toLowerCase() {
    return new _ZodString2({
      ...this._def,
      checks: [...this._def.checks, { kind: "toLowerCase" }]
    });
  }
  toUpperCase() {
    return new _ZodString2({
      ...this._def,
      checks: [...this._def.checks, { kind: "toUpperCase" }]
    });
  }
  get isDatetime() {
    return !!this._def.checks.find((ch) => ch.kind === "datetime");
  }
  get isDate() {
    return !!this._def.checks.find((ch) => ch.kind === "date");
  }
  get isTime() {
    return !!this._def.checks.find((ch) => ch.kind === "time");
  }
  get isDuration() {
    return !!this._def.checks.find((ch) => ch.kind === "duration");
  }
  get isEmail() {
    return !!this._def.checks.find((ch) => ch.kind === "email");
  }
  get isURL() {
    return !!this._def.checks.find((ch) => ch.kind === "url");
  }
  get isEmoji() {
    return !!this._def.checks.find((ch) => ch.kind === "emoji");
  }
  get isUUID() {
    return !!this._def.checks.find((ch) => ch.kind === "uuid");
  }
  get isNANOID() {
    return !!this._def.checks.find((ch) => ch.kind === "nanoid");
  }
  get isCUID() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid");
  }
  get isCUID2() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid2");
  }
  get isULID() {
    return !!this._def.checks.find((ch) => ch.kind === "ulid");
  }
  get isIP() {
    return !!this._def.checks.find((ch) => ch.kind === "ip");
  }
  get isCIDR() {
    return !!this._def.checks.find((ch) => ch.kind === "cidr");
  }
  get isBase64() {
    return !!this._def.checks.find((ch) => ch.kind === "base64");
  }
  get isBase64url() {
    return !!this._def.checks.find((ch) => ch.kind === "base64url");
  }
  get minLength() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxLength() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
};
ZodString2.create = (params) => {
  return new ZodString2({
    checks: [],
    typeName: ZodFirstPartyTypeKind2.ZodString,
    coerce: params?.coerce ?? false,
    ...processCreateParams(params)
  });
};
function floatSafeRemainder2(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / 10 ** decCount;
}
var ZodNumber2 = class _ZodNumber extends ZodType2 {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
    this.step = this.multipleOf;
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = Number(input.data);
    }
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.number) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType.number,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    let ctx = void 0;
    const status = new ParseStatus();
    for (const check2 of this._def.checks) {
      if (check2.kind === "int") {
        if (!util.isInteger(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode2.invalid_type,
            expected: "integer",
            received: "float",
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "min") {
        const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode2.too_small,
            minimum: check2.value,
            type: "number",
            inclusive: check2.inclusive,
            exact: false,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "max") {
        const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode2.too_big,
            maximum: check2.value,
            type: "number",
            inclusive: check2.inclusive,
            exact: false,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "multipleOf") {
        if (floatSafeRemainder2(input.data, check2.value) !== 0) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode2.not_multiple_of,
            multipleOf: check2.value,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "finite") {
        if (!Number.isFinite(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode2.not_finite,
            message: check2.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check2);
      }
    }
    return { status: status.value, value: input.data };
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new _ZodNumber({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check2) {
    return new _ZodNumber({
      ...this._def,
      checks: [...this._def.checks, check2]
    });
  }
  int(message) {
    return this._addCheck({
      kind: "int",
      message: errorUtil.toString(message)
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  finite(message) {
    return this._addCheck({
      kind: "finite",
      message: errorUtil.toString(message)
    });
  }
  safe(message) {
    return this._addCheck({
      kind: "min",
      inclusive: true,
      value: Number.MIN_SAFE_INTEGER,
      message: errorUtil.toString(message)
    })._addCheck({
      kind: "max",
      inclusive: true,
      value: Number.MAX_SAFE_INTEGER,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxValue() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
  get isInt() {
    return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
  }
  get isFinite() {
    let max = null;
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
        return true;
      } else if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      } else if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return Number.isFinite(min) && Number.isFinite(max);
  }
};
ZodNumber2.create = (params) => {
  return new ZodNumber2({
    checks: [],
    typeName: ZodFirstPartyTypeKind2.ZodNumber,
    coerce: params?.coerce || false,
    ...processCreateParams(params)
  });
};
var ZodBigInt2 = class _ZodBigInt extends ZodType2 {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
  }
  _parse(input) {
    if (this._def.coerce) {
      try {
        input.data = BigInt(input.data);
      } catch {
        return this._getInvalidInput(input);
      }
    }
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.bigint) {
      return this._getInvalidInput(input);
    }
    let ctx = void 0;
    const status = new ParseStatus();
    for (const check2 of this._def.checks) {
      if (check2.kind === "min") {
        const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode2.too_small,
            type: "bigint",
            minimum: check2.value,
            inclusive: check2.inclusive,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "max") {
        const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode2.too_big,
            type: "bigint",
            maximum: check2.value,
            inclusive: check2.inclusive,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "multipleOf") {
        if (input.data % check2.value !== BigInt(0)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode2.not_multiple_of,
            multipleOf: check2.value,
            message: check2.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check2);
      }
    }
    return { status: status.value, value: input.data };
  }
  _getInvalidInput(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode2.invalid_type,
      expected: ZodParsedType.bigint,
      received: ctx.parsedType
    });
    return INVALID;
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new _ZodBigInt({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check2) {
    return new _ZodBigInt({
      ...this._def,
      checks: [...this._def.checks, check2]
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxValue() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
};
ZodBigInt2.create = (params) => {
  return new ZodBigInt2({
    checks: [],
    typeName: ZodFirstPartyTypeKind2.ZodBigInt,
    coerce: params?.coerce ?? false,
    ...processCreateParams(params)
  });
};
var ZodBoolean2 = class extends ZodType2 {
  _parse(input) {
    if (this._def.coerce) {
      input.data = Boolean(input.data);
    }
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.boolean) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType.boolean,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodBoolean2.create = (params) => {
  return new ZodBoolean2({
    typeName: ZodFirstPartyTypeKind2.ZodBoolean,
    coerce: params?.coerce || false,
    ...processCreateParams(params)
  });
};
var ZodDate2 = class _ZodDate extends ZodType2 {
  _parse(input) {
    if (this._def.coerce) {
      input.data = new Date(input.data);
    }
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.date) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType.date,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    if (Number.isNaN(input.data.getTime())) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode2.invalid_date
      });
      return INVALID;
    }
    const status = new ParseStatus();
    let ctx = void 0;
    for (const check2 of this._def.checks) {
      if (check2.kind === "min") {
        if (input.data.getTime() < check2.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode2.too_small,
            message: check2.message,
            inclusive: true,
            exact: false,
            minimum: check2.value,
            type: "date"
          });
          status.dirty();
        }
      } else if (check2.kind === "max") {
        if (input.data.getTime() > check2.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode2.too_big,
            message: check2.message,
            inclusive: true,
            exact: false,
            maximum: check2.value,
            type: "date"
          });
          status.dirty();
        }
      } else {
        util.assertNever(check2);
      }
    }
    return {
      status: status.value,
      value: new Date(input.data.getTime())
    };
  }
  _addCheck(check2) {
    return new _ZodDate({
      ...this._def,
      checks: [...this._def.checks, check2]
    });
  }
  min(minDate, message) {
    return this._addCheck({
      kind: "min",
      value: minDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  max(maxDate, message) {
    return this._addCheck({
      kind: "max",
      value: maxDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  get minDate() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min != null ? new Date(min) : null;
  }
  get maxDate() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max != null ? new Date(max) : null;
  }
};
ZodDate2.create = (params) => {
  return new ZodDate2({
    checks: [],
    coerce: params?.coerce || false,
    typeName: ZodFirstPartyTypeKind2.ZodDate,
    ...processCreateParams(params)
  });
};
var ZodSymbol2 = class extends ZodType2 {
  _parse(input) {
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.symbol) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType.symbol,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodSymbol2.create = (params) => {
  return new ZodSymbol2({
    typeName: ZodFirstPartyTypeKind2.ZodSymbol,
    ...processCreateParams(params)
  });
};
var ZodUndefined2 = class extends ZodType2 {
  _parse(input) {
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType.undefined,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodUndefined2.create = (params) => {
  return new ZodUndefined2({
    typeName: ZodFirstPartyTypeKind2.ZodUndefined,
    ...processCreateParams(params)
  });
};
var ZodNull2 = class extends ZodType2 {
  _parse(input) {
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.null) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType.null,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodNull2.create = (params) => {
  return new ZodNull2({
    typeName: ZodFirstPartyTypeKind2.ZodNull,
    ...processCreateParams(params)
  });
};
var ZodAny2 = class extends ZodType2 {
  constructor() {
    super(...arguments);
    this._any = true;
  }
  _parse(input) {
    return OK(input.data);
  }
};
ZodAny2.create = (params) => {
  return new ZodAny2({
    typeName: ZodFirstPartyTypeKind2.ZodAny,
    ...processCreateParams(params)
  });
};
var ZodUnknown2 = class extends ZodType2 {
  constructor() {
    super(...arguments);
    this._unknown = true;
  }
  _parse(input) {
    return OK(input.data);
  }
};
ZodUnknown2.create = (params) => {
  return new ZodUnknown2({
    typeName: ZodFirstPartyTypeKind2.ZodUnknown,
    ...processCreateParams(params)
  });
};
var ZodNever2 = class extends ZodType2 {
  _parse(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode2.invalid_type,
      expected: ZodParsedType.never,
      received: ctx.parsedType
    });
    return INVALID;
  }
};
ZodNever2.create = (params) => {
  return new ZodNever2({
    typeName: ZodFirstPartyTypeKind2.ZodNever,
    ...processCreateParams(params)
  });
};
var ZodVoid2 = class extends ZodType2 {
  _parse(input) {
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType.void,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodVoid2.create = (params) => {
  return new ZodVoid2({
    typeName: ZodFirstPartyTypeKind2.ZodVoid,
    ...processCreateParams(params)
  });
};
var ZodArray2 = class _ZodArray extends ZodType2 {
  _parse(input) {
    const { ctx, status } = this._processInputParams(input);
    const def = this._def;
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (def.exactLength !== null) {
      const tooBig = ctx.data.length > def.exactLength.value;
      const tooSmall = ctx.data.length < def.exactLength.value;
      if (tooBig || tooSmall) {
        addIssueToContext(ctx, {
          code: tooBig ? ZodIssueCode2.too_big : ZodIssueCode2.too_small,
          minimum: tooSmall ? def.exactLength.value : void 0,
          maximum: tooBig ? def.exactLength.value : void 0,
          type: "array",
          inclusive: true,
          exact: true,
          message: def.exactLength.message
        });
        status.dirty();
      }
    }
    if (def.minLength !== null) {
      if (ctx.data.length < def.minLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode2.too_small,
          minimum: def.minLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.minLength.message
        });
        status.dirty();
      }
    }
    if (def.maxLength !== null) {
      if (ctx.data.length > def.maxLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode2.too_big,
          maximum: def.maxLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.maxLength.message
        });
        status.dirty();
      }
    }
    if (ctx.common.async) {
      return Promise.all([...ctx.data].map((item, i2) => {
        return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i2));
      })).then((result2) => {
        return ParseStatus.mergeArray(status, result2);
      });
    }
    const result = [...ctx.data].map((item, i2) => {
      return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i2));
    });
    return ParseStatus.mergeArray(status, result);
  }
  get element() {
    return this._def.type;
  }
  min(minLength, message) {
    return new _ZodArray({
      ...this._def,
      minLength: { value: minLength, message: errorUtil.toString(message) }
    });
  }
  max(maxLength, message) {
    return new _ZodArray({
      ...this._def,
      maxLength: { value: maxLength, message: errorUtil.toString(message) }
    });
  }
  length(len, message) {
    return new _ZodArray({
      ...this._def,
      exactLength: { value: len, message: errorUtil.toString(message) }
    });
  }
  nonempty(message) {
    return this.min(1, message);
  }
};
ZodArray2.create = (schema, params) => {
  return new ZodArray2({
    type: schema,
    minLength: null,
    maxLength: null,
    exactLength: null,
    typeName: ZodFirstPartyTypeKind2.ZodArray,
    ...processCreateParams(params)
  });
};
function deepPartialify(schema) {
  if (schema instanceof ZodObject2) {
    const newShape = {};
    for (const key in schema.shape) {
      const fieldSchema = schema.shape[key];
      newShape[key] = ZodOptional2.create(deepPartialify(fieldSchema));
    }
    return new ZodObject2({
      ...schema._def,
      shape: () => newShape
    });
  } else if (schema instanceof ZodArray2) {
    return new ZodArray2({
      ...schema._def,
      type: deepPartialify(schema.element)
    });
  } else if (schema instanceof ZodOptional2) {
    return ZodOptional2.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodNullable2) {
    return ZodNullable2.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodTuple2) {
    return ZodTuple2.create(schema.items.map((item) => deepPartialify(item)));
  } else {
    return schema;
  }
}
var ZodObject2 = class _ZodObject extends ZodType2 {
  constructor() {
    super(...arguments);
    this._cached = null;
    this.nonstrict = this.passthrough;
    this.augment = this.extend;
  }
  _getCached() {
    if (this._cached !== null)
      return this._cached;
    const shape = this._def.shape();
    const keys = util.objectKeys(shape);
    this._cached = { shape, keys };
    return this._cached;
  }
  _parse(input) {
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.object) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType.object,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const { status, ctx } = this._processInputParams(input);
    const { shape, keys: shapeKeys } = this._getCached();
    const extraKeys = [];
    if (!(this._def.catchall instanceof ZodNever2 && this._def.unknownKeys === "strip")) {
      for (const key in ctx.data) {
        if (!shapeKeys.includes(key)) {
          extraKeys.push(key);
        }
      }
    }
    const pairs = [];
    for (const key of shapeKeys) {
      const keyValidator = shape[key];
      const value = ctx.data[key];
      pairs.push({
        key: { status: "valid", value: key },
        value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (this._def.catchall instanceof ZodNever2) {
      const unknownKeys = this._def.unknownKeys;
      if (unknownKeys === "passthrough") {
        for (const key of extraKeys) {
          pairs.push({
            key: { status: "valid", value: key },
            value: { status: "valid", value: ctx.data[key] }
          });
        }
      } else if (unknownKeys === "strict") {
        if (extraKeys.length > 0) {
          addIssueToContext(ctx, {
            code: ZodIssueCode2.unrecognized_keys,
            keys: extraKeys
          });
          status.dirty();
        }
      } else if (unknownKeys === "strip") {
      } else {
        throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
      }
    } else {
      const catchall = this._def.catchall;
      for (const key of extraKeys) {
        const value = ctx.data[key];
        pairs.push({
          key: { status: "valid", value: key },
          value: catchall._parse(
            new ParseInputLazyPath(ctx, value, ctx.path, key)
            //, ctx.child(key), value, getParsedType(value)
          ),
          alwaysSet: key in ctx.data
        });
      }
    }
    if (ctx.common.async) {
      return Promise.resolve().then(async () => {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value,
            alwaysSet: pair.alwaysSet
          });
        }
        return syncPairs;
      }).then((syncPairs) => {
        return ParseStatus.mergeObjectSync(status, syncPairs);
      });
    } else {
      return ParseStatus.mergeObjectSync(status, pairs);
    }
  }
  get shape() {
    return this._def.shape();
  }
  strict(message) {
    errorUtil.errToObj;
    return new _ZodObject({
      ...this._def,
      unknownKeys: "strict",
      ...message !== void 0 ? {
        errorMap: (issue2, ctx) => {
          const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError;
          if (issue2.code === "unrecognized_keys")
            return {
              message: errorUtil.errToObj(message).message ?? defaultError
            };
          return {
            message: defaultError
          };
        }
      } : {}
    });
  }
  strip() {
    return new _ZodObject({
      ...this._def,
      unknownKeys: "strip"
    });
  }
  passthrough() {
    return new _ZodObject({
      ...this._def,
      unknownKeys: "passthrough"
    });
  }
  // const AugmentFactory =
  //   <Def extends ZodObjectDef>(def: Def) =>
  //   <Augmentation extends ZodRawShape>(
  //     augmentation: Augmentation
  //   ): ZodObject<
  //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
  //     Def["unknownKeys"],
  //     Def["catchall"]
  //   > => {
  //     return new ZodObject({
  //       ...def,
  //       shape: () => ({
  //         ...def.shape(),
  //         ...augmentation,
  //       }),
  //     }) as any;
  //   };
  extend(augmentation) {
    return new _ZodObject({
      ...this._def,
      shape: () => ({
        ...this._def.shape(),
        ...augmentation
      })
    });
  }
  /**
   * Prior to zod@1.0.12 there was a bug in the
   * inferred type of merged objects. Please
   * upgrade if you are experiencing issues.
   */
  merge(merging) {
    const merged = new _ZodObject({
      unknownKeys: merging._def.unknownKeys,
      catchall: merging._def.catchall,
      shape: () => ({
        ...this._def.shape(),
        ...merging._def.shape()
      }),
      typeName: ZodFirstPartyTypeKind2.ZodObject
    });
    return merged;
  }
  // merge<
  //   Incoming extends AnyZodObject,
  //   Augmentation extends Incoming["shape"],
  //   NewOutput extends {
  //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  //       ? Augmentation[k]["_output"]
  //       : k extends keyof Output
  //       ? Output[k]
  //       : never;
  //   },
  //   NewInput extends {
  //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  //       ? Augmentation[k]["_input"]
  //       : k extends keyof Input
  //       ? Input[k]
  //       : never;
  //   }
  // >(
  //   merging: Incoming
  // ): ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"],
  //   NewOutput,
  //   NewInput
  // > {
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  setKey(key, schema) {
    return this.augment({ [key]: schema });
  }
  // merge<Incoming extends AnyZodObject>(
  //   merging: Incoming
  // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
  // ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"]
  // > {
  //   // const mergedShape = objectUtil.mergeShapes(
  //   //   this._def.shape(),
  //   //   merging._def.shape()
  //   // );
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  catchall(index) {
    return new _ZodObject({
      ...this._def,
      catchall: index
    });
  }
  pick(mask) {
    const shape = {};
    for (const key of util.objectKeys(mask)) {
      if (mask[key] && this.shape[key]) {
        shape[key] = this.shape[key];
      }
    }
    return new _ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  omit(mask) {
    const shape = {};
    for (const key of util.objectKeys(this.shape)) {
      if (!mask[key]) {
        shape[key] = this.shape[key];
      }
    }
    return new _ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  /**
   * @deprecated
   */
  deepPartial() {
    return deepPartialify(this);
  }
  partial(mask) {
    const newShape = {};
    for (const key of util.objectKeys(this.shape)) {
      const fieldSchema = this.shape[key];
      if (mask && !mask[key]) {
        newShape[key] = fieldSchema;
      } else {
        newShape[key] = fieldSchema.optional();
      }
    }
    return new _ZodObject({
      ...this._def,
      shape: () => newShape
    });
  }
  required(mask) {
    const newShape = {};
    for (const key of util.objectKeys(this.shape)) {
      if (mask && !mask[key]) {
        newShape[key] = this.shape[key];
      } else {
        const fieldSchema = this.shape[key];
        let newField = fieldSchema;
        while (newField instanceof ZodOptional2) {
          newField = newField._def.innerType;
        }
        newShape[key] = newField;
      }
    }
    return new _ZodObject({
      ...this._def,
      shape: () => newShape
    });
  }
  keyof() {
    return createZodEnum(util.objectKeys(this.shape));
  }
};
ZodObject2.create = (shape, params) => {
  return new ZodObject2({
    shape: () => shape,
    unknownKeys: "strip",
    catchall: ZodNever2.create(),
    typeName: ZodFirstPartyTypeKind2.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject2.strictCreate = (shape, params) => {
  return new ZodObject2({
    shape: () => shape,
    unknownKeys: "strict",
    catchall: ZodNever2.create(),
    typeName: ZodFirstPartyTypeKind2.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject2.lazycreate = (shape, params) => {
  return new ZodObject2({
    shape,
    unknownKeys: "strip",
    catchall: ZodNever2.create(),
    typeName: ZodFirstPartyTypeKind2.ZodObject,
    ...processCreateParams(params)
  });
};
var ZodUnion2 = class extends ZodType2 {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const options = this._def.options;
    function handleResults(results) {
      for (const result of results) {
        if (result.result.status === "valid") {
          return result.result;
        }
      }
      for (const result of results) {
        if (result.result.status === "dirty") {
          ctx.common.issues.push(...result.ctx.common.issues);
          return result.result;
        }
      }
      const unionErrors = results.map((result) => new ZodError2(result.ctx.common.issues));
      addIssueToContext(ctx, {
        code: ZodIssueCode2.invalid_union,
        unionErrors
      });
      return INVALID;
    }
    if (ctx.common.async) {
      return Promise.all(options.map(async (option) => {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        return {
          result: await option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: childCtx
          }),
          ctx: childCtx
        };
      })).then(handleResults);
    } else {
      let dirty = void 0;
      const issues = [];
      for (const option of options) {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        const result = option._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: childCtx
        });
        if (result.status === "valid") {
          return result;
        } else if (result.status === "dirty" && !dirty) {
          dirty = { result, ctx: childCtx };
        }
        if (childCtx.common.issues.length) {
          issues.push(childCtx.common.issues);
        }
      }
      if (dirty) {
        ctx.common.issues.push(...dirty.ctx.common.issues);
        return dirty.result;
      }
      const unionErrors = issues.map((issues2) => new ZodError2(issues2));
      addIssueToContext(ctx, {
        code: ZodIssueCode2.invalid_union,
        unionErrors
      });
      return INVALID;
    }
  }
  get options() {
    return this._def.options;
  }
};
ZodUnion2.create = (types3, params) => {
  return new ZodUnion2({
    options: types3,
    typeName: ZodFirstPartyTypeKind2.ZodUnion,
    ...processCreateParams(params)
  });
};
var getDiscriminator = (type) => {
  if (type instanceof ZodLazy2) {
    return getDiscriminator(type.schema);
  } else if (type instanceof ZodEffects) {
    return getDiscriminator(type.innerType());
  } else if (type instanceof ZodLiteral2) {
    return [type.value];
  } else if (type instanceof ZodEnum2) {
    return type.options;
  } else if (type instanceof ZodNativeEnum) {
    return util.objectValues(type.enum);
  } else if (type instanceof ZodDefault2) {
    return getDiscriminator(type._def.innerType);
  } else if (type instanceof ZodUndefined2) {
    return [void 0];
  } else if (type instanceof ZodNull2) {
    return [null];
  } else if (type instanceof ZodOptional2) {
    return [void 0, ...getDiscriminator(type.unwrap())];
  } else if (type instanceof ZodNullable2) {
    return [null, ...getDiscriminator(type.unwrap())];
  } else if (type instanceof ZodBranded) {
    return getDiscriminator(type.unwrap());
  } else if (type instanceof ZodReadonly2) {
    return getDiscriminator(type.unwrap());
  } else if (type instanceof ZodCatch2) {
    return getDiscriminator(type._def.innerType);
  } else {
    return [];
  }
};
var ZodDiscriminatedUnion2 = class _ZodDiscriminatedUnion extends ZodType2 {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const discriminator = this.discriminator;
    const discriminatorValue = ctx.data[discriminator];
    const option = this.optionsMap.get(discriminatorValue);
    if (!option) {
      addIssueToContext(ctx, {
        code: ZodIssueCode2.invalid_union_discriminator,
        options: Array.from(this.optionsMap.keys()),
        path: [discriminator]
      });
      return INVALID;
    }
    if (ctx.common.async) {
      return option._parseAsync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    } else {
      return option._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    }
  }
  get discriminator() {
    return this._def.discriminator;
  }
  get options() {
    return this._def.options;
  }
  get optionsMap() {
    return this._def.optionsMap;
  }
  /**
   * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
   * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
   * have a different value for each object in the union.
   * @param discriminator the name of the discriminator property
   * @param types an array of object schemas
   * @param params
   */
  static create(discriminator, options, params) {
    const optionsMap = /* @__PURE__ */ new Map();
    for (const type of options) {
      const discriminatorValues = getDiscriminator(type.shape[discriminator]);
      if (!discriminatorValues.length) {
        throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
      }
      for (const value of discriminatorValues) {
        if (optionsMap.has(value)) {
          throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
        }
        optionsMap.set(value, type);
      }
    }
    return new _ZodDiscriminatedUnion({
      typeName: ZodFirstPartyTypeKind2.ZodDiscriminatedUnion,
      discriminator,
      options,
      optionsMap,
      ...processCreateParams(params)
    });
  }
};
function mergeValues2(a, b) {
  const aType = getParsedType2(a);
  const bType = getParsedType2(b);
  if (a === b) {
    return { valid: true, data: a };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b);
    const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a, ...b };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues2(a[key], b[key]);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
    if (a.length !== b.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index = 0; index < a.length; index++) {
      const itemA = a[index];
      const itemB = b[index];
      const sharedValue = mergeValues2(itemA, itemB);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
    return { valid: true, data: a };
  } else {
    return { valid: false };
  }
}
var ZodIntersection2 = class extends ZodType2 {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const handleParsed = (parsedLeft, parsedRight) => {
      if (isAborted(parsedLeft) || isAborted(parsedRight)) {
        return INVALID;
      }
      const merged = mergeValues2(parsedLeft.value, parsedRight.value);
      if (!merged.valid) {
        addIssueToContext(ctx, {
          code: ZodIssueCode2.invalid_intersection_types
        });
        return INVALID;
      }
      if (isDirty(parsedLeft) || isDirty(parsedRight)) {
        status.dirty();
      }
      return { status: status.value, value: merged.data };
    };
    if (ctx.common.async) {
      return Promise.all([
        this._def.left._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        }),
        this._def.right._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        })
      ]).then(([left, right]) => handleParsed(left, right));
    } else {
      return handleParsed(this._def.left._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }), this._def.right._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }));
    }
  }
};
ZodIntersection2.create = (left, right, params) => {
  return new ZodIntersection2({
    left,
    right,
    typeName: ZodFirstPartyTypeKind2.ZodIntersection,
    ...processCreateParams(params)
  });
};
var ZodTuple2 = class _ZodTuple extends ZodType2 {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (ctx.data.length < this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode2.too_small,
        minimum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      return INVALID;
    }
    const rest = this._def.rest;
    if (!rest && ctx.data.length > this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode2.too_big,
        maximum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      status.dirty();
    }
    const items = [...ctx.data].map((item, itemIndex) => {
      const schema = this._def.items[itemIndex] || this._def.rest;
      if (!schema)
        return null;
      return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
    }).filter((x2) => !!x2);
    if (ctx.common.async) {
      return Promise.all(items).then((results) => {
        return ParseStatus.mergeArray(status, results);
      });
    } else {
      return ParseStatus.mergeArray(status, items);
    }
  }
  get items() {
    return this._def.items;
  }
  rest(rest) {
    return new _ZodTuple({
      ...this._def,
      rest
    });
  }
};
ZodTuple2.create = (schemas, params) => {
  if (!Array.isArray(schemas)) {
    throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  }
  return new ZodTuple2({
    items: schemas,
    typeName: ZodFirstPartyTypeKind2.ZodTuple,
    rest: null,
    ...processCreateParams(params)
  });
};
var ZodRecord2 = class _ZodRecord extends ZodType2 {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const pairs = [];
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    for (const key in ctx.data) {
      pairs.push({
        key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
        value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (ctx.common.async) {
      return ParseStatus.mergeObjectAsync(status, pairs);
    } else {
      return ParseStatus.mergeObjectSync(status, pairs);
    }
  }
  get element() {
    return this._def.valueType;
  }
  static create(first, second, third) {
    if (second instanceof ZodType2) {
      return new _ZodRecord({
        keyType: first,
        valueType: second,
        typeName: ZodFirstPartyTypeKind2.ZodRecord,
        ...processCreateParams(third)
      });
    }
    return new _ZodRecord({
      keyType: ZodString2.create(),
      valueType: first,
      typeName: ZodFirstPartyTypeKind2.ZodRecord,
      ...processCreateParams(second)
    });
  }
};
var ZodMap2 = class extends ZodType2 {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.map) {
      addIssueToContext(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType.map,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    const pairs = [...ctx.data.entries()].map(([key, value], index) => {
      return {
        key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
        value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
      };
    });
    if (ctx.common.async) {
      const finalMap = /* @__PURE__ */ new Map();
      return Promise.resolve().then(async () => {
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          if (key.status === "aborted" || value.status === "aborted") {
            return INVALID;
          }
          if (key.status === "dirty" || value.status === "dirty") {
            status.dirty();
          }
          finalMap.set(key.value, value.value);
        }
        return { status: status.value, value: finalMap };
      });
    } else {
      const finalMap = /* @__PURE__ */ new Map();
      for (const pair of pairs) {
        const key = pair.key;
        const value = pair.value;
        if (key.status === "aborted" || value.status === "aborted") {
          return INVALID;
        }
        if (key.status === "dirty" || value.status === "dirty") {
          status.dirty();
        }
        finalMap.set(key.value, value.value);
      }
      return { status: status.value, value: finalMap };
    }
  }
};
ZodMap2.create = (keyType, valueType, params) => {
  return new ZodMap2({
    valueType,
    keyType,
    typeName: ZodFirstPartyTypeKind2.ZodMap,
    ...processCreateParams(params)
  });
};
var ZodSet2 = class _ZodSet extends ZodType2 {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.set) {
      addIssueToContext(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType.set,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const def = this._def;
    if (def.minSize !== null) {
      if (ctx.data.size < def.minSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode2.too_small,
          minimum: def.minSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.minSize.message
        });
        status.dirty();
      }
    }
    if (def.maxSize !== null) {
      if (ctx.data.size > def.maxSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode2.too_big,
          maximum: def.maxSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.maxSize.message
        });
        status.dirty();
      }
    }
    const valueType = this._def.valueType;
    function finalizeSet(elements2) {
      const parsedSet = /* @__PURE__ */ new Set();
      for (const element of elements2) {
        if (element.status === "aborted")
          return INVALID;
        if (element.status === "dirty")
          status.dirty();
        parsedSet.add(element.value);
      }
      return { status: status.value, value: parsedSet };
    }
    const elements = [...ctx.data.values()].map((item, i2) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i2)));
    if (ctx.common.async) {
      return Promise.all(elements).then((elements2) => finalizeSet(elements2));
    } else {
      return finalizeSet(elements);
    }
  }
  min(minSize, message) {
    return new _ZodSet({
      ...this._def,
      minSize: { value: minSize, message: errorUtil.toString(message) }
    });
  }
  max(maxSize, message) {
    return new _ZodSet({
      ...this._def,
      maxSize: { value: maxSize, message: errorUtil.toString(message) }
    });
  }
  size(size, message) {
    return this.min(size, message).max(size, message);
  }
  nonempty(message) {
    return this.min(1, message);
  }
};
ZodSet2.create = (valueType, params) => {
  return new ZodSet2({
    valueType,
    minSize: null,
    maxSize: null,
    typeName: ZodFirstPartyTypeKind2.ZodSet,
    ...processCreateParams(params)
  });
};
var ZodFunction2 = class _ZodFunction extends ZodType2 {
  constructor() {
    super(...arguments);
    this.validate = this.implement;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.function) {
      addIssueToContext(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType.function,
        received: ctx.parsedType
      });
      return INVALID;
    }
    function makeArgsIssue(args, error51) {
      return makeIssue({
        data: args,
        path: ctx.path,
        errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x2) => !!x2),
        issueData: {
          code: ZodIssueCode2.invalid_arguments,
          argumentsError: error51
        }
      });
    }
    function makeReturnsIssue(returns, error51) {
      return makeIssue({
        data: returns,
        path: ctx.path,
        errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x2) => !!x2),
        issueData: {
          code: ZodIssueCode2.invalid_return_type,
          returnTypeError: error51
        }
      });
    }
    const params = { errorMap: ctx.common.contextualErrorMap };
    const fn = ctx.data;
    if (this._def.returns instanceof ZodPromise2) {
      const me = this;
      return OK(async function(...args) {
        const error51 = new ZodError2([]);
        const parsedArgs = await me._def.args.parseAsync(args, params).catch((e2) => {
          error51.addIssue(makeArgsIssue(args, e2));
          throw error51;
        });
        const result = await Reflect.apply(fn, this, parsedArgs);
        const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e2) => {
          error51.addIssue(makeReturnsIssue(result, e2));
          throw error51;
        });
        return parsedReturns;
      });
    } else {
      const me = this;
      return OK(function(...args) {
        const parsedArgs = me._def.args.safeParse(args, params);
        if (!parsedArgs.success) {
          throw new ZodError2([makeArgsIssue(args, parsedArgs.error)]);
        }
        const result = Reflect.apply(fn, this, parsedArgs.data);
        const parsedReturns = me._def.returns.safeParse(result, params);
        if (!parsedReturns.success) {
          throw new ZodError2([makeReturnsIssue(result, parsedReturns.error)]);
        }
        return parsedReturns.data;
      });
    }
  }
  parameters() {
    return this._def.args;
  }
  returnType() {
    return this._def.returns;
  }
  args(...items) {
    return new _ZodFunction({
      ...this._def,
      args: ZodTuple2.create(items).rest(ZodUnknown2.create())
    });
  }
  returns(returnType) {
    return new _ZodFunction({
      ...this._def,
      returns: returnType
    });
  }
  implement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  strictImplement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  static create(args, returns, params) {
    return new _ZodFunction({
      args: args ? args : ZodTuple2.create([]).rest(ZodUnknown2.create()),
      returns: returns || ZodUnknown2.create(),
      typeName: ZodFirstPartyTypeKind2.ZodFunction,
      ...processCreateParams(params)
    });
  }
};
var ZodLazy2 = class extends ZodType2 {
  get schema() {
    return this._def.getter();
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const lazySchema = this._def.getter();
    return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
  }
};
ZodLazy2.create = (getter, params) => {
  return new ZodLazy2({
    getter,
    typeName: ZodFirstPartyTypeKind2.ZodLazy,
    ...processCreateParams(params)
  });
};
var ZodLiteral2 = class extends ZodType2 {
  _parse(input) {
    if (input.data !== this._def.value) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode2.invalid_literal,
        expected: this._def.value
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
  get value() {
    return this._def.value;
  }
};
ZodLiteral2.create = (value, params) => {
  return new ZodLiteral2({
    value,
    typeName: ZodFirstPartyTypeKind2.ZodLiteral,
    ...processCreateParams(params)
  });
};
function createZodEnum(values, params) {
  return new ZodEnum2({
    values,
    typeName: ZodFirstPartyTypeKind2.ZodEnum,
    ...processCreateParams(params)
  });
}
var ZodEnum2 = class _ZodEnum extends ZodType2 {
  _parse(input) {
    if (typeof input.data !== "string") {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode2.invalid_type
      });
      return INVALID;
    }
    if (!this._cache) {
      this._cache = new Set(this._def.values);
    }
    if (!this._cache.has(input.data)) {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode2.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input.data);
  }
  get options() {
    return this._def.values;
  }
  get enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Values() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  extract(values, newDef = this._def) {
    return _ZodEnum.create(values, {
      ...this._def,
      ...newDef
    });
  }
  exclude(values, newDef = this._def) {
    return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
      ...this._def,
      ...newDef
    });
  }
};
ZodEnum2.create = createZodEnum;
var ZodNativeEnum = class extends ZodType2 {
  _parse(input) {
    const nativeEnumValues = util.getValidEnumValues(this._def.values);
    const ctx = this._getOrReturnCtx(input);
    if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode2.invalid_type
      });
      return INVALID;
    }
    if (!this._cache) {
      this._cache = new Set(util.getValidEnumValues(this._def.values));
    }
    if (!this._cache.has(input.data)) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode2.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input.data);
  }
  get enum() {
    return this._def.values;
  }
};
ZodNativeEnum.create = (values, params) => {
  return new ZodNativeEnum({
    values,
    typeName: ZodFirstPartyTypeKind2.ZodNativeEnum,
    ...processCreateParams(params)
  });
};
var ZodPromise2 = class extends ZodType2 {
  unwrap() {
    return this._def.type;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
      addIssueToContext(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType.promise,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
    return OK(promisified.then((data) => {
      return this._def.type.parseAsync(data, {
        path: ctx.path,
        errorMap: ctx.common.contextualErrorMap
      });
    }));
  }
};
ZodPromise2.create = (schema, params) => {
  return new ZodPromise2({
    type: schema,
    typeName: ZodFirstPartyTypeKind2.ZodPromise,
    ...processCreateParams(params)
  });
};
var ZodEffects = class extends ZodType2 {
  innerType() {
    return this._def.schema;
  }
  sourceType() {
    return this._def.schema._def.typeName === ZodFirstPartyTypeKind2.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const effect = this._def.effect || null;
    const checkCtx = {
      addIssue: (arg) => {
        addIssueToContext(ctx, arg);
        if (arg.fatal) {
          status.abort();
        } else {
          status.dirty();
        }
      },
      get path() {
        return ctx.path;
      }
    };
    checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
    if (effect.type === "preprocess") {
      const processed = effect.transform(ctx.data, checkCtx);
      if (ctx.common.async) {
        return Promise.resolve(processed).then(async (processed2) => {
          if (status.value === "aborted")
            return INVALID;
          const result = await this._def.schema._parseAsync({
            data: processed2,
            path: ctx.path,
            parent: ctx
          });
          if (result.status === "aborted")
            return INVALID;
          if (result.status === "dirty")
            return DIRTY(result.value);
          if (status.value === "dirty")
            return DIRTY(result.value);
          return result;
        });
      } else {
        if (status.value === "aborted")
          return INVALID;
        const result = this._def.schema._parseSync({
          data: processed,
          path: ctx.path,
          parent: ctx
        });
        if (result.status === "aborted")
          return INVALID;
        if (result.status === "dirty")
          return DIRTY(result.value);
        if (status.value === "dirty")
          return DIRTY(result.value);
        return result;
      }
    }
    if (effect.type === "refinement") {
      const executeRefinement = (acc) => {
        const result = effect.refinement(acc, checkCtx);
        if (ctx.common.async) {
          return Promise.resolve(result);
        }
        if (result instanceof Promise) {
          throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
        }
        return acc;
      };
      if (ctx.common.async === false) {
        const inner = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inner.status === "aborted")
          return INVALID;
        if (inner.status === "dirty")
          status.dirty();
        executeRefinement(inner.value);
        return { status: status.value, value: inner.value };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
          if (inner.status === "aborted")
            return INVALID;
          if (inner.status === "dirty")
            status.dirty();
          return executeRefinement(inner.value).then(() => {
            return { status: status.value, value: inner.value };
          });
        });
      }
    }
    if (effect.type === "transform") {
      if (ctx.common.async === false) {
        const base = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (!isValid(base))
          return INVALID;
        const result = effect.transform(base.value, checkCtx);
        if (result instanceof Promise) {
          throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
        }
        return { status: status.value, value: result };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
          if (!isValid(base))
            return INVALID;
          return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
            status: status.value,
            value: result
          }));
        });
      }
    }
    util.assertNever(effect);
  }
};
ZodEffects.create = (schema, effect, params) => {
  return new ZodEffects({
    schema,
    typeName: ZodFirstPartyTypeKind2.ZodEffects,
    effect,
    ...processCreateParams(params)
  });
};
ZodEffects.createWithPreprocess = (preprocess2, schema, params) => {
  return new ZodEffects({
    schema,
    effect: { type: "preprocess", transform: preprocess2 },
    typeName: ZodFirstPartyTypeKind2.ZodEffects,
    ...processCreateParams(params)
  });
};
var ZodOptional2 = class extends ZodType2 {
  _parse(input) {
    const parsedType2 = this._getType(input);
    if (parsedType2 === ZodParsedType.undefined) {
      return OK(void 0);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodOptional2.create = (type, params) => {
  return new ZodOptional2({
    innerType: type,
    typeName: ZodFirstPartyTypeKind2.ZodOptional,
    ...processCreateParams(params)
  });
};
var ZodNullable2 = class extends ZodType2 {
  _parse(input) {
    const parsedType2 = this._getType(input);
    if (parsedType2 === ZodParsedType.null) {
      return OK(null);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodNullable2.create = (type, params) => {
  return new ZodNullable2({
    innerType: type,
    typeName: ZodFirstPartyTypeKind2.ZodNullable,
    ...processCreateParams(params)
  });
};
var ZodDefault2 = class extends ZodType2 {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    let data = ctx.data;
    if (ctx.parsedType === ZodParsedType.undefined) {
      data = this._def.defaultValue();
    }
    return this._def.innerType._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  removeDefault() {
    return this._def.innerType;
  }
};
ZodDefault2.create = (type, params) => {
  return new ZodDefault2({
    innerType: type,
    typeName: ZodFirstPartyTypeKind2.ZodDefault,
    defaultValue: typeof params.default === "function" ? params.default : () => params.default,
    ...processCreateParams(params)
  });
};
var ZodCatch2 = class extends ZodType2 {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const newCtx = {
      ...ctx,
      common: {
        ...ctx.common,
        issues: []
      }
    };
    const result = this._def.innerType._parse({
      data: newCtx.data,
      path: newCtx.path,
      parent: {
        ...newCtx
      }
    });
    if (isAsync(result)) {
      return result.then((result2) => {
        return {
          status: "valid",
          value: result2.status === "valid" ? result2.value : this._def.catchValue({
            get error() {
              return new ZodError2(newCtx.common.issues);
            },
            input: newCtx.data
          })
        };
      });
    } else {
      return {
        status: "valid",
        value: result.status === "valid" ? result.value : this._def.catchValue({
          get error() {
            return new ZodError2(newCtx.common.issues);
          },
          input: newCtx.data
        })
      };
    }
  }
  removeCatch() {
    return this._def.innerType;
  }
};
ZodCatch2.create = (type, params) => {
  return new ZodCatch2({
    innerType: type,
    typeName: ZodFirstPartyTypeKind2.ZodCatch,
    catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
    ...processCreateParams(params)
  });
};
var ZodNaN2 = class extends ZodType2 {
  _parse(input) {
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.nan) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType.nan,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
};
ZodNaN2.create = (params) => {
  return new ZodNaN2({
    typeName: ZodFirstPartyTypeKind2.ZodNaN,
    ...processCreateParams(params)
  });
};
var ZodBranded = class extends ZodType2 {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const data = ctx.data;
    return this._def.type._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  unwrap() {
    return this._def.type;
  }
};
var ZodPipeline = class _ZodPipeline extends ZodType2 {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.common.async) {
      const handleAsync = async () => {
        const inResult = await this._def.in._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inResult.status === "aborted")
          return INVALID;
        if (inResult.status === "dirty") {
          status.dirty();
          return DIRTY(inResult.value);
        } else {
          return this._def.out._parseAsync({
            data: inResult.value,
            path: ctx.path,
            parent: ctx
          });
        }
      };
      return handleAsync();
    } else {
      const inResult = this._def.in._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
      if (inResult.status === "aborted")
        return INVALID;
      if (inResult.status === "dirty") {
        status.dirty();
        return {
          status: "dirty",
          value: inResult.value
        };
      } else {
        return this._def.out._parseSync({
          data: inResult.value,
          path: ctx.path,
          parent: ctx
        });
      }
    }
  }
  static create(a, b) {
    return new _ZodPipeline({
      in: a,
      out: b,
      typeName: ZodFirstPartyTypeKind2.ZodPipeline
    });
  }
};
var ZodReadonly2 = class extends ZodType2 {
  _parse(input) {
    const result = this._def.innerType._parse(input);
    const freeze = (data) => {
      if (isValid(data)) {
        data.value = Object.freeze(data.value);
      }
      return data;
    };
    return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodReadonly2.create = (type, params) => {
  return new ZodReadonly2({
    innerType: type,
    typeName: ZodFirstPartyTypeKind2.ZodReadonly,
    ...processCreateParams(params)
  });
};
var late = {
  object: ZodObject2.lazycreate
};
var ZodFirstPartyTypeKind2;
(function(ZodFirstPartyTypeKind3) {
  ZodFirstPartyTypeKind3["ZodString"] = "ZodString";
  ZodFirstPartyTypeKind3["ZodNumber"] = "ZodNumber";
  ZodFirstPartyTypeKind3["ZodNaN"] = "ZodNaN";
  ZodFirstPartyTypeKind3["ZodBigInt"] = "ZodBigInt";
  ZodFirstPartyTypeKind3["ZodBoolean"] = "ZodBoolean";
  ZodFirstPartyTypeKind3["ZodDate"] = "ZodDate";
  ZodFirstPartyTypeKind3["ZodSymbol"] = "ZodSymbol";
  ZodFirstPartyTypeKind3["ZodUndefined"] = "ZodUndefined";
  ZodFirstPartyTypeKind3["ZodNull"] = "ZodNull";
  ZodFirstPartyTypeKind3["ZodAny"] = "ZodAny";
  ZodFirstPartyTypeKind3["ZodUnknown"] = "ZodUnknown";
  ZodFirstPartyTypeKind3["ZodNever"] = "ZodNever";
  ZodFirstPartyTypeKind3["ZodVoid"] = "ZodVoid";
  ZodFirstPartyTypeKind3["ZodArray"] = "ZodArray";
  ZodFirstPartyTypeKind3["ZodObject"] = "ZodObject";
  ZodFirstPartyTypeKind3["ZodUnion"] = "ZodUnion";
  ZodFirstPartyTypeKind3["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  ZodFirstPartyTypeKind3["ZodIntersection"] = "ZodIntersection";
  ZodFirstPartyTypeKind3["ZodTuple"] = "ZodTuple";
  ZodFirstPartyTypeKind3["ZodRecord"] = "ZodRecord";
  ZodFirstPartyTypeKind3["ZodMap"] = "ZodMap";
  ZodFirstPartyTypeKind3["ZodSet"] = "ZodSet";
  ZodFirstPartyTypeKind3["ZodFunction"] = "ZodFunction";
  ZodFirstPartyTypeKind3["ZodLazy"] = "ZodLazy";
  ZodFirstPartyTypeKind3["ZodLiteral"] = "ZodLiteral";
  ZodFirstPartyTypeKind3["ZodEnum"] = "ZodEnum";
  ZodFirstPartyTypeKind3["ZodEffects"] = "ZodEffects";
  ZodFirstPartyTypeKind3["ZodNativeEnum"] = "ZodNativeEnum";
  ZodFirstPartyTypeKind3["ZodOptional"] = "ZodOptional";
  ZodFirstPartyTypeKind3["ZodNullable"] = "ZodNullable";
  ZodFirstPartyTypeKind3["ZodDefault"] = "ZodDefault";
  ZodFirstPartyTypeKind3["ZodCatch"] = "ZodCatch";
  ZodFirstPartyTypeKind3["ZodPromise"] = "ZodPromise";
  ZodFirstPartyTypeKind3["ZodBranded"] = "ZodBranded";
  ZodFirstPartyTypeKind3["ZodPipeline"] = "ZodPipeline";
  ZodFirstPartyTypeKind3["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind2 || (ZodFirstPartyTypeKind2 = {}));
var stringType = ZodString2.create;
var numberType = ZodNumber2.create;
var nanType = ZodNaN2.create;
var bigIntType = ZodBigInt2.create;
var booleanType = ZodBoolean2.create;
var dateType = ZodDate2.create;
var symbolType = ZodSymbol2.create;
var undefinedType = ZodUndefined2.create;
var nullType = ZodNull2.create;
var anyType = ZodAny2.create;
var unknownType = ZodUnknown2.create;
var neverType = ZodNever2.create;
var voidType = ZodVoid2.create;
var arrayType = ZodArray2.create;
var objectType = ZodObject2.create;
var strictObjectType = ZodObject2.strictCreate;
var unionType = ZodUnion2.create;
var discriminatedUnionType = ZodDiscriminatedUnion2.create;
var intersectionType = ZodIntersection2.create;
var tupleType = ZodTuple2.create;
var recordType = ZodRecord2.create;
var mapType = ZodMap2.create;
var setType = ZodSet2.create;
var functionType = ZodFunction2.create;
var lazyType = ZodLazy2.create;
var literalType = ZodLiteral2.create;
var enumType = ZodEnum2.create;
var nativeEnumType = ZodNativeEnum.create;
var promiseType = ZodPromise2.create;
var effectsType = ZodEffects.create;
var optionalType = ZodOptional2.create;
var nullableType = ZodNullable2.create;
var preprocessType = ZodEffects.createWithPreprocess;
var pipelineType = ZodPipeline.create;

// node_modules/zod/v4/mini/schemas.js
var ZodMiniType = /* @__PURE__ */ $constructor("ZodMiniType", (inst, def) => {
  if (!inst._zod)
    throw new Error("Uninitialized schema in ZodMiniType.");
  $ZodType.init(inst, def);
  inst.def = def;
  inst.type = def.type;
  inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });
  inst.safeParse = (data, params) => safeParse(inst, data, params);
  inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
  inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
  inst.check = (...checks) => {
    return inst.clone({
      ...def,
      checks: [
        ...def.checks ?? [],
        ...checks.map((ch) => typeof ch === "function" ? {
          _zod: { check: ch, def: { check: "custom" }, onattach: [] }
        } : ch)
      ]
    }, { parent: true });
  };
  inst.with = inst.check;
  inst.clone = (_def, params) => clone(inst, _def, params);
  inst.brand = () => inst;
  inst.register = ((reg, meta3) => {
    reg.add(inst, meta3);
    return inst;
  });
  inst.apply = (fn) => fn(inst);
});
var ZodMiniObject = /* @__PURE__ */ $constructor("ZodMiniObject", (inst, def) => {
  $ZodObject.init(inst, def);
  ZodMiniType.init(inst, def);
  defineLazy(inst, "shape", () => def.shape);
});
// @__NO_SIDE_EFFECTS__
function object2(shape, params) {
  const def = {
    type: "object",
    shape: shape ?? {},
    ...normalizeParams(params)
  };
  return new ZodMiniObject(def);
}

// node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
function isZ4Schema(s2) {
  const schema = s2;
  return !!schema._zod;
}
function objectFromShape(shape) {
  const values = Object.values(shape);
  if (values.length === 0)
    return object2({});
  const allV4 = values.every(isZ4Schema);
  const allV3 = values.every((s2) => !isZ4Schema(s2));
  if (allV4)
    return object2(shape);
  if (allV3)
    return objectType(shape);
  throw new Error("Mixed Zod versions detected in object shape.");
}
function safeParse3(schema, data) {
  if (isZ4Schema(schema)) {
    const result2 = safeParse(schema, data);
    return result2;
  }
  const v3Schema = schema;
  const result = v3Schema.safeParse(data);
  return result;
}
async function safeParseAsync3(schema, data) {
  if (isZ4Schema(schema)) {
    const result2 = await safeParseAsync(schema, data);
    return result2;
  }
  const v3Schema = schema;
  const result = await v3Schema.safeParseAsync(data);
  return result;
}
function getObjectShape(schema) {
  if (!schema)
    return void 0;
  let rawShape;
  if (isZ4Schema(schema)) {
    const v4Schema = schema;
    rawShape = v4Schema._zod?.def?.shape;
  } else {
    const v3Schema = schema;
    rawShape = v3Schema.shape;
  }
  if (!rawShape)
    return void 0;
  if (typeof rawShape === "function") {
    try {
      return rawShape();
    } catch {
      return void 0;
    }
  }
  return rawShape;
}
function normalizeObjectSchema(schema) {
  if (!schema)
    return void 0;
  if (typeof schema === "object") {
    const asV3 = schema;
    const asV4 = schema;
    if (!asV3._def && !asV4._zod) {
      const values = Object.values(schema);
      if (values.length > 0 && values.every((v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function"))) {
        return objectFromShape(schema);
      }
    }
  }
  if (isZ4Schema(schema)) {
    const v4Schema = schema;
    const def = v4Schema._zod?.def;
    if (def && (def.type === "object" || def.shape !== void 0)) {
      return schema;
    }
  } else {
    const v3Schema = schema;
    if (v3Schema.shape !== void 0) {
      return schema;
    }
  }
  return void 0;
}
function getDotPath(path) {
  if (path.length === 0) {
    return "object root";
  }
  return path.reduce((acc, seg, index) => {
    if (index === 0) {
      return String(seg);
    }
    if (typeof seg === "number") {
      return `${acc}[${seg}]`;
    }
    return `${acc}.${seg}`;
  }, "");
}
function getParseErrorMessage(error51) {
  if (error51 && typeof error51 === "object") {
    if ("issues" in error51 && Array.isArray(error51.issues) && error51.issues.length > 0) {
      return error51.issues.map((i2) => {
        if (!i2.path?.length) {
          return i2.message;
        }
        return `${i2.message} at ${getDotPath(i2.path)}`;
      }).join("\n");
    }
    if ("message" in error51 && typeof error51.message === "string") {
      return error51.message;
    }
    try {
      return JSON.stringify(error51);
    } catch {
      return String(error51);
    }
  }
  return String(error51);
}
function getSchemaDescription(schema) {
  return schema.description;
}
function isSchemaOptional(schema) {
  if (isZ4Schema(schema)) {
    const v4Schema = schema;
    return v4Schema._zod?.def?.type === "optional";
  }
  const v3Schema = schema;
  if (typeof schema.isOptional === "function") {
    return schema.isOptional();
  }
  return v3Schema._def?.typeName === "ZodOptional";
}
function getLiteralValue(schema) {
  if (isZ4Schema(schema)) {
    const v4Schema = schema;
    const def2 = v4Schema._zod?.def;
    if (def2) {
      if (def2.value !== void 0)
        return def2.value;
      if (Array.isArray(def2.values) && def2.values.length > 0) {
        return def2.values[0];
      }
    }
  }
  const v3Schema = schema;
  const def = v3Schema._def;
  if (def) {
    if (def.value !== void 0)
      return def.value;
    if (Array.isArray(def.values) && def.values.length > 0) {
      return def.values[0];
    }
  }
  const directValue = schema.value;
  if (directValue !== void 0)
    return directValue;
  return void 0;
}

// node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js
function isTerminal(status) {
  return status === "completed" || status === "failed" || status === "cancelled";
}

// node_modules/zod-to-json-schema/dist/esm/Options.js
var ignoreOverride = /* @__PURE__ */ Symbol("Let zodToJsonSchema decide on which parser to use");
var defaultOptions = {
  name: void 0,
  $refStrategy: "root",
  basePath: ["#"],
  effectStrategy: "input",
  pipeStrategy: "all",
  dateStrategy: "format:date-time",
  mapStrategy: "entries",
  removeAdditionalStrategy: "passthrough",
  allowedAdditionalProperties: true,
  rejectedAdditionalProperties: false,
  definitionPath: "definitions",
  target: "jsonSchema7",
  strictUnions: false,
  definitions: {},
  errorMessages: false,
  markdownDescription: false,
  patternStrategy: "escape",
  applyRegexFlags: false,
  emailStrategy: "format:email",
  base64Strategy: "contentEncoding:base64",
  nameStrategy: "ref",
  openAiAnyTypeName: "OpenAiAnyType"
};
var getDefaultOptions = (options) => typeof options === "string" ? {
  ...defaultOptions,
  name: options
} : {
  ...defaultOptions,
  ...options
};

// node_modules/zod-to-json-schema/dist/esm/Refs.js
var getRefs = (options) => {
  const _options = getDefaultOptions(options);
  const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
  return {
    ..._options,
    flags: { hasReferencedOpenAiAnyType: false },
    currentPath,
    propertyPath: void 0,
    seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
      def._def,
      {
        def: def._def,
        path: [..._options.basePath, _options.definitionPath, name],
        // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
        jsonSchema: void 0
      }
    ]))
  };
};

// node_modules/zod-to-json-schema/dist/esm/errorMessages.js
function addErrorMessage(res, key, errorMessage, refs) {
  if (!refs?.errorMessages)
    return;
  if (errorMessage) {
    res.errorMessage = {
      ...res.errorMessage,
      [key]: errorMessage
    };
  }
}
function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
  res[key] = value;
  addErrorMessage(res, key, errorMessage, refs);
}

// node_modules/zod-to-json-schema/dist/esm/getRelativePath.js
var getRelativePath = (pathA, pathB) => {
  let i2 = 0;
  for (; i2 < pathA.length && i2 < pathB.length; i2++) {
    if (pathA[i2] !== pathB[i2])
      break;
  }
  return [(pathA.length - i2).toString(), ...pathB.slice(i2)].join("/");
};

// node_modules/zod-to-json-schema/dist/esm/parsers/any.js
function parseAnyDef(refs) {
  if (refs.target !== "openAi") {
    return {};
  }
  const anyDefinitionPath = [
    ...refs.basePath,
    refs.definitionPath,
    refs.openAiAnyTypeName
  ];
  refs.flags.hasReferencedOpenAiAnyType = true;
  return {
    $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/")
  };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/array.js
function parseArrayDef(def, refs) {
  const res = {
    type: "array"
  };
  if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind2.ZodAny) {
    res.items = parseDef(def.type._def, {
      ...refs,
      currentPath: [...refs.currentPath, "items"]
    });
  }
  if (def.minLength) {
    setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
  }
  if (def.maxLength) {
    setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
  }
  if (def.exactLength) {
    setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
    setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
  }
  return res;
}

// node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
function parseBigintDef(def, refs) {
  const res = {
    type: "integer",
    format: "int64"
  };
  if (!def.checks)
    return res;
  for (const check2 of def.checks) {
    switch (check2.kind) {
      case "min":
        if (refs.target === "jsonSchema7") {
          if (check2.inclusive) {
            setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);
          } else {
            setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs);
          }
        } else {
          if (!check2.inclusive) {
            res.exclusiveMinimum = true;
          }
          setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);
        }
        break;
      case "max":
        if (refs.target === "jsonSchema7") {
          if (check2.inclusive) {
            setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);
          } else {
            setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs);
          }
        } else {
          if (!check2.inclusive) {
            res.exclusiveMaximum = true;
          }
          setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);
        }
        break;
      case "multipleOf":
        setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs);
        break;
    }
  }
  return res;
}

// node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
function parseBooleanDef() {
  return {
    type: "boolean"
  };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/branded.js
function parseBrandedDef(_def, refs) {
  return parseDef(_def.type._def, refs);
}

// node_modules/zod-to-json-schema/dist/esm/parsers/catch.js
var parseCatchDef = (def, refs) => {
  return parseDef(def.innerType._def, refs);
};

// node_modules/zod-to-json-schema/dist/esm/parsers/date.js
function parseDateDef(def, refs, overrideDateStrategy) {
  const strategy = overrideDateStrategy ?? refs.dateStrategy;
  if (Array.isArray(strategy)) {
    return {
      anyOf: strategy.map((item, i2) => parseDateDef(def, refs, item))
    };
  }
  switch (strategy) {
    case "string":
    case "format:date-time":
      return {
        type: "string",
        format: "date-time"
      };
    case "format:date":
      return {
        type: "string",
        format: "date"
      };
    case "integer":
      return integerDateParser(def, refs);
  }
}
var integerDateParser = (def, refs) => {
  const res = {
    type: "integer",
    format: "unix-time"
  };
  if (refs.target === "openApi3") {
    return res;
  }
  for (const check2 of def.checks) {
    switch (check2.kind) {
      case "min":
        setResponseValueAndErrors(
          res,
          "minimum",
          check2.value,
          // This is in milliseconds
          check2.message,
          refs
        );
        break;
      case "max":
        setResponseValueAndErrors(
          res,
          "maximum",
          check2.value,
          // This is in milliseconds
          check2.message,
          refs
        );
        break;
    }
  }
  return res;
};

// node_modules/zod-to-json-schema/dist/esm/parsers/default.js
function parseDefaultDef(_def, refs) {
  return {
    ...parseDef(_def.innerType._def, refs),
    default: _def.defaultValue()
  };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/effects.js
function parseEffectsDef(_def, refs) {
  return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs);
}

// node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
function parseEnumDef(def) {
  return {
    type: "string",
    enum: Array.from(def.values)
  };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
var isJsonSchema7AllOfType = (type) => {
  if ("type" in type && type.type === "string")
    return false;
  return "allOf" in type;
};
function parseIntersectionDef(def, refs) {
  const allOf = [
    parseDef(def.left._def, {
      ...refs,
      currentPath: [...refs.currentPath, "allOf", "0"]
    }),
    parseDef(def.right._def, {
      ...refs,
      currentPath: [...refs.currentPath, "allOf", "1"]
    })
  ].filter((x2) => !!x2);
  let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
  const mergedAllOf = [];
  allOf.forEach((schema) => {
    if (isJsonSchema7AllOfType(schema)) {
      mergedAllOf.push(...schema.allOf);
      if (schema.unevaluatedProperties === void 0) {
        unevaluatedProperties = void 0;
      }
    } else {
      let nestedSchema = schema;
      if ("additionalProperties" in schema && schema.additionalProperties === false) {
        const { additionalProperties, ...rest } = schema;
        nestedSchema = rest;
      } else {
        unevaluatedProperties = void 0;
      }
      mergedAllOf.push(nestedSchema);
    }
  });
  return mergedAllOf.length ? {
    allOf: mergedAllOf,
    ...unevaluatedProperties
  } : void 0;
}

// node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
function parseLiteralDef(def, refs) {
  const parsedType2 = typeof def.value;
  if (parsedType2 !== "bigint" && parsedType2 !== "number" && parsedType2 !== "boolean" && parsedType2 !== "string") {
    return {
      type: Array.isArray(def.value) ? "array" : "object"
    };
  }
  if (refs.target === "openApi3") {
    return {
      type: parsedType2 === "bigint" ? "integer" : parsedType2,
      enum: [def.value]
    };
  }
  return {
    type: parsedType2 === "bigint" ? "integer" : parsedType2,
    const: def.value
  };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/string.js
var emojiRegex2 = void 0;
var zodPatterns = {
  /**
   * `c` was changed to `[cC]` to replicate /i flag
   */
  cuid: /^[cC][^\s-]{8,}$/,
  cuid2: /^[0-9a-z]+$/,
  ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
  /**
   * `a-z` was added to replicate /i flag
   */
  email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
  /**
   * Constructed a valid Unicode RegExp
   *
   * Lazily instantiate since this type of regex isn't supported
   * in all envs (e.g. React Native).
   *
   * See:
   * https://github.com/colinhacks/zod/issues/2433
   * Fix in Zod:
   * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
   */
  emoji: () => {
    if (emojiRegex2 === void 0) {
      emojiRegex2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
    }
    return emojiRegex2;
  },
  /**
   * Unused
   */
  uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
  /**
   * Unused
   */
  ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
  ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
  /**
   * Unused
   */
  ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
  ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
  base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
  base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
  nanoid: /^[a-zA-Z0-9_-]{21}$/,
  jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
};
function parseStringDef(def, refs) {
  const res = {
    type: "string"
  };
  if (def.checks) {
    for (const check2 of def.checks) {
      switch (check2.kind) {
        case "min":
          setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs);
          break;
        case "max":
          setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs);
          break;
        case "email":
          switch (refs.emailStrategy) {
            case "format:email":
              addFormat(res, "email", check2.message, refs);
              break;
            case "format:idn-email":
              addFormat(res, "idn-email", check2.message, refs);
              break;
            case "pattern:zod":
              addPattern(res, zodPatterns.email, check2.message, refs);
              break;
          }
          break;
        case "url":
          addFormat(res, "uri", check2.message, refs);
          break;
        case "uuid":
          addFormat(res, "uuid", check2.message, refs);
          break;
        case "regex":
          addPattern(res, check2.regex, check2.message, refs);
          break;
        case "cuid":
          addPattern(res, zodPatterns.cuid, check2.message, refs);
          break;
        case "cuid2":
          addPattern(res, zodPatterns.cuid2, check2.message, refs);
          break;
        case "startsWith":
          addPattern(res, RegExp(`^${escapeLiteralCheckValue(check2.value, refs)}`), check2.message, refs);
          break;
        case "endsWith":
          addPattern(res, RegExp(`${escapeLiteralCheckValue(check2.value, refs)}$`), check2.message, refs);
          break;
        case "datetime":
          addFormat(res, "date-time", check2.message, refs);
          break;
        case "date":
          addFormat(res, "date", check2.message, refs);
          break;
        case "time":
          addFormat(res, "time", check2.message, refs);
          break;
        case "duration":
          addFormat(res, "duration", check2.message, refs);
          break;
        case "length":
          setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs);
          setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs);
          break;
        case "includes": {
          addPattern(res, RegExp(escapeLiteralCheckValue(check2.value, refs)), check2.message, refs);
          break;
        }
        case "ip": {
          if (check2.version !== "v6") {
            addFormat(res, "ipv4", check2.message, refs);
          }
          if (check2.version !== "v4") {
            addFormat(res, "ipv6", check2.message, refs);
          }
          break;
        }
        case "base64url":
          addPattern(res, zodPatterns.base64url, check2.message, refs);
          break;
        case "jwt":
          addPattern(res, zodPatterns.jwt, check2.message, refs);
          break;
        case "cidr": {
          if (check2.version !== "v6") {
            addPattern(res, zodPatterns.ipv4Cidr, check2.message, refs);
          }
          if (check2.version !== "v4") {
            addPattern(res, zodPatterns.ipv6Cidr, check2.message, refs);
          }
          break;
        }
        case "emoji":
          addPattern(res, zodPatterns.emoji(), check2.message, refs);
          break;
        case "ulid": {
          addPattern(res, zodPatterns.ulid, check2.message, refs);
          break;
        }
        case "base64": {
          switch (refs.base64Strategy) {
            case "format:binary": {
              addFormat(res, "binary", check2.message, refs);
              break;
            }
            case "contentEncoding:base64": {
              setResponseValueAndErrors(res, "contentEncoding", "base64", check2.message, refs);
              break;
            }
            case "pattern:zod": {
              addPattern(res, zodPatterns.base64, check2.message, refs);
              break;
            }
          }
          break;
        }
        case "nanoid": {
          addPattern(res, zodPatterns.nanoid, check2.message, refs);
        }
        case "toLowerCase":
        case "toUpperCase":
        case "trim":
          break;
        default:
          /* @__PURE__ */ ((_) => {
          })(check2);
      }
    }
  }
  return res;
}
function escapeLiteralCheckValue(literal2, refs) {
  return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal2) : literal2;
}
var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
function escapeNonAlphaNumeric(source) {
  let result = "";
  for (let i2 = 0; i2 < source.length; i2++) {
    if (!ALPHA_NUMERIC.has(source[i2])) {
      result += "\\";
    }
    result += source[i2];
  }
  return result;
}
function addFormat(schema, value, message, refs) {
  if (schema.format || schema.anyOf?.some((x2) => x2.format)) {
    if (!schema.anyOf) {
      schema.anyOf = [];
    }
    if (schema.format) {
      schema.anyOf.push({
        format: schema.format,
        ...schema.errorMessage && refs.errorMessages && {
          errorMessage: { format: schema.errorMessage.format }
        }
      });
      delete schema.format;
      if (schema.errorMessage) {
        delete schema.errorMessage.format;
        if (Object.keys(schema.errorMessage).length === 0) {
          delete schema.errorMessage;
        }
      }
    }
    schema.anyOf.push({
      format: value,
      ...message && refs.errorMessages && { errorMessage: { format: message } }
    });
  } else {
    setResponseValueAndErrors(schema, "format", value, message, refs);
  }
}
function addPattern(schema, regex, message, refs) {
  if (schema.pattern || schema.allOf?.some((x2) => x2.pattern)) {
    if (!schema.allOf) {
      schema.allOf = [];
    }
    if (schema.pattern) {
      schema.allOf.push({
        pattern: schema.pattern,
        ...schema.errorMessage && refs.errorMessages && {
          errorMessage: { pattern: schema.errorMessage.pattern }
        }
      });
      delete schema.pattern;
      if (schema.errorMessage) {
        delete schema.errorMessage.pattern;
        if (Object.keys(schema.errorMessage).length === 0) {
          delete schema.errorMessage;
        }
      }
    }
    schema.allOf.push({
      pattern: stringifyRegExpWithFlags(regex, refs),
      ...message && refs.errorMessages && { errorMessage: { pattern: message } }
    });
  } else {
    setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);
  }
}
function stringifyRegExpWithFlags(regex, refs) {
  if (!refs.applyRegexFlags || !regex.flags) {
    return regex.source;
  }
  const flags = {
    i: regex.flags.includes("i"),
    m: regex.flags.includes("m"),
    s: regex.flags.includes("s")
    // `.` matches newlines
  };
  const source = flags.i ? regex.source.toLowerCase() : regex.source;
  let pattern = "";
  let isEscaped = false;
  let inCharGroup = false;
  let inCharRange = false;
  for (let i2 = 0; i2 < source.length; i2++) {
    if (isEscaped) {
      pattern += source[i2];
      isEscaped = false;
      continue;
    }
    if (flags.i) {
      if (inCharGroup) {
        if (source[i2].match(/[a-z]/)) {
          if (inCharRange) {
            pattern += source[i2];
            pattern += `${source[i2 - 2]}-${source[i2]}`.toUpperCase();
            inCharRange = false;
          } else if (source[i2 + 1] === "-" && source[i2 + 2]?.match(/[a-z]/)) {
            pattern += source[i2];
            inCharRange = true;
          } else {
            pattern += `${source[i2]}${source[i2].toUpperCase()}`;
          }
          continue;
        }
      } else if (source[i2].match(/[a-z]/)) {
        pattern += `[${source[i2]}${source[i2].toUpperCase()}]`;
        continue;
      }
    }
    if (flags.m) {
      if (source[i2] === "^") {
        pattern += `(^|(?<=[\r
]))`;
        continue;
      } else if (source[i2] === "$") {
        pattern += `($|(?=[\r
]))`;
        continue;
      }
    }
    if (flags.s && source[i2] === ".") {
      pattern += inCharGroup ? `${source[i2]}\r
` : `[${source[i2]}\r
]`;
      continue;
    }
    pattern += source[i2];
    if (source[i2] === "\\") {
      isEscaped = true;
    } else if (inCharGroup && source[i2] === "]") {
      inCharGroup = false;
    } else if (!inCharGroup && source[i2] === "[") {
      inCharGroup = true;
    }
  }
  try {
    new RegExp(pattern);
  } catch {
    console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
    return regex.source;
  }
  return pattern;
}

// node_modules/zod-to-json-schema/dist/esm/parsers/record.js
function parseRecordDef(def, refs) {
  if (refs.target === "openAi") {
    console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
  }
  if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodEnum) {
    return {
      type: "object",
      required: def.keyType._def.values,
      properties: def.keyType._def.values.reduce((acc, key) => ({
        ...acc,
        [key]: parseDef(def.valueType._def, {
          ...refs,
          currentPath: [...refs.currentPath, "properties", key]
        }) ?? parseAnyDef(refs)
      }), {}),
      additionalProperties: refs.rejectedAdditionalProperties
    };
  }
  const schema = {
    type: "object",
    additionalProperties: parseDef(def.valueType._def, {
      ...refs,
      currentPath: [...refs.currentPath, "additionalProperties"]
    }) ?? refs.allowedAdditionalProperties
  };
  if (refs.target === "openApi3") {
    return schema;
  }
  if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodString && def.keyType._def.checks?.length) {
    const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
    return {
      ...schema,
      propertyNames: keyType
    };
  } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodEnum) {
    return {
      ...schema,
      propertyNames: {
        enum: def.keyType._def.values
      }
    };
  } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && def.keyType._def.type._def.checks?.length) {
    const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
    return {
      ...schema,
      propertyNames: keyType
    };
  }
  return schema;
}

// node_modules/zod-to-json-schema/dist/esm/parsers/map.js
function parseMapDef(def, refs) {
  if (refs.mapStrategy === "record") {
    return parseRecordDef(def, refs);
  }
  const keys = parseDef(def.keyType._def, {
    ...refs,
    currentPath: [...refs.currentPath, "items", "items", "0"]
  }) || parseAnyDef(refs);
  const values = parseDef(def.valueType._def, {
    ...refs,
    currentPath: [...refs.currentPath, "items", "items", "1"]
  }) || parseAnyDef(refs);
  return {
    type: "array",
    maxItems: 125,
    items: {
      type: "array",
      items: [keys, values],
      minItems: 2,
      maxItems: 2
    }
  };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
function parseNativeEnumDef(def) {
  const object3 = def.values;
  const actualKeys = Object.keys(def.values).filter((key) => {
    return typeof object3[object3[key]] !== "number";
  });
  const actualValues = actualKeys.map((key) => object3[key]);
  const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
  return {
    type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
    enum: actualValues
  };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/never.js
function parseNeverDef(refs) {
  return refs.target === "openAi" ? void 0 : {
    not: parseAnyDef({
      ...refs,
      currentPath: [...refs.currentPath, "not"]
    })
  };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/null.js
function parseNullDef(refs) {
  return refs.target === "openApi3" ? {
    enum: ["null"],
    nullable: true
  } : {
    type: "null"
  };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/union.js
var primitiveMappings = {
  ZodString: "string",
  ZodNumber: "number",
  ZodBigInt: "integer",
  ZodBoolean: "boolean",
  ZodNull: "null"
};
function parseUnionDef(def, refs) {
  if (refs.target === "openApi3")
    return asAnyOf(def, refs);
  const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
  if (options.every((x2) => x2._def.typeName in primitiveMappings && (!x2._def.checks || !x2._def.checks.length))) {
    const types3 = options.reduce((types4, x2) => {
      const type = primitiveMappings[x2._def.typeName];
      return type && !types4.includes(type) ? [...types4, type] : types4;
    }, []);
    return {
      type: types3.length > 1 ? types3 : types3[0]
    };
  } else if (options.every((x2) => x2._def.typeName === "ZodLiteral" && !x2.description)) {
    const types3 = options.reduce((acc, x2) => {
      const type = typeof x2._def.value;
      switch (type) {
        case "string":
        case "number":
        case "boolean":
          return [...acc, type];
        case "bigint":
          return [...acc, "integer"];
        case "object":
          if (x2._def.value === null)
            return [...acc, "null"];
        case "symbol":
        case "undefined":
        case "function":
        default:
          return acc;
      }
    }, []);
    if (types3.length === options.length) {
      const uniqueTypes = types3.filter((x2, i2, a) => a.indexOf(x2) === i2);
      return {
        type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
        enum: options.reduce((acc, x2) => {
          return acc.includes(x2._def.value) ? acc : [...acc, x2._def.value];
        }, [])
      };
    }
  } else if (options.every((x2) => x2._def.typeName === "ZodEnum")) {
    return {
      type: "string",
      enum: options.reduce((acc, x2) => [
        ...acc,
        ...x2._def.values.filter((x3) => !acc.includes(x3))
      ], [])
    };
  }
  return asAnyOf(def, refs);
}
var asAnyOf = (def, refs) => {
  const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x2, i2) => parseDef(x2._def, {
    ...refs,
    currentPath: [...refs.currentPath, "anyOf", `${i2}`]
  })).filter((x2) => !!x2 && (!refs.strictUnions || typeof x2 === "object" && Object.keys(x2).length > 0));
  return anyOf.length ? { anyOf } : void 0;
};

// node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
function parseNullableDef(def, refs) {
  if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
    if (refs.target === "openApi3") {
      return {
        type: primitiveMappings[def.innerType._def.typeName],
        nullable: true
      };
    }
    return {
      type: [
        primitiveMappings[def.innerType._def.typeName],
        "null"
      ]
    };
  }
  if (refs.target === "openApi3") {
    const base2 = parseDef(def.innerType._def, {
      ...refs,
      currentPath: [...refs.currentPath]
    });
    if (base2 && "$ref" in base2)
      return { allOf: [base2], nullable: true };
    return base2 && { ...base2, nullable: true };
  }
  const base = parseDef(def.innerType._def, {
    ...refs,
    currentPath: [...refs.currentPath, "anyOf", "0"]
  });
  return base && { anyOf: [base, { type: "null" }] };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/number.js
function parseNumberDef(def, refs) {
  const res = {
    type: "number"
  };
  if (!def.checks)
    return res;
  for (const check2 of def.checks) {
    switch (check2.kind) {
      case "int":
        res.type = "integer";
        addErrorMessage(res, "type", check2.message, refs);
        break;
      case "min":
        if (refs.target === "jsonSchema7") {
          if (check2.inclusive) {
            setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);
          } else {
            setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs);
          }
        } else {
          if (!check2.inclusive) {
            res.exclusiveMinimum = true;
          }
          setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);
        }
        break;
      case "max":
        if (refs.target === "jsonSchema7") {
          if (check2.inclusive) {
            setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);
          } else {
            setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs);
          }
        } else {
          if (!check2.inclusive) {
            res.exclusiveMaximum = true;
          }
          setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);
        }
        break;
      case "multipleOf":
        setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs);
        break;
    }
  }
  return res;
}

// node_modules/zod-to-json-schema/dist/esm/parsers/object.js
function parseObjectDef(def, refs) {
  const forceOptionalIntoNullable = refs.target === "openAi";
  const result = {
    type: "object",
    properties: {}
  };
  const required2 = [];
  const shape = def.shape();
  for (const propName in shape) {
    let propDef = shape[propName];
    if (propDef === void 0 || propDef._def === void 0) {
      continue;
    }
    let propOptional = safeIsOptional(propDef);
    if (propOptional && forceOptionalIntoNullable) {
      if (propDef._def.typeName === "ZodOptional") {
        propDef = propDef._def.innerType;
      }
      if (!propDef.isNullable()) {
        propDef = propDef.nullable();
      }
      propOptional = false;
    }
    const parsedDef = parseDef(propDef._def, {
      ...refs,
      currentPath: [...refs.currentPath, "properties", propName],
      propertyPath: [...refs.currentPath, "properties", propName]
    });
    if (parsedDef === void 0) {
      continue;
    }
    result.properties[propName] = parsedDef;
    if (!propOptional) {
      required2.push(propName);
    }
  }
  if (required2.length) {
    result.required = required2;
  }
  const additionalProperties = decideAdditionalProperties(def, refs);
  if (additionalProperties !== void 0) {
    result.additionalProperties = additionalProperties;
  }
  return result;
}
function decideAdditionalProperties(def, refs) {
  if (def.catchall._def.typeName !== "ZodNever") {
    return parseDef(def.catchall._def, {
      ...refs,
      currentPath: [...refs.currentPath, "additionalProperties"]
    });
  }
  switch (def.unknownKeys) {
    case "passthrough":
      return refs.allowedAdditionalProperties;
    case "strict":
      return refs.rejectedAdditionalProperties;
    case "strip":
      return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
  }
}
function safeIsOptional(schema) {
  try {
    return schema.isOptional();
  } catch {
    return true;
  }
}

// node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
var parseOptionalDef = (def, refs) => {
  if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
    return parseDef(def.innerType._def, refs);
  }
  const innerSchema = parseDef(def.innerType._def, {
    ...refs,
    currentPath: [...refs.currentPath, "anyOf", "1"]
  });
  return innerSchema ? {
    anyOf: [
      {
        not: parseAnyDef(refs)
      },
      innerSchema
    ]
  } : parseAnyDef(refs);
};

// node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
var parsePipelineDef = (def, refs) => {
  if (refs.pipeStrategy === "input") {
    return parseDef(def.in._def, refs);
  } else if (refs.pipeStrategy === "output") {
    return parseDef(def.out._def, refs);
  }
  const a = parseDef(def.in._def, {
    ...refs,
    currentPath: [...refs.currentPath, "allOf", "0"]
  });
  const b = parseDef(def.out._def, {
    ...refs,
    currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
  });
  return {
    allOf: [a, b].filter((x2) => x2 !== void 0)
  };
};

// node_modules/zod-to-json-schema/dist/esm/parsers/promise.js
function parsePromiseDef(def, refs) {
  return parseDef(def.type._def, refs);
}

// node_modules/zod-to-json-schema/dist/esm/parsers/set.js
function parseSetDef(def, refs) {
  const items = parseDef(def.valueType._def, {
    ...refs,
    currentPath: [...refs.currentPath, "items"]
  });
  const schema = {
    type: "array",
    uniqueItems: true,
    items
  };
  if (def.minSize) {
    setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
  }
  if (def.maxSize) {
    setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
  }
  return schema;
}

// node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
function parseTupleDef(def, refs) {
  if (def.rest) {
    return {
      type: "array",
      minItems: def.items.length,
      items: def.items.map((x2, i2) => parseDef(x2._def, {
        ...refs,
        currentPath: [...refs.currentPath, "items", `${i2}`]
      })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], []),
      additionalItems: parseDef(def.rest._def, {
        ...refs,
        currentPath: [...refs.currentPath, "additionalItems"]
      })
    };
  } else {
    return {
      type: "array",
      minItems: def.items.length,
      maxItems: def.items.length,
      items: def.items.map((x2, i2) => parseDef(x2._def, {
        ...refs,
        currentPath: [...refs.currentPath, "items", `${i2}`]
      })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], [])
    };
  }
}

// node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js
function parseUndefinedDef(refs) {
  return {
    not: parseAnyDef(refs)
  };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js
function parseUnknownDef(refs) {
  return parseAnyDef(refs);
}

// node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js
var parseReadonlyDef = (def, refs) => {
  return parseDef(def.innerType._def, refs);
};

// node_modules/zod-to-json-schema/dist/esm/selectParser.js
var selectParser = (def, typeName, refs) => {
  switch (typeName) {
    case ZodFirstPartyTypeKind2.ZodString:
      return parseStringDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodNumber:
      return parseNumberDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodObject:
      return parseObjectDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodBigInt:
      return parseBigintDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodBoolean:
      return parseBooleanDef();
    case ZodFirstPartyTypeKind2.ZodDate:
      return parseDateDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodUndefined:
      return parseUndefinedDef(refs);
    case ZodFirstPartyTypeKind2.ZodNull:
      return parseNullDef(refs);
    case ZodFirstPartyTypeKind2.ZodArray:
      return parseArrayDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodUnion:
    case ZodFirstPartyTypeKind2.ZodDiscriminatedUnion:
      return parseUnionDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodIntersection:
      return parseIntersectionDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodTuple:
      return parseTupleDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodRecord:
      return parseRecordDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodLiteral:
      return parseLiteralDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodEnum:
      return parseEnumDef(def);
    case ZodFirstPartyTypeKind2.ZodNativeEnum:
      return parseNativeEnumDef(def);
    case ZodFirstPartyTypeKind2.ZodNullable:
      return parseNullableDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodOptional:
      return parseOptionalDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodMap:
      return parseMapDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodSet:
      return parseSetDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodLazy:
      return () => def.getter()._def;
    case ZodFirstPartyTypeKind2.ZodPromise:
      return parsePromiseDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodNaN:
    case ZodFirstPartyTypeKind2.ZodNever:
      return parseNeverDef(refs);
    case ZodFirstPartyTypeKind2.ZodEffects:
      return parseEffectsDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodAny:
      return parseAnyDef(refs);
    case ZodFirstPartyTypeKind2.ZodUnknown:
      return parseUnknownDef(refs);
    case ZodFirstPartyTypeKind2.ZodDefault:
      return parseDefaultDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodBranded:
      return parseBrandedDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodReadonly:
      return parseReadonlyDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodCatch:
      return parseCatchDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodPipeline:
      return parsePipelineDef(def, refs);
    case ZodFirstPartyTypeKind2.ZodFunction:
    case ZodFirstPartyTypeKind2.ZodVoid:
    case ZodFirstPartyTypeKind2.ZodSymbol:
      return void 0;
    default:
      return /* @__PURE__ */ ((_) => void 0)(typeName);
  }
};

// node_modules/zod-to-json-schema/dist/esm/parseDef.js
function parseDef(def, refs, forceResolution = false) {
  const seenItem = refs.seen.get(def);
  if (refs.override) {
    const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
    if (overrideResult !== ignoreOverride) {
      return overrideResult;
    }
  }
  if (seenItem && !forceResolution) {
    const seenSchema = get$ref(seenItem, refs);
    if (seenSchema !== void 0) {
      return seenSchema;
    }
  }
  const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
  refs.seen.set(def, newItem);
  const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
  const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
  if (jsonSchema) {
    addMeta(def, refs, jsonSchema);
  }
  if (refs.postProcess) {
    const postProcessResult = refs.postProcess(jsonSchema, def, refs);
    newItem.jsonSchema = jsonSchema;
    return postProcessResult;
  }
  newItem.jsonSchema = jsonSchema;
  return jsonSchema;
}
var get$ref = (item, refs) => {
  switch (refs.$refStrategy) {
    case "root":
      return { $ref: item.path.join("/") };
    case "relative":
      return { $ref: getRelativePath(refs.currentPath, item.path) };
    case "none":
    case "seen": {
      if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
        console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
        return parseAnyDef(refs);
      }
      return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0;
    }
  }
};
var addMeta = (def, refs, jsonSchema) => {
  if (def.description) {
    jsonSchema.description = def.description;
    if (refs.markdownDescription) {
      jsonSchema.markdownDescription = def.description;
    }
  }
  return jsonSchema;
};

// node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
var zodToJsonSchema = (schema, options) => {
  const refs = getRefs(options);
  let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({
    ...acc,
    [name2]: parseDef(schema2._def, {
      ...refs,
      currentPath: [...refs.basePath, refs.definitionPath, name2]
    }, true) ?? parseAnyDef(refs)
  }), {}) : void 0;
  const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
  const main2 = parseDef(schema._def, name === void 0 ? refs : {
    ...refs,
    currentPath: [...refs.basePath, refs.definitionPath, name]
  }, false) ?? parseAnyDef(refs);
  const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
  if (title !== void 0) {
    main2.title = title;
  }
  if (refs.flags.hasReferencedOpenAiAnyType) {
    if (!definitions) {
      definitions = {};
    }
    if (!definitions[refs.openAiAnyTypeName]) {
      definitions[refs.openAiAnyTypeName] = {
        // Skipping "object" as no properties can be defined and additionalProperties must be "false"
        type: ["string", "number", "integer", "boolean", "array", "null"],
        items: {
          $ref: refs.$refStrategy === "relative" ? "1" : [
            ...refs.basePath,
            refs.definitionPath,
            refs.openAiAnyTypeName
          ].join("/")
        }
      };
    }
  }
  const combined = name === void 0 ? definitions ? {
    ...main2,
    [refs.definitionPath]: definitions
  } : main2 : {
    $ref: [
      ...refs.$refStrategy === "relative" ? [] : refs.basePath,
      refs.definitionPath,
      name
    ].join("/"),
    [refs.definitionPath]: {
      ...definitions,
      [name]: main2
    }
  };
  if (refs.target === "jsonSchema7") {
    combined.$schema = "http://json-schema.org/draft-07/schema#";
  } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {
    combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
  }
  if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) {
    console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
  }
  return combined;
};

// node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js
function mapMiniTarget(t2) {
  if (!t2)
    return "draft-7";
  if (t2 === "jsonSchema7" || t2 === "draft-7")
    return "draft-7";
  if (t2 === "jsonSchema2019-09" || t2 === "draft-2020-12")
    return "draft-2020-12";
  return "draft-7";
}
function toJsonSchemaCompat(schema, opts) {
  if (isZ4Schema(schema)) {
    return toJSONSchema(schema, {
      target: mapMiniTarget(opts?.target),
      io: opts?.pipeStrategy ?? "input"
    });
  }
  return zodToJsonSchema(schema, {
    strictUnions: opts?.strictUnions ?? true,
    pipeStrategy: opts?.pipeStrategy ?? "input"
  });
}
function getMethodLiteral(schema) {
  const shape = getObjectShape(schema);
  const methodSchema = shape?.method;
  if (!methodSchema) {
    throw new Error("Schema is missing a method literal");
  }
  const value = getLiteralValue(methodSchema);
  if (typeof value !== "string") {
    throw new Error("Schema method literal must be a string");
  }
  return value;
}
function parseWithCompat(schema, data) {
  const result = safeParse3(schema, data);
  if (!result.success) {
    throw result.error;
  }
  return result.data;
}

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

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

// node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js
var ExperimentalServerTasks = class {
  constructor(_server) {
    this._server = _server;
  }
  /**
   * Sends a request and returns an AsyncGenerator that yields response messages.
   * The generator is guaranteed to end with either a 'result' or 'error' message.
   *
   * This method provides streaming access to request processing, allowing you to
   * observe intermediate task status updates for task-augmented requests.
   *
   * @param request - The request to send
   * @param resultSchema - Zod schema for validating the result
   * @param options - Optional request options (timeout, signal, task creation params, etc.)
   * @returns AsyncGenerator that yields ResponseMessage objects
   *
   * @experimental
   */
  requestStream(request, resultSchema, options) {
    return this._server.requestStream(request, resultSchema, options);
  }
  /**
   * Sends a sampling request and returns an AsyncGenerator that yields response messages.
   * The generator is guaranteed to end with either a 'result' or 'error' message.
   *
   * For task-augmented requests, yields 'taskCreated' and 'taskStatus' messages
   * before the final result.
   *
   * @example
   * ```typescript
   * const stream = server.experimental.tasks.createMessageStream({
   *     messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }],
   *     maxTokens: 100
   * }, {
   *     onprogress: (progress) => {
   *         // Handle streaming tokens via progress notifications
   *         console.log('Progress:', progress.message);
   *     }
   * });
   *
   * for await (const message of stream) {
   *     switch (message.type) {
   *         case 'taskCreated':
   *             console.log('Task created:', message.task.taskId);
   *             break;
   *         case 'taskStatus':
   *             console.log('Task status:', message.task.status);
   *             break;
   *         case 'result':
   *             console.log('Final result:', message.result);
   *             break;
   *         case 'error':
   *             console.error('Error:', message.error);
   *             break;
   *     }
   * }
   * ```
   *
   * @param params - The sampling request parameters
   * @param options - Optional request options (timeout, signal, task creation params, onprogress, etc.)
   * @returns AsyncGenerator that yields ResponseMessage objects
   *
   * @experimental
   */
  createMessageStream(params, options) {
    const clientCapabilities = this._server.getClientCapabilities();
    if ((params.tools || params.toolChoice) && !clientCapabilities?.sampling?.tools) {
      throw new Error("Client does not support sampling tools capability.");
    }
    if (params.messages.length > 0) {
      const lastMessage = params.messages[params.messages.length - 1];
      const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];
      const hasToolResults = lastContent.some((c) => c.type === "tool_result");
      const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0;
      const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : [];
      const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use");
      if (hasToolResults) {
        if (lastContent.some((c) => c.type !== "tool_result")) {
          throw new Error("The last message must contain only tool_result content if any is present");
        }
        if (!hasPreviousToolUse) {
          throw new Error("tool_result blocks are not matching any tool_use from the previous message");
        }
      }
      if (hasPreviousToolUse) {
        const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id));
        const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId));
        if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) {
          throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match");
        }
      }
    }
    return this.requestStream({
      method: "sampling/createMessage",
      params
    }, CreateMessageResultSchema, options);
  }
  /**
   * Sends an elicitation request and returns an AsyncGenerator that yields response messages.
   * The generator is guaranteed to end with either a 'result' or 'error' message.
   *
   * For task-augmented requests (especially URL-based elicitation), yields 'taskCreated'
   * and 'taskStatus' messages before the final result.
   *
   * @example
   * ```typescript
   * const stream = server.experimental.tasks.elicitInputStream({
   *     mode: 'url',
   *     message: 'Please authenticate',
   *     elicitationId: 'auth-123',
   *     url: 'https://example.com/auth'
   * }, {
   *     task: { ttl: 300000 } // Task-augmented for long-running auth flow
   * });
   *
   * for await (const message of stream) {
   *     switch (message.type) {
   *         case 'taskCreated':
   *             console.log('Task created:', message.task.taskId);
   *             break;
   *         case 'taskStatus':
   *             console.log('Task status:', message.task.status);
   *             break;
   *         case 'result':
   *             console.log('User action:', message.result.action);
   *             break;
   *         case 'error':
   *             console.error('Error:', message.error);
   *             break;
   *     }
   * }
   * ```
   *
   * @param params - The elicitation request parameters
   * @param options - Optional request options (timeout, signal, task creation params, etc.)
   * @returns AsyncGenerator that yields ResponseMessage objects
   *
   * @experimental
   */
  elicitInputStream(params, options) {
    const clientCapabilities = this._server.getClientCapabilities();
    const mode = params.mode ?? "form";
    switch (mode) {
      case "url": {
        if (!clientCapabilities?.elicitation?.url) {
          throw new Error("Client does not support url elicitation.");
        }
        break;
      }
      case "form": {
        if (!clientCapabilities?.elicitation?.form) {
          throw new Error("Client does not support form elicitation.");
        }
        break;
      }
    }
    const normalizedParams = mode === "form" && params.mode === void 0 ? { ...params, mode: "form" } : params;
    return this.requestStream({
      method: "elicitation/create",
      params: normalizedParams
    }, ElicitResultSchema, options);
  }
  /**
   * Gets the current status of a task.
   *
   * @param taskId - The task identifier
   * @param options - Optional request options
   * @returns The task status
   *
   * @experimental
   */
  async getTask(taskId, options) {
    return this._server.getTask({ taskId }, options);
  }
  /**
   * Retrieves the result of a completed task.
   *
   * @param taskId - The task identifier
   * @param resultSchema - Zod schema for validating the result
   * @param options - Optional request options
   * @returns The task result
   *
   * @experimental
   */
  async getTaskResult(taskId, resultSchema, options) {
    return this._server.getTaskResult({ taskId }, resultSchema, options);
  }
  /**
   * Lists tasks with optional pagination.
   *
   * @param cursor - Optional pagination cursor
   * @param options - Optional request options
   * @returns List of tasks with optional next cursor
   *
   * @experimental
   */
  async listTasks(cursor, options) {
    return this._server.listTasks(cursor ? { cursor } : void 0, options);
  }
  /**
   * Cancels a running task.
   *
   * @param taskId - The task identifier
   * @param options - Optional request options
   *
   * @experimental
   */
  async cancelTask(taskId, options) {
    return this._server.cancelTask({ taskId }, options);
  }
};

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

// node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js
var Server = class extends Protocol {
  /**
   * Initializes this server with the given name and version information.
   */
  constructor(_serverInfo, options) {
    super(options);
    this._serverInfo = _serverInfo;
    this._loggingLevels = /* @__PURE__ */ new Map();
    this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index]));
    this.isMessageIgnored = (level, sessionId) => {
      const currentLevel = this._loggingLevels.get(sessionId);
      return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false;
    };
    this._capabilities = options?.capabilities ?? {};
    this._instructions = options?.instructions;
    this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();
    this.setRequestHandler(InitializeRequestSchema, (request) => this._oninitialize(request));
    this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.());
    if (this._capabilities.logging) {
      this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => {
        const transportSessionId = extra.sessionId || extra.requestInfo?.headers["mcp-session-id"] || void 0;
        const { level } = request.params;
        const parseResult = LoggingLevelSchema.safeParse(level);
        if (parseResult.success) {
          this._loggingLevels.set(transportSessionId, parseResult.data);
        }
        return {};
      });
    }
  }
  /**
   * Access experimental features.
   *
   * WARNING: These APIs are experimental and may change without notice.
   *
   * @experimental
   */
  get experimental() {
    if (!this._experimental) {
      this._experimental = {
        tasks: new ExperimentalServerTasks(this)
      };
    }
    return this._experimental;
  }
  /**
   * Registers new capabilities. This can only be called before connecting to a transport.
   *
   * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
   */
  registerCapabilities(capabilities) {
    if (this.transport) {
      throw new Error("Cannot register capabilities after connecting to transport");
    }
    this._capabilities = mergeCapabilities(this._capabilities, capabilities);
  }
  /**
   * Override request handler registration to enforce server-side validation for tools/call.
   */
  setRequestHandler(requestSchema, handler) {
    const shape = getObjectShape(requestSchema);
    const methodSchema = shape?.method;
    if (!methodSchema) {
      throw new Error("Schema is missing a method literal");
    }
    const methodValue = getLiteralValue(methodSchema);
    if (typeof methodValue !== "string") {
      throw new Error("Schema method literal must be a string");
    }
    const method = methodValue;
    if (method === "tools/call") {
      const wrappedHandler = async (request, extra) => {
        const validatedRequest = safeParse3(CallToolRequestSchema, request);
        if (!validatedRequest.success) {
          const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
          throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`);
        }
        const { params } = validatedRequest.data;
        const result = await Promise.resolve(handler(request, extra));
        if (params.task) {
          const taskValidationResult = safeParse3(CreateTaskResultSchema, result);
          if (!taskValidationResult.success) {
            const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
            throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
          }
          return taskValidationResult.data;
        }
        const validationResult = safeParse3(CallToolResultSchema, result);
        if (!validationResult.success) {
          const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
          throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`);
        }
        return validationResult.data;
      };
      return super.setRequestHandler(requestSchema, wrappedHandler);
    }
    return super.setRequestHandler(requestSchema, handler);
  }
  assertCapabilityForMethod(method) {
    switch (method) {
      case "sampling/createMessage":
        if (!this._clientCapabilities?.sampling) {
          throw new Error(`Client does not support sampling (required for ${method})`);
        }
        break;
      case "elicitation/create":
        if (!this._clientCapabilities?.elicitation) {
          throw new Error(`Client does not support elicitation (required for ${method})`);
        }
        break;
      case "roots/list":
        if (!this._clientCapabilities?.roots) {
          throw new Error(`Client does not support listing roots (required for ${method})`);
        }
        break;
      case "ping":
        break;
    }
  }
  assertNotificationCapability(method) {
    switch (method) {
      case "notifications/message":
        if (!this._capabilities.logging) {
          throw new Error(`Server does not support logging (required for ${method})`);
        }
        break;
      case "notifications/resources/updated":
      case "notifications/resources/list_changed":
        if (!this._capabilities.resources) {
          throw new Error(`Server does not support notifying about resources (required for ${method})`);
        }
        break;
      case "notifications/tools/list_changed":
        if (!this._capabilities.tools) {
          throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);
        }
        break;
      case "notifications/prompts/list_changed":
        if (!this._capabilities.prompts) {
          throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);
        }
        break;
      case "notifications/elicitation/complete":
        if (!this._clientCapabilities?.elicitation?.url) {
          throw new Error(`Client does not support URL elicitation (required for ${method})`);
        }
        break;
      case "notifications/cancelled":
        break;
      case "notifications/progress":
        break;
    }
  }
  assertRequestHandlerCapability(method) {
    if (!this._capabilities) {
      return;
    }
    switch (method) {
      case "completion/complete":
        if (!this._capabilities.completions) {
          throw new Error(`Server does not support completions (required for ${method})`);
        }
        break;
      case "logging/setLevel":
        if (!this._capabilities.logging) {
          throw new Error(`Server does not support logging (required for ${method})`);
        }
        break;
      case "prompts/get":
      case "prompts/list":
        if (!this._capabilities.prompts) {
          throw new Error(`Server does not support prompts (required for ${method})`);
        }
        break;
      case "resources/list":
      case "resources/templates/list":
      case "resources/read":
        if (!this._capabilities.resources) {
          throw new Error(`Server does not support resources (required for ${method})`);
        }
        break;
      case "tools/call":
      case "tools/list":
        if (!this._capabilities.tools) {
          throw new Error(`Server does not support tools (required for ${method})`);
        }
        break;
      case "tasks/get":
      case "tasks/list":
      case "tasks/result":
      case "tasks/cancel":
        if (!this._capabilities.tasks) {
          throw new Error(`Server does not support tasks capability (required for ${method})`);
        }
        break;
      case "ping":
      case "initialize":
        break;
    }
  }
  assertTaskCapability(method) {
    assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, "Client");
  }
  assertTaskHandlerCapability(method) {
    if (!this._capabilities) {
      return;
    }
    assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, "Server");
  }
  async _oninitialize(request) {
    const requestedVersion = request.params.protocolVersion;
    this._clientCapabilities = request.params.capabilities;
    this._clientVersion = request.params.clientInfo;
    const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION;
    return {
      protocolVersion,
      capabilities: this.getCapabilities(),
      serverInfo: this._serverInfo,
      ...this._instructions && { instructions: this._instructions }
    };
  }
  /**
   * After initialization has completed, this will be populated with the client's reported capabilities.
   */
  getClientCapabilities() {
    return this._clientCapabilities;
  }
  /**
   * After initialization has completed, this will be populated with information about the client's name and version.
   */
  getClientVersion() {
    return this._clientVersion;
  }
  getCapabilities() {
    return this._capabilities;
  }
  async ping() {
    return this.request({ method: "ping" }, EmptyResultSchema);
  }
  // Implementation
  async createMessage(params, options) {
    if (params.tools || params.toolChoice) {
      if (!this._clientCapabilities?.sampling?.tools) {
        throw new Error("Client does not support sampling tools capability.");
      }
    }
    if (params.messages.length > 0) {
      const lastMessage = params.messages[params.messages.length - 1];
      const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];
      const hasToolResults = lastContent.some((c) => c.type === "tool_result");
      const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0;
      const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : [];
      const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use");
      if (hasToolResults) {
        if (lastContent.some((c) => c.type !== "tool_result")) {
          throw new Error("The last message must contain only tool_result content if any is present");
        }
        if (!hasPreviousToolUse) {
          throw new Error("tool_result blocks are not matching any tool_use from the previous message");
        }
      }
      if (hasPreviousToolUse) {
        const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id));
        const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId));
        if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) {
          throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match");
        }
      }
    }
    if (params.tools) {
      return this.request({ method: "sampling/createMessage", params }, CreateMessageResultWithToolsSchema, options);
    }
    return this.request({ method: "sampling/createMessage", params }, CreateMessageResultSchema, options);
  }
  /**
   * Creates an elicitation request for the given parameters.
   * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`.
   * @param params The parameters for the elicitation request.
   * @param options Optional request options.
   * @returns The result of the elicitation request.
   */
  async elicitInput(params, options) {
    const mode = params.mode ?? "form";
    switch (mode) {
      case "url": {
        if (!this._clientCapabilities?.elicitation?.url) {
          throw new Error("Client does not support url elicitation.");
        }
        const urlParams = params;
        return this.request({ method: "elicitation/create", params: urlParams }, ElicitResultSchema, options);
      }
      case "form": {
        if (!this._clientCapabilities?.elicitation?.form) {
          throw new Error("Client does not support form elicitation.");
        }
        const formParams = params.mode === "form" ? params : { ...params, mode: "form" };
        const result = await this.request({ method: "elicitation/create", params: formParams }, ElicitResultSchema, options);
        if (result.action === "accept" && result.content && formParams.requestedSchema) {
          try {
            const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema);
            const validationResult = validator(result.content);
            if (!validationResult.valid) {
              throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`);
            }
          } catch (error51) {
            if (error51 instanceof McpError) {
              throw error51;
            }
            throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error51 instanceof Error ? error51.message : String(error51)}`);
          }
        }
        return result;
      }
    }
  }
  /**
   * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete`
   * notification for the specified elicitation ID.
   *
   * @param elicitationId The ID of the elicitation to mark as complete.
   * @param options Optional notification options. Useful when the completion notification should be related to a prior request.
   * @returns A function that emits the completion notification when awaited.
   */
  createElicitationCompletionNotifier(elicitationId, options) {
    if (!this._clientCapabilities?.elicitation?.url) {
      throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");
    }
    return () => this.notification({
      method: "notifications/elicitation/complete",
      params: {
        elicitationId
      }
    }, options);
  }
  async listRoots(params, options) {
    return this.request({ method: "roots/list", params }, ListRootsResultSchema, options);
  }
  /**
   * Sends a logging message to the client, if connected.
   * Note: You only need to send the parameters object, not the entire JSON RPC message
   * @see LoggingMessageNotification
   * @param params
   * @param sessionId optional for stateless and backward compatibility
   */
  async sendLoggingMessage(params, sessionId) {
    if (this._capabilities.logging) {
      if (!this.isMessageIgnored(params.level, sessionId)) {
        return this.notification({ method: "notifications/message", params });
      }
    }
  }
  async sendResourceUpdated(params) {
    return this.notification({
      method: "notifications/resources/updated",
      params
    });
  }
  async sendResourceListChanged() {
    return this.notification({
      method: "notifications/resources/list_changed"
    });
  }
  async sendToolListChanged() {
    return this.notification({ method: "notifications/tools/list_changed" });
  }
  async sendPromptListChanged() {
    return this.notification({ method: "notifications/prompts/list_changed" });
  }
};

// node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js
var COMPLETABLE_SYMBOL = /* @__PURE__ */ Symbol.for("mcp.completable");
function isCompletable(schema) {
  return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema;
}
function getCompleter(schema) {
  const meta3 = schema[COMPLETABLE_SYMBOL];
  return meta3?.complete;
}
var McpZodTypeKind;
(function(McpZodTypeKind2) {
  McpZodTypeKind2["Completable"] = "McpCompletable";
})(McpZodTypeKind || (McpZodTypeKind = {}));

// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.js
var TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/;
function validateToolName(name) {
  const warnings = [];
  if (name.length === 0) {
    return {
      isValid: false,
      warnings: ["Tool name cannot be empty"]
    };
  }
  if (name.length > 128) {
    return {
      isValid: false,
      warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]
    };
  }
  if (name.includes(" ")) {
    warnings.push("Tool name contains spaces, which may cause parsing issues");
  }
  if (name.includes(",")) {
    warnings.push("Tool name contains commas, which may cause parsing issues");
  }
  if (name.startsWith("-") || name.endsWith("-")) {
    warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");
  }
  if (name.startsWith(".") || name.endsWith(".")) {
    warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");
  }
  if (!TOOL_NAME_REGEX.test(name)) {
    const invalidChars = name.split("").filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index);
    warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)");
    return {
      isValid: false,
      warnings
    };
  }
  return {
    isValid: true,
    warnings
  };
}
function issueToolNameWarning(name, warnings) {
  if (warnings.length > 0) {
    console.warn(`Tool name validation warning for "${name}":`);
    for (const warning of warnings) {
      console.warn(`  - ${warning}`);
    }
    console.warn("Tool registration will proceed, but this may cause compatibility issues.");
    console.warn("Consider updating the tool name to conform to the MCP tool naming standard.");
    console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.");
  }
}
function validateAndWarnToolName(name) {
  const result = validateToolName(name);
  issueToolNameWarning(name, result.warnings);
  return result.isValid;
}

// node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.js
var ExperimentalMcpServerTasks = class {
  constructor(_mcpServer) {
    this._mcpServer = _mcpServer;
  }
  registerToolTask(name, config2, handler) {
    const execution = { taskSupport: "required", ...config2.execution };
    if (execution.taskSupport === "forbidden") {
      throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`);
    }
    const mcpServerInternal = this._mcpServer;
    return mcpServerInternal._createRegisteredTool(name, config2.title, config2.description, config2.inputSchema, config2.outputSchema, config2.annotations, execution, config2._meta, handler);
  }
};

// node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js
var McpServer = class {
  constructor(serverInfo, options) {
    this._registeredResources = {};
    this._registeredResourceTemplates = {};
    this._registeredTools = {};
    this._registeredPrompts = {};
    this._toolHandlersInitialized = false;
    this._completionHandlerInitialized = false;
    this._resourceHandlersInitialized = false;
    this._promptHandlersInitialized = false;
    this.server = new Server(serverInfo, options);
  }
  /**
   * Access experimental features.
   *
   * WARNING: These APIs are experimental and may change without notice.
   *
   * @experimental
   */
  get experimental() {
    if (!this._experimental) {
      this._experimental = {
        tasks: new ExperimentalMcpServerTasks(this)
      };
    }
    return this._experimental;
  }
  /**
   * Attaches to the given transport, starts it, and starts listening for messages.
   *
   * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.
   */
  async connect(transport) {
    return await this.server.connect(transport);
  }
  /**
   * Closes the connection.
   */
  async close() {
    await this.server.close();
  }
  setToolRequestHandlers() {
    if (this._toolHandlersInitialized) {
      return;
    }
    this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema));
    this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema));
    this.server.registerCapabilities({
      tools: {
        listChanged: true
      }
    });
    this.server.setRequestHandler(ListToolsRequestSchema, () => ({
      tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => {
        const toolDefinition = {
          name,
          title: tool.title,
          description: tool.description,
          inputSchema: (() => {
            const obj = normalizeObjectSchema(tool.inputSchema);
            return obj ? toJsonSchemaCompat(obj, {
              strictUnions: true,
              pipeStrategy: "input"
            }) : EMPTY_OBJECT_JSON_SCHEMA;
          })(),
          annotations: tool.annotations,
          execution: tool.execution,
          _meta: tool._meta
        };
        if (tool.outputSchema) {
          const obj = normalizeObjectSchema(tool.outputSchema);
          if (obj) {
            toolDefinition.outputSchema = toJsonSchemaCompat(obj, {
              strictUnions: true,
              pipeStrategy: "output"
            });
          }
        }
        return toolDefinition;
      })
    }));
    this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
      try {
        const tool = this._registeredTools[request.params.name];
        if (!tool) {
          throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`);
        }
        if (!tool.enabled) {
          throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`);
        }
        const isTaskRequest = !!request.params.task;
        const taskSupport = tool.execution?.taskSupport;
        const isTaskHandler = "createTask" in tool.handler;
        if ((taskSupport === "required" || taskSupport === "optional") && !isTaskHandler) {
          throw new McpError(ErrorCode.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`);
        }
        if (taskSupport === "required" && !isTaskRequest) {
          throw new McpError(ErrorCode.MethodNotFound, `Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`);
        }
        if (taskSupport === "optional" && !isTaskRequest && isTaskHandler) {
          return await this.handleAutomaticTaskPolling(tool, request, extra);
        }
        const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);
        const result = await this.executeToolHandler(tool, args, extra);
        if (isTaskRequest) {
          return result;
        }
        await this.validateToolOutput(tool, result, request.params.name);
        return result;
      } catch (error51) {
        if (error51 instanceof McpError) {
          if (error51.code === ErrorCode.UrlElicitationRequired) {
            throw error51;
          }
        }
        return this.createToolError(error51 instanceof Error ? error51.message : String(error51));
      }
    });
    this._toolHandlersInitialized = true;
  }
  /**
   * Creates a tool error result.
   *
   * @param errorMessage - The error message.
   * @returns The tool error result.
   */
  createToolError(errorMessage) {
    return {
      content: [
        {
          type: "text",
          text: errorMessage
        }
      ],
      isError: true
    };
  }
  /**
   * Validates tool input arguments against the tool's input schema.
   */
  async validateToolInput(tool, args, toolName) {
    if (!tool.inputSchema) {
      return void 0;
    }
    const inputObj = normalizeObjectSchema(tool.inputSchema);
    const schemaToParse = inputObj ?? tool.inputSchema;
    const parseResult = await safeParseAsync3(schemaToParse, args);
    if (!parseResult.success) {
      const error51 = "error" in parseResult ? parseResult.error : "Unknown error";
      const errorMessage = getParseErrorMessage(error51);
      throw new McpError(ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`);
    }
    return parseResult.data;
  }
  /**
   * Validates tool output against the tool's output schema.
   */
  async validateToolOutput(tool, result, toolName) {
    if (!tool.outputSchema) {
      return;
    }
    if (!("content" in result)) {
      return;
    }
    if (result.isError) {
      return;
    }
    if (!result.structuredContent) {
      throw new McpError(ErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);
    }
    const outputObj = normalizeObjectSchema(tool.outputSchema);
    const parseResult = await safeParseAsync3(outputObj, result.structuredContent);
    if (!parseResult.success) {
      const error51 = "error" in parseResult ? parseResult.error : "Unknown error";
      const errorMessage = getParseErrorMessage(error51);
      throw new McpError(ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`);
    }
  }
  /**
   * Executes a tool handler (either regular or task-based).
   */
  async executeToolHandler(tool, args, extra) {
    const handler = tool.handler;
    const isTaskHandler = "createTask" in handler;
    if (isTaskHandler) {
      if (!extra.taskStore) {
        throw new Error("No task store provided.");
      }
      const taskExtra = { ...extra, taskStore: extra.taskStore };
      if (tool.inputSchema) {
        const typedHandler = handler;
        return await Promise.resolve(typedHandler.createTask(args, taskExtra));
      } else {
        const typedHandler = handler;
        return await Promise.resolve(typedHandler.createTask(taskExtra));
      }
    }
    if (tool.inputSchema) {
      const typedHandler = handler;
      return await Promise.resolve(typedHandler(args, extra));
    } else {
      const typedHandler = handler;
      return await Promise.resolve(typedHandler(extra));
    }
  }
  /**
   * Handles automatic task polling for tools with taskSupport 'optional'.
   */
  async handleAutomaticTaskPolling(tool, request, extra) {
    if (!extra.taskStore) {
      throw new Error("No task store provided for task-capable tool.");
    }
    const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);
    const handler = tool.handler;
    const taskExtra = { ...extra, taskStore: extra.taskStore };
    const createTaskResult = args ? await Promise.resolve(handler.createTask(args, taskExtra)) : (
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      await Promise.resolve(handler.createTask(taskExtra))
    );
    const taskId = createTaskResult.task.taskId;
    let task = createTaskResult.task;
    const pollInterval = task.pollInterval ?? 5e3;
    while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") {
      await new Promise((resolve2) => setTimeout(resolve2, pollInterval));
      const updatedTask = await extra.taskStore.getTask(taskId);
      if (!updatedTask) {
        throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`);
      }
      task = updatedTask;
    }
    return await extra.taskStore.getTaskResult(taskId);
  }
  setCompletionRequestHandler() {
    if (this._completionHandlerInitialized) {
      return;
    }
    this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema));
    this.server.registerCapabilities({
      completions: {}
    });
    this.server.setRequestHandler(CompleteRequestSchema, async (request) => {
      switch (request.params.ref.type) {
        case "ref/prompt":
          assertCompleteRequestPrompt(request);
          return this.handlePromptCompletion(request, request.params.ref);
        case "ref/resource":
          assertCompleteRequestResourceTemplate(request);
          return this.handleResourceCompletion(request, request.params.ref);
        default:
          throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`);
      }
    });
    this._completionHandlerInitialized = true;
  }
  async handlePromptCompletion(request, ref) {
    const prompt = this._registeredPrompts[ref.name];
    if (!prompt) {
      throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`);
    }
    if (!prompt.enabled) {
      throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`);
    }
    if (!prompt.argsSchema) {
      return EMPTY_COMPLETION_RESULT;
    }
    const promptShape = getObjectShape(prompt.argsSchema);
    const field = promptShape?.[request.params.argument.name];
    if (!isCompletable(field)) {
      return EMPTY_COMPLETION_RESULT;
    }
    const completer = getCompleter(field);
    if (!completer) {
      return EMPTY_COMPLETION_RESULT;
    }
    const suggestions = await completer(request.params.argument.value, request.params.context);
    return createCompletionResult(suggestions);
  }
  async handleResourceCompletion(request, ref) {
    const template = Object.values(this._registeredResourceTemplates).find((t2) => t2.resourceTemplate.uriTemplate.toString() === ref.uri);
    if (!template) {
      if (this._registeredResources[ref.uri]) {
        return EMPTY_COMPLETION_RESULT;
      }
      throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`);
    }
    const completer = template.resourceTemplate.completeCallback(request.params.argument.name);
    if (!completer) {
      return EMPTY_COMPLETION_RESULT;
    }
    const suggestions = await completer(request.params.argument.value, request.params.context);
    return createCompletionResult(suggestions);
  }
  setResourceRequestHandlers() {
    if (this._resourceHandlersInitialized) {
      return;
    }
    this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema));
    this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema));
    this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema));
    this.server.registerCapabilities({
      resources: {
        listChanged: true
      }
    });
    this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => {
      const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({
        uri,
        name: resource.name,
        ...resource.metadata
      }));
      const templateResources = [];
      for (const template of Object.values(this._registeredResourceTemplates)) {
        if (!template.resourceTemplate.listCallback) {
          continue;
        }
        const result = await template.resourceTemplate.listCallback(extra);
        for (const resource of result.resources) {
          templateResources.push({
            ...template.metadata,
            // the defined resource metadata should override the template metadata if present
            ...resource
          });
        }
      }
      return { resources: [...resources, ...templateResources] };
    });
    this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {
      const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({
        name,
        uriTemplate: template.resourceTemplate.uriTemplate.toString(),
        ...template.metadata
      }));
      return { resourceTemplates };
    });
    this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {
      const uri = new URL(request.params.uri);
      const resource = this._registeredResources[uri.toString()];
      if (resource) {
        if (!resource.enabled) {
          throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`);
        }
        return resource.readCallback(uri, extra);
      }
      for (const template of Object.values(this._registeredResourceTemplates)) {
        const variables = template.resourceTemplate.uriTemplate.match(uri.toString());
        if (variables) {
          return template.readCallback(uri, variables, extra);
        }
      }
      throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`);
    });
    this._resourceHandlersInitialized = true;
  }
  setPromptRequestHandlers() {
    if (this._promptHandlersInitialized) {
      return;
    }
    this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema));
    this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema));
    this.server.registerCapabilities({
      prompts: {
        listChanged: true
      }
    });
    this.server.setRequestHandler(ListPromptsRequestSchema, () => ({
      prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => {
        return {
          name,
          title: prompt.title,
          description: prompt.description,
          arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : void 0
        };
      })
    }));
    this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => {
      const prompt = this._registeredPrompts[request.params.name];
      if (!prompt) {
        throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`);
      }
      if (!prompt.enabled) {
        throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`);
      }
      if (prompt.argsSchema) {
        const argsObj = normalizeObjectSchema(prompt.argsSchema);
        const parseResult = await safeParseAsync3(argsObj, request.params.arguments);
        if (!parseResult.success) {
          const error51 = "error" in parseResult ? parseResult.error : "Unknown error";
          const errorMessage = getParseErrorMessage(error51);
          throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${errorMessage}`);
        }
        const args = parseResult.data;
        const cb = prompt.callback;
        return await Promise.resolve(cb(args, extra));
      } else {
        const cb = prompt.callback;
        return await Promise.resolve(cb(extra));
      }
    });
    this._promptHandlersInitialized = true;
  }
  resource(name, uriOrTemplate, ...rest) {
    let metadata;
    if (typeof rest[0] === "object") {
      metadata = rest.shift();
    }
    const readCallback = rest[0];
    if (typeof uriOrTemplate === "string") {
      if (this._registeredResources[uriOrTemplate]) {
        throw new Error(`Resource ${uriOrTemplate} is already registered`);
      }
      const registeredResource = this._createRegisteredResource(name, void 0, uriOrTemplate, metadata, readCallback);
      this.setResourceRequestHandlers();
      this.sendResourceListChanged();
      return registeredResource;
    } else {
      if (this._registeredResourceTemplates[name]) {
        throw new Error(`Resource template ${name} is already registered`);
      }
      const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, void 0, uriOrTemplate, metadata, readCallback);
      this.setResourceRequestHandlers();
      this.sendResourceListChanged();
      return registeredResourceTemplate;
    }
  }
  registerResource(name, uriOrTemplate, config2, readCallback) {
    if (typeof uriOrTemplate === "string") {
      if (this._registeredResources[uriOrTemplate]) {
        throw new Error(`Resource ${uriOrTemplate} is already registered`);
      }
      const registeredResource = this._createRegisteredResource(name, config2.title, uriOrTemplate, config2, readCallback);
      this.setResourceRequestHandlers();
      this.sendResourceListChanged();
      return registeredResource;
    } else {
      if (this._registeredResourceTemplates[name]) {
        throw new Error(`Resource template ${name} is already registered`);
      }
      const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config2.title, uriOrTemplate, config2, readCallback);
      this.setResourceRequestHandlers();
      this.sendResourceListChanged();
      return registeredResourceTemplate;
    }
  }
  _createRegisteredResource(name, title, uri, metadata, readCallback) {
    const registeredResource = {
      name,
      title,
      metadata,
      readCallback,
      enabled: true,
      disable: () => registeredResource.update({ enabled: false }),
      enable: () => registeredResource.update({ enabled: true }),
      remove: () => registeredResource.update({ uri: null }),
      update: (updates) => {
        if (typeof updates.uri !== "undefined" && updates.uri !== uri) {
          delete this._registeredResources[uri];
          if (updates.uri)
            this._registeredResources[updates.uri] = registeredResource;
        }
        if (typeof updates.name !== "undefined")
          registeredResource.name = updates.name;
        if (typeof updates.title !== "undefined")
          registeredResource.title = updates.title;
        if (typeof updates.metadata !== "undefined")
          registeredResource.metadata = updates.metadata;
        if (typeof updates.callback !== "undefined")
          registeredResource.readCallback = updates.callback;
        if (typeof updates.enabled !== "undefined")
          registeredResource.enabled = updates.enabled;
        this.sendResourceListChanged();
      }
    };
    this._registeredResources[uri] = registeredResource;
    return registeredResource;
  }
  _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) {
    const registeredResourceTemplate = {
      resourceTemplate: template,
      title,
      metadata,
      readCallback,
      enabled: true,
      disable: () => registeredResourceTemplate.update({ enabled: false }),
      enable: () => registeredResourceTemplate.update({ enabled: true }),
      remove: () => registeredResourceTemplate.update({ name: null }),
      update: (updates) => {
        if (typeof updates.name !== "undefined" && updates.name !== name) {
          delete this._registeredResourceTemplates[name];
          if (updates.name)
            this._registeredResourceTemplates[updates.name] = registeredResourceTemplate;
        }
        if (typeof updates.title !== "undefined")
          registeredResourceTemplate.title = updates.title;
        if (typeof updates.template !== "undefined")
          registeredResourceTemplate.resourceTemplate = updates.template;
        if (typeof updates.metadata !== "undefined")
          registeredResourceTemplate.metadata = updates.metadata;
        if (typeof updates.callback !== "undefined")
          registeredResourceTemplate.readCallback = updates.callback;
        if (typeof updates.enabled !== "undefined")
          registeredResourceTemplate.enabled = updates.enabled;
        this.sendResourceListChanged();
      }
    };
    this._registeredResourceTemplates[name] = registeredResourceTemplate;
    const variableNames = template.uriTemplate.variableNames;
    const hasCompleter = Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v));
    if (hasCompleter) {
      this.setCompletionRequestHandler();
    }
    return registeredResourceTemplate;
  }
  _createRegisteredPrompt(name, title, description, argsSchema, callback) {
    const registeredPrompt = {
      title,
      description,
      argsSchema: argsSchema === void 0 ? void 0 : objectFromShape(argsSchema),
      callback,
      enabled: true,
      disable: () => registeredPrompt.update({ enabled: false }),
      enable: () => registeredPrompt.update({ enabled: true }),
      remove: () => registeredPrompt.update({ name: null }),
      update: (updates) => {
        if (typeof updates.name !== "undefined" && updates.name !== name) {
          delete this._registeredPrompts[name];
          if (updates.name)
            this._registeredPrompts[updates.name] = registeredPrompt;
        }
        if (typeof updates.title !== "undefined")
          registeredPrompt.title = updates.title;
        if (typeof updates.description !== "undefined")
          registeredPrompt.description = updates.description;
        if (typeof updates.argsSchema !== "undefined")
          registeredPrompt.argsSchema = objectFromShape(updates.argsSchema);
        if (typeof updates.callback !== "undefined")
          registeredPrompt.callback = updates.callback;
        if (typeof updates.enabled !== "undefined")
          registeredPrompt.enabled = updates.enabled;
        this.sendPromptListChanged();
      }
    };
    this._registeredPrompts[name] = registeredPrompt;
    if (argsSchema) {
      const hasCompletable = Object.values(argsSchema).some((field) => {
        const inner = field instanceof ZodOptional ? field._def?.innerType : field;
        return isCompletable(inner);
      });
      if (hasCompletable) {
        this.setCompletionRequestHandler();
      }
    }
    return registeredPrompt;
  }
  _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, execution, _meta, handler) {
    validateAndWarnToolName(name);
    const registeredTool = {
      title,
      description,
      inputSchema: getZodSchemaObject(inputSchema),
      outputSchema: getZodSchemaObject(outputSchema),
      annotations,
      execution,
      _meta,
      handler,
      enabled: true,
      disable: () => registeredTool.update({ enabled: false }),
      enable: () => registeredTool.update({ enabled: true }),
      remove: () => registeredTool.update({ name: null }),
      update: (updates) => {
        if (typeof updates.name !== "undefined" && updates.name !== name) {
          if (typeof updates.name === "string") {
            validateAndWarnToolName(updates.name);
          }
          delete this._registeredTools[name];
          if (updates.name)
            this._registeredTools[updates.name] = registeredTool;
        }
        if (typeof updates.title !== "undefined")
          registeredTool.title = updates.title;
        if (typeof updates.description !== "undefined")
          registeredTool.description = updates.description;
        if (typeof updates.paramsSchema !== "undefined")
          registeredTool.inputSchema = objectFromShape(updates.paramsSchema);
        if (typeof updates.outputSchema !== "undefined")
          registeredTool.outputSchema = objectFromShape(updates.outputSchema);
        if (typeof updates.callback !== "undefined")
          registeredTool.handler = updates.callback;
        if (typeof updates.annotations !== "undefined")
          registeredTool.annotations = updates.annotations;
        if (typeof updates._meta !== "undefined")
          registeredTool._meta = updates._meta;
        if (typeof updates.enabled !== "undefined")
          registeredTool.enabled = updates.enabled;
        this.sendToolListChanged();
      }
    };
    this._registeredTools[name] = registeredTool;
    this.setToolRequestHandlers();
    this.sendToolListChanged();
    return registeredTool;
  }
  /**
   * tool() implementation. Parses arguments passed to overrides defined above.
   */
  tool(name, ...rest) {
    if (this._registeredTools[name]) {
      throw new Error(`Tool ${name} is already registered`);
    }
    let description;
    let inputSchema;
    let outputSchema;
    let annotations;
    if (typeof rest[0] === "string") {
      description = rest.shift();
    }
    if (rest.length > 1) {
      const firstArg = rest[0];
      if (isZodRawShapeCompat(firstArg)) {
        inputSchema = rest.shift();
        if (rest.length > 1 && typeof rest[0] === "object" && rest[0] !== null && !isZodRawShapeCompat(rest[0])) {
          annotations = rest.shift();
        }
      } else if (typeof firstArg === "object" && firstArg !== null) {
        if (Object.values(firstArg).some((v) => typeof v === "object" && v !== null)) {
          throw new Error(`Tool ${name} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);
        }
        annotations = rest.shift();
      }
    }
    const callback = rest[0];
    return this._createRegisteredTool(name, void 0, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, void 0, callback);
  }
  /**
   * Registers a tool with a config object and callback.
   */
  registerTool(name, config2, cb) {
    if (this._registeredTools[name]) {
      throw new Error(`Tool ${name} is already registered`);
    }
    const { title, description, inputSchema, outputSchema, annotations, _meta } = config2;
    return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, _meta, cb);
  }
  prompt(name, ...rest) {
    if (this._registeredPrompts[name]) {
      throw new Error(`Prompt ${name} is already registered`);
    }
    let description;
    if (typeof rest[0] === "string") {
      description = rest.shift();
    }
    let argsSchema;
    if (rest.length > 1) {
      argsSchema = rest.shift();
    }
    const cb = rest[0];
    const registeredPrompt = this._createRegisteredPrompt(name, void 0, description, argsSchema, cb);
    this.setPromptRequestHandlers();
    this.sendPromptListChanged();
    return registeredPrompt;
  }
  /**
   * Registers a prompt with a config object and callback.
   */
  registerPrompt(name, config2, cb) {
    if (this._registeredPrompts[name]) {
      throw new Error(`Prompt ${name} is already registered`);
    }
    const { title, description, argsSchema } = config2;
    const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb);
    this.setPromptRequestHandlers();
    this.sendPromptListChanged();
    return registeredPrompt;
  }
  /**
   * Checks if the server is connected to a transport.
   * @returns True if the server is connected
   */
  isConnected() {
    return this.server.transport !== void 0;
  }
  /**
   * Sends a logging message to the client, if connected.
   * Note: You only need to send the parameters object, not the entire JSON RPC message
   * @see LoggingMessageNotification
   * @param params
   * @param sessionId optional for stateless and backward compatibility
   */
  async sendLoggingMessage(params, sessionId) {
    return this.server.sendLoggingMessage(params, sessionId);
  }
  /**
   * Sends a resource list changed event to the client, if connected.
   */
  sendResourceListChanged() {
    if (this.isConnected()) {
      this.server.sendResourceListChanged();
    }
  }
  /**
   * Sends a tool list changed event to the client, if connected.
   */
  sendToolListChanged() {
    if (this.isConnected()) {
      this.server.sendToolListChanged();
    }
  }
  /**
   * Sends a prompt list changed event to the client, if connected.
   */
  sendPromptListChanged() {
    if (this.isConnected()) {
      this.server.sendPromptListChanged();
    }
  }
};
var EMPTY_OBJECT_JSON_SCHEMA = {
  type: "object",
  properties: {}
};
function isZodTypeLike(value) {
  return value !== null && typeof value === "object" && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
}
function isZodSchemaInstance(obj) {
  return "_def" in obj || "_zod" in obj || isZodTypeLike(obj);
}
function isZodRawShapeCompat(obj) {
  if (typeof obj !== "object" || obj === null) {
    return false;
  }
  if (isZodSchemaInstance(obj)) {
    return false;
  }
  if (Object.keys(obj).length === 0) {
    return true;
  }
  return Object.values(obj).some(isZodTypeLike);
}
function getZodSchemaObject(schema) {
  if (!schema) {
    return void 0;
  }
  if (isZodRawShapeCompat(schema)) {
    return objectFromShape(schema);
  }
  if (!isZodSchemaInstance(schema)) {
    throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");
  }
  return schema;
}
function promptArgumentsFromSchema(schema) {
  const shape = getObjectShape(schema);
  if (!shape)
    return [];
  return Object.entries(shape).map(([name, field]) => {
    const description = getSchemaDescription(field);
    const isOptional = isSchemaOptional(field);
    return {
      name,
      description,
      required: !isOptional
    };
  });
}
function getMethodValue(schema) {
  const shape = getObjectShape(schema);
  const methodSchema = shape?.method;
  if (!methodSchema) {
    throw new Error("Schema is missing a method literal");
  }
  const value = getLiteralValue(methodSchema);
  if (typeof value === "string") {
    return value;
  }
  throw new Error("Schema method literal must be a string");
}
function createCompletionResult(suggestions) {
  return {
    completion: {
      values: suggestions.slice(0, 100),
      total: suggestions.length,
      hasMore: suggestions.length > 100
    }
  };
}
var EMPTY_COMPLETION_RESULT = {
  completion: {
    values: [],
    hasMore: false
  }
};

// node_modules/@kirbah/mcp-youtube/dist/utils/errorHandler.js
var formatError2 = (error51) => {
  if (error51 instanceof AppError) {
    const errorResponse2 = {
      error: error51.name,
      message: error51.message,
      details: error51.details
    };
    return {
      success: false,
      error: errorResponse2,
      content: []
    };
  }
  const errorMessage = error51 instanceof Error ? error51.message : "An unknown error occurred";
  const errorResponse = {
    error: "ToolExecutionError",
    message: errorMessage
  };
  return {
    success: false,
    error: errorResponse,
    content: []
  };
};

// node_modules/@kirbah/mcp-youtube/dist/tools/base.js
var BaseTool = class {
  container;
  // Dependencies are injected automatically via constructor
  constructor(container2) {
    this.container = container2;
  }
  // Public entry point that handles error catching and logging
  async execute(params) {
    try {
      const validatedParams = await this.schema.parseAsync(params);
      return await this.executeImpl(validatedParams);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : String(err);
      console.error(`Tool execution failed: ${this.name}`, {
        error: errorMessage
      });
      return {
        content: [{ type: "text", text: `Error: ${errorMessage}` }],
        isError: true
      };
    }
  }
  // Helper to format the tool for the MCP SDK registration
  getDefinition() {
    return {
      description: this.description,
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      inputSchema: this.schema
    };
  }
};

// node_modules/@kirbah/mcp-youtube/dist/utils/validation.js
var videoIdSchema = external_exports.string().min(1, "Video ID cannot be empty");
var channelIdSchema = external_exports.string().min(1, "Channel ID cannot be empty");
var maxResultsSchema = external_exports.number().min(1).max(500).optional();
var querySchema = external_exports.string().min(1, "Query cannot be empty");
var languageSchema = external_exports.string().optional();
var regionCodeSchema = external_exports.string().length(2, "Region code must be 2 characters").optional();
var categoryIdSchema = external_exports.string().optional();

// node_modules/@kirbah/mcp-youtube/dist/utils/responseFormatter.js
var formatSuccess = (data) => {
  return {
    success: true,
    content: [{ type: "text", text: JSON.stringify(data, null, 2) }]
  };
};
var formatVideoMap = (videoIds, results) => {
  return videoIds.reduce((acc, videoId, index) => {
    acc[videoId] = results[index];
    return acc;
  }, {});
};

// node_modules/@kirbah/mcp-youtube/dist/tools/video/getVideoDetails.js
var getVideoDetailsSchema = external_exports.object({
  videoIds: external_exports.array(videoIdSchema).describe("Array of YouTube video IDs to get details for"),
  includeTags: external_exports.boolean().optional().default(false).describe("Specify 'true' to include the video's 'tags' array in the response, which is useful for extracting niche keywords. The 'tags' are omitted by default to conserve tokens."),
  descriptionDetail: external_exports.enum(["NONE", "SNIPPET", "LONG"]).optional().default("NONE").describe("Controls video description detail to manage token cost. Options: 'NONE' (default, no text), 'SNIPPET' (a brief preview for broad scans), 'LONG' (a 500-char text for deep analysis of specific targets).")
});
var GetVideoDetailsTool = class extends BaseTool {
  name = "getVideoDetails";
  description = "Get detailed information about multiple YouTube videos. Returns comprehensive data including video metadata, statistics, and content details. Use this when you need complete information about specific videos.";
  schema = getVideoDetailsSchema;
  async executeImpl(params) {
    const videoPromises = params.videoIds.map(async (videoId) => {
      const fullVideoDetails = await this.container.youtubeService.getVideo({
        videoId,
        parts: ["snippet", "statistics", "contentDetails"]
      });
      if (!fullVideoDetails) {
        return { [videoId]: null };
      }
      const viewCount = parseYouTubeNumber(fullVideoDetails.statistics?.viewCount);
      const likeCount = parseYouTubeNumber(fullVideoDetails.statistics?.likeCount);
      const commentCount = parseYouTubeNumber(fullVideoDetails.statistics?.commentCount);
      const formattedDescription = formatDescription(fullVideoDetails.snippet?.description, params.descriptionDetail);
      const baseLeanDetails = {
        id: fullVideoDetails.id ?? null,
        title: fullVideoDetails.snippet?.title ?? null,
        channelId: fullVideoDetails.snippet?.channelId ?? null,
        channelTitle: fullVideoDetails.snippet?.channelTitle ?? null,
        publishedAt: fullVideoDetails.snippet?.publishedAt ?? null,
        duration: fullVideoDetails.contentDetails?.duration ?? null,
        viewCount,
        likeCount,
        commentCount,
        likeToViewRatio: calculateLikeToViewRatio(viewCount, likeCount),
        commentToViewRatio: calculateCommentToViewRatio(viewCount, commentCount),
        categoryId: fullVideoDetails.snippet?.categoryId ?? null,
        defaultLanguage: fullVideoDetails.snippet?.defaultLanguage ?? null
      };
      const detailsWithDescription = formattedDescription !== void 0 ? { ...baseLeanDetails, description: formattedDescription } : baseLeanDetails;
      const leanDetails = params.includeTags ? {
        ...detailsWithDescription,
        tags: fullVideoDetails.snippet?.tags ?? []
      } : detailsWithDescription;
      return { [videoId]: leanDetails };
    });
    const results = await Promise.all(videoPromises);
    const finalOutput = results.reduce((acc, current) => ({ ...acc, ...current }), {});
    return formatSuccess(finalOutput);
  }
};

// node_modules/@kirbah/mcp-youtube/dist/tools/video/searchVideos.js
var searchVideosSchema = external_exports.object({
  query: querySchema.describe("Search query string to find videos"),
  maxResults: maxResultsSchema.optional().default(10).describe("Maximum number of results to return (1-500, default: 10)"),
  order: external_exports.enum(["relevance", "date", "viewCount"]).optional().describe("Sort order for results (default: relevance)"),
  type: external_exports.enum(["video", "channel"]).optional().describe("Type of content to search for (default: video)"),
  channelId: external_exports.string().optional().describe("Restrict search to specific channel ID"),
  videoDuration: external_exports.enum(["any", "short", "medium", "long"]).optional().describe("Filter by video duration. 'any' (default): no duration filter. 'short': videos less than 4 minutes. 'medium': videos 4 to 20 minutes. 'long': videos longer than 20 minutes."),
  recency: external_exports.enum([
    "any",
    "pastHour",
    "pastDay",
    "pastWeek",
    "pastMonth",
    "pastQuarter",
    "pastYear"
  ]).optional().describe("Filter by recency. Possible values: 'any', 'pastHour', 'pastDay', 'pastWeek', 'pastMonth', 'pastQuarter', 'pastYear'."),
  regionCode: external_exports.string().length(2).optional().describe("2-letter country code to restrict results")
});
var SearchVideosTool = class extends BaseTool {
  name = "searchVideos";
  description = "Universal search tool for YouTube content. Use this to find **videos** (default) or **channels**. To find a specific content creator, you MUST set `type` to 'channel'. Supports filtering by `recency` (e.g., 'pastWeek') and `videoDuration`. Returns `videoId` or `channelId` needed for other tools.";
  schema = searchVideosSchema;
  async executeImpl(params) {
    const rawResults = await this.container.youtubeService.searchVideos(params);
    const leanResults = rawResults.map((result) => ({
      videoId: result.id?.videoId ?? null,
      title: result.snippet?.title ?? null,
      descriptionSnippet: result.snippet?.description ?? null,
      channelId: result.snippet?.channelId ?? null,
      channelTitle: result.snippet?.channelTitle ?? null,
      publishedAt: result.snippet?.publishedAt ?? null
    }));
    return formatSuccess(leanResults);
  }
};

// node_modules/@kirbah/mcp-youtube/dist/tools/video/getTranscripts.js
var getTranscriptsSchema = external_exports.object({
  videoIds: external_exports.array(videoIdSchema).describe("Array of YouTube video IDs to get transcripts for"),
  lang: languageSchema.default("en").describe("Language code for transcripts (e.g., 'en', 'ko', 'es'). Defaults to environment setting or 'en'"),
  format: external_exports.enum(["full_text", "key_segments"]).default("key_segments").describe("The desired transcript format. 'full_text': Returns the entire transcript as a single string. 'key_segments': (Default) Returns only the video's intro hook and final call to action.")
});
var GetTranscriptsTool = class extends BaseTool {
  name = "getTranscripts";
  description = "Retrieves specific, meaningful segments of a video's transcript. By default, it returns the intro 'hook' and the final 'outro' or call to action. It can also return the full transcript text. Use this to efficiently analyze a video's key messaging.";
  schema = getTranscriptsSchema;
  async executeImpl(params) {
    const { videoIds, lang, format } = params;
    const transcriptPromises = videoIds.map((videoId) => this.container.transcriptService.getTranscriptSegments(videoId, lang, format));
    const transcripts = await Promise.all(transcriptPromises);
    const result = formatVideoMap(videoIds, transcripts);
    return formatSuccess(result);
  }
};

// node_modules/@kirbah/mcp-youtube/dist/tools/video/getVideoComments.js
var getVideoCommentsSchema = external_exports.object({
  videoId: external_exports.string().min(1).describe("The 11-character ID of the YouTube video."),
  maxResults: external_exports.number().min(1).max(100).default(20).describe("Max number of top-level comments to return (1-100, default: 20)."),
  order: external_exports.enum(["relevance", "time"]).default("relevance").describe("Sort order for comments. Use 'relevance' (default) for most helpful or 'time' for newest."),
  maxReplies: external_exports.number().min(0).max(5).default(0).describe("Max replies per comment to return (0-5, default: 0). Use 0 for best performance."),
  commentDetail: external_exports.enum(["SNIPPET", "FULL"]).default("SNIPPET").describe("Detail level for comment text. 'SNIPPET' (default, 200 chars) or 'FULL' (entire text).")
});
var GetVideoCommentsTool = class extends BaseTool {
  name = "getVideoComments";
  description = "Retrieves comments for a video. Warning: Setting `maxReplies` > 0 significantly increases API cost. Only set `maxReplies` if you specifically need to analyze conversation threads. Defaults to top-level comments only.";
  schema = getVideoCommentsSchema;
  async executeImpl(params) {
    const comments = await this.container.youtubeService.getVideoComments(params);
    return formatSuccess(comments);
  }
};

// node_modules/@kirbah/mcp-youtube/dist/tools/channel/getChannelStatistics.js
var getChannelStatisticsSchema = external_exports.object({
  channelIds: external_exports.array(channelIdSchema).min(1, "Channel IDs array must contain at least 1 element(s)").describe("Array of YouTube channel IDs to get statistics for")
});
var GetChannelStatisticsTool = class extends BaseTool {
  name = "getChannelStatistics";
  description = "Retrieves statistics for multiple channels. Returns detailed metrics including subscriber count, view count, video count, and channel creation date for each channel. Use this when you need to analyze the performance and reach of multiple YouTube channels.";
  schema = getChannelStatisticsSchema;
  async executeImpl(params) {
    const statsPromises = params.channelIds.map((channelId) => this.container.youtubeService.getChannelStatistics(channelId));
    const statisticsResults = await Promise.all(statsPromises);
    return formatSuccess(statisticsResults);
  }
};

// node_modules/@kirbah/mcp-youtube/dist/tools/channel/getChannelTopVideos.js
var getChannelTopVideosSchema = external_exports.object({
  channelId: channelIdSchema.describe("YouTube channel ID to get top videos from"),
  maxResults: maxResultsSchema.optional().default(10).describe("Maximum number of top videos to return (1-500, default: 10)"),
  includeTags: external_exports.boolean().optional().default(false).describe("Specify 'true' to include the video's 'tags' array in the response, which is useful for extracting niche keywords. The 'tags' are omitted by default to conserve tokens."),
  descriptionDetail: external_exports.enum(["NONE", "SNIPPET", "LONG"]).optional().default("NONE").describe("Controls video description detail to manage token cost. Options: 'NONE' (default, no text), 'SNIPPET' (a brief preview for broad scans), 'LONG' (a 500-char text for deep analysis of specific targets).")
});
var GetChannelTopVideosTool = class extends BaseTool {
  name = "getChannelTopVideos";
  description = "Retrieves a channel's most popular videos. CRITICAL: Requires a valid `channelId` (starting with 'UC...'), NOT a channel handle or name. Use `searchVideos` (type='channel') first to find the `channelId` if you only have a name.";
  schema = getChannelTopVideosSchema;
  async executeImpl(params) {
    const topVideos = await this.container.youtubeService.getChannelTopVideos(params);
    return formatSuccess(topVideos);
  }
};

// node_modules/@kirbah/mcp-youtube/dist/tools/general/getTrendingVideos.js
var getTrendingVideosSchema = external_exports.object({
  regionCode: regionCodeSchema.default("US").describe("Two-letter country code (e.g., 'US', 'GB', 'JP'). Defaults to 'US'"),
  categoryId: categoryIdSchema.describe("YouTube category ID to filter trending videos by category. Use getVideoCategories tool to get available category IDs."),
  // categoryId is optional and has no default
  maxResults: maxResultsSchema.default(10).describe("Maximum number of trending videos to return (1-500, default: 10)")
});
var GetTrendingVideosTool = class extends BaseTool {
  name = "getTrendingVideos";
  description = "Retrieves trending videos based on region and category. Returns a list of videos that are currently popular in the specified region and category. Use this when you want to discover what's trending in specific areas or categories. To get available category IDs and their names, use the getVideoCategories tool first.";
  schema = getTrendingVideosSchema;
  async executeImpl(params) {
    const trendingVideos = await this.container.youtubeService.getTrendingVideos(params);
    return formatSuccess(trendingVideos);
  }
};

// node_modules/@kirbah/mcp-youtube/dist/tools/general/getVideoCategories.js
var getVideoCategoriesSchema = external_exports.object({
  regionCode: regionCodeSchema.default("US").describe("Two-letter country code (e.g., 'US', 'GB', 'JP'). Defaults to 'US'")
});
var GetVideoCategoriesTool = class extends BaseTool {
  name = "getVideoCategories";
  description = "Retrieves available video categories for a specific region. Returns a list of YouTube video categories with their IDs and titles that can be used for filtering trending videos or other category-specific operations. Different regions may have different available categories.";
  schema = getVideoCategoriesSchema;
  async executeImpl(params) {
    const { regionCode } = params;
    const categories = await this.container.youtubeService.getVideoCategories(regionCode);
    return formatSuccess(categories);
  }
};

// node_modules/@kirbah/mcp-youtube/dist/services/analysis/analysis.logic.js
var STALENESS_DAYS_NEW = 14;
var STALENESS_DAYS_ESTABLISHED = 45;
var MIN_AVG_VIEWS_THRESHOLD = 1e3;
var MAX_SUBSCRIBER_CAP = 1e5;
var MIN_SUBSCRIBER_THRESHOLD = 1e3;
var MIN_OUTLIER_VIEW_COUNT = 1e3;
var MIN_VIDEO_DURATION_SECONDS = 180;
function isQuotaError(error51) {
  if (typeof error51 !== "object" || error51 === null) {
    return false;
  }
  const err = error51;
  if (err.code === 403) {
    return true;
  }
  if (err.errors && Array.isArray(err.errors)) {
    return err.errors.some((e2) => e2.reason === "quotaExceeded");
  }
  return false;
}
function calculateChannelAgePublishedAfter(channelAge) {
  const targetDate = /* @__PURE__ */ new Date();
  const monthsToSubtract = channelAge === "NEW" ? 6 : 24;
  targetDate.setDate(1);
  targetDate.setMonth(targetDate.getMonth() - monthsToSubtract);
  targetDate.setUTCHours(0, 0, 0, 0);
  return targetDate.toISOString();
}
function getOutlierMultiplier(outlierMagnitude) {
  return outlierMagnitude === "STANDARD" ? 1 : 3;
}
function getConsistencyThreshold(consistencyLevel) {
  return consistencyLevel === "MODERATE" ? 30 : 50;
}
function applyStalnessHeuristic(channel, channelAge) {
  if (!channel.latestAnalysis) {
    return true;
  }
  const now = /* @__PURE__ */ new Date();
  const analysisAge = now.getTime() - channel.latestAnalysis.analyzedAt.getTime();
  const staleDays = channelAge === "NEW" ? STALENESS_DAYS_NEW : STALENESS_DAYS_ESTABLISHED;
  const staleThreshold = staleDays * 24 * 60 * 60 * 1e3;
  return analysisAge > staleThreshold;
}
function calculateDerivedMetrics(channel) {
  const avgViews = channel.latestStats?.videoCount > 0 ? channel.latestStats.viewCount / channel.latestStats.videoCount : 0;
  const engagementRatio = channel.latestStats?.subscriberCount > 0 ? channel.latestStats.viewCount / channel.latestStats.subscriberCount : 0;
  return {
    historicalAvgViewsPerVideo: avgViews,
    libraryEngagementRatio: engagementRatio
  };
}
function calculateChannelAge(createdAt) {
  const now = /* @__PURE__ */ new Date();
  const ageInMs = now.getTime() - createdAt.getTime();
  return ageInMs / (1e3 * 60 * 60 * 24 * 30);
}
function isValidChannelAge(ageInMonths, channelAge) {
  if (channelAge === "NEW") {
    return ageInMonths <= 6;
  } else {
    return ageInMonths >= 6 && ageInMonths <= 24;
  }
}
function parseISO8601Duration(duration3) {
  const regex = /PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/;
  const matches = duration3.match(regex);
  if (!matches) {
    return 0;
  }
  const hours = parseInt(matches[1] || "0", 10);
  const minutes = parseInt(matches[2] || "0", 10);
  const seconds = parseInt(matches[3] || "0", 10);
  return hours * 3600 + minutes * 60 + seconds;
}
function calculateConsistencyMetrics(videos, subscriberCount) {
  if (videos.length === 0) {
    return {
      sourceVideoCount: 0,
      metrics: {
        STANDARD: { outlierVideoCount: 0, consistencyPercentage: 0 },
        STRONG: { outlierVideoCount: 0, consistencyPercentage: 0 }
      }
    };
  }
  let longFormVideoCount = 0;
  let standardOutlierCount = 0;
  let strongOutlierCount = 0;
  const standardThreshold = subscriberCount * getOutlierMultiplier("STANDARD");
  const strongThreshold = subscriberCount * getOutlierMultiplier("STRONG");
  for (const video of videos) {
    if (!video.contentDetails?.duration) {
      continue;
    }
    const durationInSeconds = parseISO8601Duration(video.contentDetails.duration);
    if (durationInSeconds < MIN_VIDEO_DURATION_SECONDS) {
      continue;
    }
    if (!video.statistics?.viewCount) {
      continue;
    }
    longFormVideoCount++;
    const viewCount = parseInt(video.statistics.viewCount);
    if (viewCount > standardThreshold && viewCount > MIN_OUTLIER_VIEW_COUNT) {
      standardOutlierCount++;
    }
    if (viewCount > strongThreshold && viewCount > MIN_OUTLIER_VIEW_COUNT) {
      strongOutlierCount++;
    }
  }
  const standardConsistencyPercentage = longFormVideoCount > 0 ? standardOutlierCount / longFormVideoCount * 100 : 0;
  const strongConsistencyPercentage = longFormVideoCount > 0 ? strongOutlierCount / longFormVideoCount * 100 : 0;
  return {
    sourceVideoCount: longFormVideoCount,
    metrics: {
      STANDARD: {
        outlierVideoCount: standardOutlierCount,
        consistencyPercentage: standardConsistencyPercentage
      },
      STRONG: {
        outlierVideoCount: strongOutlierCount,
        consistencyPercentage: strongConsistencyPercentage
      }
    }
  };
}

// node_modules/@kirbah/mcp-youtube/dist/services/analysis/phase1-candidate-search.js
async function executeInitialCandidateSearch(options, youtubeService) {
  try {
    const publishedAfter = calculateChannelAgePublishedAfter(options.channelAge);
    const searchResults = await youtubeService.searchVideos({
      query: options.query,
      publishedAfter,
      type: "video",
      order: "relevance",
      maxResults: 50,
      regionCode: options.regionCode,
      videoCategoryId: options.videoCategoryId
    });
    const channelIds = /* @__PURE__ */ new Set();
    for (const video of searchResults) {
      if (video.snippet?.channelId) {
        channelIds.add(video.snippet.channelId);
      }
    }
    return Array.from(channelIds);
  } catch (error51) {
    if (error51 instanceof AppError)
      throw error51;
    if (isQuotaError(error51)) {
      throw new Error("YouTube API quota exceeded during Phase 1.", {
        cause: error51
      });
    }
    const message = error51 instanceof Error ? error51.message : "An unknown error occurred";
    throw new Error(`Phase 1 failed: ${message}`, { cause: error51 });
  }
}

// node_modules/@kirbah/mcp-youtube/dist/services/analysis/phase2-channel-filtering.js
var MIN_VIDEOS_FOR_ANALYSIS = 10;
async function executeChannelPreFiltering(channelIds, options, youtubeService, nicheRepository) {
  try {
    const prospectsForPhase3 = [];
    const needsStatsFetch = [];
    const cachedChannels = await nicheRepository.findChannelsByIds(channelIds);
    const cachedChannelMap = /* @__PURE__ */ new Map();
    for (const channel of cachedChannels) {
      cachedChannelMap.set(channel._id, channel);
    }
    for (const channelId of channelIds) {
      const cachedChannel = cachedChannelMap.get(channelId);
      if (!cachedChannel) {
        needsStatsFetch.push(channelId);
      } else {
        const isStale = applyStalnessHeuristic(cachedChannel, options.channelAge);
        if (isStale) {
          needsStatsFetch.push(channelId);
        }
      }
    }
    let freshChannelStats = /* @__PURE__ */ new Map();
    if (needsStatsFetch.length > 0) {
      freshChannelStats = await youtubeService.batchFetchChannelStatistics(needsStatsFetch);
    }
    for (const channelId of channelIds) {
      let channelData = cachedChannelMap.get(channelId);
      const freshStats = freshChannelStats.get(channelId);
      if (freshStats) {
        const now = /* @__PURE__ */ new Date();
        const channelCreatedAt = freshStats.snippet?.publishedAt ? new Date(freshStats.snippet.publishedAt) : now;
        const updatedChannel = {
          _id: channelId,
          channelTitle: freshStats.snippet?.title || "Unknown Channel",
          createdAt: channelCreatedAt,
          status: channelData?.status || "candidate",
          latestStats: {
            fetchedAt: now,
            subscriberCount: parseInt(freshStats.statistics?.subscriberCount || "0"),
            videoCount: parseInt(freshStats.statistics?.videoCount || "0"),
            viewCount: parseInt(freshStats.statistics?.viewCount || "0")
          },
          latestAnalysis: channelData?.latestAnalysis,
          analysisHistory: channelData?.analysisHistory || []
        };
        await nicheRepository.updateChannel(channelId, {
          $set: updatedChannel
        });
        channelData = updatedChannel;
      }
      if (!channelData) {
        continue;
      }
      if (channelData.latestStats.subscriberCount > MAX_SUBSCRIBER_CAP) {
        await nicheRepository.updateChannel(channelId, {
          $set: { status: "archived_too_large" }
        });
        continue;
      }
      if (channelData.latestStats.subscriberCount < MIN_SUBSCRIBER_THRESHOLD) {
        await nicheRepository.updateChannel(channelId, {
          $set: { status: "archived_too_small" }
        });
        continue;
      }
      if (channelData.latestStats.videoCount < MIN_VIDEOS_FOR_ANALYSIS) {
        await nicheRepository.updateChannel(channelId, {
          $set: { status: "archived_low_sample_size" }
        });
        continue;
      }
      const channelAge = calculateChannelAge(channelData.createdAt);
      const isValidAge = isValidChannelAge(channelAge, options.channelAge);
      if (!isValidAge) {
        await nicheRepository.updateChannel(channelId, {
          $set: { status: "archived_too_old" }
        });
        continue;
      }
      const metrics = calculateDerivedMetrics(channelData);
      const hasGoodPotential = metrics.historicalAvgViewsPerVideo >= MIN_AVG_VIEWS_THRESHOLD;
      if (!hasGoodPotential) {
        await nicheRepository.updateChannel(channelId, {
          $set: { status: "archived_low_potential" }
        });
        continue;
      }
      prospectsForPhase3.push(channelId);
    }
    return prospectsForPhase3;
  } catch (error51) {
    if (error51 instanceof Error) {
      throw new Error(`Phase 2 failed: ${error51.message}`, { cause: error51 });
    }
    throw new Error(`Phase 2 failed with an unknown error`, { cause: error51 });
  }
}

// node_modules/@kirbah/mcp-youtube/dist/services/analysis/phase3-deep-analysis.js
var REANALYSIS_SUBSCRIBER_GROWTH_THRESHOLD = 1.2;
var NO_REANALYSIS_STATUSES = /* @__PURE__ */ new Set([
  "archived_unreplicable",
  "archived_niche_mismatch"
]);
var PRESERVABLE_STATUSES = /* @__PURE__ */ new Set([
  "analyzed_promising_prime_candidate",
  "analyzed_promising_monitor"
]);
async function executeDeepConsistencyAnalysis(prospects, options, youtubeService, nicheRepository) {
  try {
    const promisingChannels = [];
    const publishedAfter = calculateChannelAgePublishedAfter(options.channelAge);
    const consistencyThreshold = getConsistencyThreshold(options.consistencyLevel);
    let quotaExceeded = false;
    for (const channelId of prospects) {
      try {
        const channelData = (await nicheRepository.findChannelsByIds([channelId]))[0];
        if (!channelData) {
          continue;
        }
        if (NO_REANALYSIS_STATUSES.has(channelData.status)) {
          continue;
        }
        let finalStatusToPersist = channelData.status;
        const isPreservableStatus = PRESERVABLE_STATUSES.has(channelData.status);
        const needsReanalysis = !channelData.latestAnalysis || // Always analyze if no previous analysis exists
        channelData.latestStats.subscriberCount >= channelData.latestAnalysis.subscriberCountAtAnalysis * REANALYSIS_SUBSCRIBER_GROWTH_THRESHOLD;
        if (!needsReanalysis) {
          const consistencyPercentage = channelData.latestAnalysis.metrics[options.outlierMagnitude].consistencyPercentage;
          if (consistencyPercentage >= consistencyThreshold) {
            promisingChannels.push(channelData);
          }
          continue;
        }
        const historicalEntry = channelData.latestAnalysis ? { ...channelData.latestAnalysis } : void 0;
        const topVideos = await youtubeService.fetchChannelRecentTopVideos(channelId, publishedAfter);
        if (!topVideos || topVideos.length === 0) {
          continue;
        }
        const { sourceVideoCount, metrics } = calculateConsistencyMetrics(
          topVideos,
          // Cast to non-nullable array after check
          channelData.latestStats.subscriberCount
        );
        const now = /* @__PURE__ */ new Date();
        const newLatestAnalysis = {
          analyzedAt: now,
          subscriberCountAtAnalysis: channelData.latestStats.subscriberCount,
          sourceVideoCount,
          metrics
        };
        const finalConsistencyPercentage = newLatestAnalysis.metrics[options.outlierMagnitude].consistencyPercentage;
        const newAutomaticStatus = finalConsistencyPercentage >= consistencyThreshold ? "analyzed_promising" : "analyzed_low_consistency";
        if (!isPreservableStatus) {
          finalStatusToPersist = newAutomaticStatus;
        }
        const updatePayload = {
          $set: {
            latestAnalysis: newLatestAnalysis,
            status: finalStatusToPersist
            // Use the carefully determined status
          }
        };
        if (historicalEntry) {
          updatePayload.$push = { analysisHistory: historicalEntry };
        }
        await nicheRepository.updateChannel(channelId, updatePayload);
        if (finalConsistencyPercentage >= consistencyThreshold) {
          promisingChannels.push({
            ...channelData,
            // Start with the original data
            latestAnalysis: newLatestAnalysis,
            // Add the new analysis data
            status: finalStatusToPersist,
            // Reflect the final persisted status
            analysisHistory: historicalEntry ? [...channelData.analysisHistory, historicalEntry] : channelData.analysisHistory
            // Reflect the updated history
          });
        }
      } catch (error51) {
        if (isQuotaError(error51)) {
          quotaExceeded = true;
          break;
        } else {
          continue;
        }
      }
    }
    return {
      results: promisingChannels,
      quotaExceeded
    };
  } catch (error51) {
    throw new Error(`Phase 3 failed: ${error51 instanceof Error ? error51.message : String(error51)}`, { cause: error51 });
  }
}

// node_modules/@kirbah/mcp-youtube/dist/services/analysis/phase4-ranking-formatting.js
function formatAndRankAnalysisResults(analysisResults, options, quotaExceeded) {
  const transformedAnalysisResults = analysisResults.map((channelData) => ({
    channelData,
    // Extract the correct metric based on the options
    consistencyPercentage: channelData.latestAnalysis.metrics[options.outlierMagnitude].consistencyPercentage,
    outlierCount: channelData.latestAnalysis.metrics[options.outlierMagnitude].outlierVideoCount
  }));
  const rankedAndFormattedResults = transformedAnalysisResults.map((result) => {
    const impactFactor = result.channelData.latestStats.videoCount > 0 ? result.channelData.latestStats.subscriberCount / result.channelData.latestStats.videoCount : 0;
    const confidenceScore = result.consistencyPercentage * Math.log10(result.outlierCount + 1) * impactFactor;
    const now = /* @__PURE__ */ new Date();
    const createdAt = new Date(result.channelData.createdAt);
    const ageInMillis = now.getTime() - createdAt.getTime();
    const ageInDays = Math.floor(ageInMillis / (1e3 * 60 * 60 * 24));
    return {
      channelId: result.channelData._id,
      channelTitle: result.channelData.channelTitle,
      channelAgeDays: ageInDays,
      subscriberCount: result.channelData.latestStats.subscriberCount,
      videoCount: result.channelData.latestStats.videoCount,
      analysis: {
        consistencyPercentage: result.consistencyPercentage,
        outlierVideoCount: result.outlierCount
      },
      _confidenceScore: confidenceScore
    };
  }).sort((a, b) => b._confidenceScore - a._confidenceScore).slice(0, options.maxResults);
  const finalResults = rankedAndFormattedResults.map(({ _confidenceScore, ...rest }) => rest);
  const finalStatus = quotaExceeded ? "PARTIAL_DUE_TO_QUOTA" : "COMPLETED_SUCCESSFULLY";
  const summary = {
    candidatesFound: 0,
    // This will be filled by the orchestrator
    candidatesAnalyzed: 0,
    // This will be filled by the orchestrator
    apiCreditsUsed: 0,
    // This will be filled by the orchestrator
    ...quotaExceeded && {
      message: "Analysis was stopped prematurely due to YouTube API quota limits. The returned results are the best found from the portion of channels analyzed."
    }
  };
  return {
    status: finalStatus,
    summary,
    results: finalResults
  };
}

// node_modules/@kirbah/mcp-youtube/dist/services/nicheAnalyzer.service.js
var NicheAnalyzerService = class {
  youtubeService;
  nicheRepository;
  constructor(youtubeService, nicheRepository) {
    this.youtubeService = youtubeService;
    this.nicheRepository = nicheRepository;
  }
  async findConsistentOutlierChannels(options) {
    try {
      this.youtubeService.resetApiCreditsUsed();
      const candidateChannelIds = await executeInitialCandidateSearch(options, this.youtubeService);
      const prospects = await executeChannelPreFiltering(candidateChannelIds, options, this.youtubeService, this.nicheRepository);
      const { results: analysisResults, quotaExceeded } = await executeDeepConsistencyAnalysis(prospects, options, this.youtubeService, this.nicheRepository);
      const finalOutput = formatAndRankAnalysisResults(
        analysisResults,
        // Pass the raw ChannelCache[] directly
        options,
        // Pass the full options object
        quotaExceeded
      );
      const actualApiCreditsUsed = this.youtubeService.getApiCreditsUsed();
      finalOutput.summary.candidatesFound = candidateChannelIds.length;
      finalOutput.summary.candidatesAnalyzed = analysisResults.length;
      finalOutput.summary.apiCreditsUsed = actualApiCreditsUsed;
      return finalOutput;
    } catch (error51) {
      if (error51 instanceof AppError)
        throw error51;
      const message = error51 instanceof Error ? error51.message : String(error51);
      throw new Error(`Failed to find consistent outlier channels: ${message}`, { cause: error51 });
    }
  }
};

// node_modules/@kirbah/mcp-youtube/dist/services/analysis/niche.repository.js
var NicheRepository = class {
  CHANNELS_CACHE_COLLECTION = "analysis_channels";
  async findChannelsByIds(ids) {
    const db = await getDb();
    const collection = db.collection(this.CHANNELS_CACHE_COLLECTION);
    const cachedChannels = await collection.find({ _id: { $in: ids } }).toArray();
    return cachedChannels;
  }
  async updateChannel(channelId, updates) {
    const db = await getDb();
    const collection = db.collection(this.CHANNELS_CACHE_COLLECTION);
    await collection.updateOne({ _id: channelId }, updates, { upsert: true });
  }
};

// node_modules/@kirbah/mcp-youtube/dist/tools/general/findConsistentOutlierChannels.js
var findConsistentOutlierChannelsSchema = external_exports.object({
  query: external_exports.string().min(1, "Query is required").describe("Required. The core topic or niche to investigate (e.g., 'stoic philosophy', 'AI history explainers')."),
  channelAge: external_exports.enum(["NEW", "ESTABLISHED"]).default("NEW").describe("Optional. Filters by channel age. Default: 'NEW'. 'NEW' = under 6 months (emerging), 'ESTABLISHED' = 6-24 months (proven)."),
  consistencyLevel: external_exports.enum(["MODERATE", "HIGH"]).default("MODERATE").describe("Optional. Minimum required consistency. Default: 'MODERATE'. 'MODERATE' (~30%) for broad discovery. 'HIGH' (~50%) for exceptional channels."),
  outlierMagnitude: external_exports.enum(["STANDARD", "STRONG"]).default("STANDARD").describe("Optional. Required 'viral factor' for videos. Default: 'STANDARD'. 'STANDARD' (views>subs) for regular content. 'STRONG' (views>3x subs) for viral channels."),
  videoCategoryId: external_exports.string().optional().describe("Optional. YouTube video category ID to narrow search (e.g., '27' for Education). Improves relevance."),
  regionCode: regionCodeSchema.optional().describe("Optional. ISO 2-letter country code (e.g., 'US', 'DE') to target a regional audience."),
  maxResults: external_exports.number().int().min(1).max(50).default(10).describe("Optional. Max number of channels to return. Default: 10.")
});
var FindConsistentOutlierChannelsTool = class extends BaseTool {
  name = "findConsistentOutlierChannels";
  description = "A powerful, high-cost discovery tool. It finds emerging channels that show consistent, high-performance relative to their size within a specific topic and timeframe.";
  schema = findConsistentOutlierChannelsSchema;
  async executeImpl(params) {
    const validatedOptions = params;
    const nicheRepository = new NicheRepository();
    const nicheAnalyzer = new NicheAnalyzerService(this.container.youtubeService, nicheRepository);
    const searchResults = await nicheAnalyzer.findConsistentOutlierChannels(validatedOptions);
    return formatSuccess(searchResults);
  }
};

// node_modules/@kirbah/mcp-youtube/dist/tools/index.js
var TOOL_CLASSES = [
  GetVideoDetailsTool,
  SearchVideosTool,
  GetTranscriptsTool,
  GetVideoCommentsTool,
  GetChannelStatisticsTool,
  GetChannelTopVideosTool,
  GetTrendingVideosTool,
  GetVideoCategoriesTool
];
function registerTools(server, container2) {
  const hasYoutubeKey = !!process.env.YOUTUBE_API_KEY;
  const toolsToRegister = [];
  if (hasYoutubeKey) {
    toolsToRegister.push(...TOOL_CLASSES);
    if (process.env.MDB_MCP_CONNECTION_STRING) {
      toolsToRegister.push(FindConsistentOutlierChannelsTool);
    }
  } else {
    toolsToRegister.push(GetTranscriptsTool);
  }
  for (const ToolClass of toolsToRegister) {
    const toolInstance = new ToolClass(container2);
    const humanReadableTitle = toolInstance.name.replace(/([A-Z])/g, " $1").replace(/^./, (str) => str.toUpperCase());
    server.registerTool(
      toolInstance.name,
      {
        description: toolInstance.description,
        inputSchema: toolInstance.schema,
        annotations: {
          title: humanReadableTitle,
          readOnlyHint: true,
          idempotentHint: true
        }
      },
      // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
      (async (args) => {
        try {
          return await toolInstance.execute(args);
        } catch (err) {
          return formatError2(err);
        }
      })
    );
  }
}

// node_modules/@kirbah/mcp-youtube/dist/prompts/index.js
var PROMPT_CLASSES = [];
function registerPromptSafe(server, promptInstance) {
  server.registerPrompt(promptInstance.name, promptInstance.getDefinition(), (args) => promptInstance.get(args));
}
function registerPrompts(server, container2) {
  if (PROMPT_CLASSES.length === 0) {
    return;
  }
  for (const PromptClass of PROMPT_CLASSES) {
    const promptInstance = new PromptClass(container2);
    registerPromptSafe(server, promptInstance);
  }
}

// node_modules/@kirbah/mcp-youtube/dist/resources/index.js
var RESOURCE_CLASSES = [];
function registerResources(server, container2) {
  if (RESOURCE_CLASSES.length === 0) {
    return;
  }
  for (const ResourceClass of RESOURCE_CLASSES) {
    const resourceInstance = new ResourceClass(container2);
    server.registerResource(
      resourceInstance.name,
      // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
      resourceInstance.uri,
      {
        mimeType: resourceInstance.mimeType,
        description: resourceInstance.description
      },
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (uri, variables) => resourceInstance.read(uri, variables)
    );
  }
}

// node_modules/@kirbah/mcp-youtube/dist/server.js
var configSchema = external_exports.object({
  youtubeApiKey: external_exports.string().optional().describe("YouTube Data API key for accessing the YouTube API."),
  mdbMcpConnectionString: external_exports.string().optional().describe("MongoDB connection string to cache the data.")
});
function createMcpServer(container2) {
  const server = new McpServer({
    name: "YouTube",
    version: package_default.version
  });
  registerTools(server, container2);
  registerPrompts(server, container2);
  registerResources(server, container2);
  return server;
}

// node_modules/@kirbah/mcp-youtube/dist/index.js
loadEnv();
async function runServer(config2) {
  const container2 = initializeContainer({
    apiKey: config2.youtubeApiKey,
    mdbMcpConnectionString: config2.mdbMcpConnectionString
  });
  const server = createMcpServer(container2);
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error(`YouTube MCP server (v${package_default.version}) running in stdio mode.`);
  return server;
}
async function main() {
  await runServer({
    youtubeApiKey: process.env.YOUTUBE_API_KEY,
    mdbMcpConnectionString: process.env.MDB_MCP_CONNECTION_STRING
  });
  const cleanup = async () => {
    console.error("Shutting down STDIO server...");
    await disconnectFromDatabase();
    console.error("Database disconnected. Exiting.");
    process.exit(0);
  };
  process.on("SIGINT", () => void cleanup());
  process.on("SIGTERM", () => void cleanup());
}
if (process.env.NODE_ENV !== "test") {
  main().catch((error51) => {
    console.error("Server error:", error51);
    process.exit(1);
  });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  runServer
});
