"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
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);
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
var __privateWrapper = (obj, member, setter, getter) => ({
  set _(value) {
    __privateSet(obj, member, value, setter);
  },
  get _() {
    return __privateGet(obj, member, getter);
  }
});

// ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/ansi-styles/index.js
function assembleStyles() {
  const codes = /* @__PURE__ */ new Map();
  for (const [groupName, group] of Object.entries(styles)) {
    for (const [styleName, style] of Object.entries(group)) {
      styles[styleName] = {
        open: `\x1B[${style[0]}m`,
        close: `\x1B[${style[1]}m`
      };
      group[styleName] = styles[styleName];
      codes.set(style[0], style[1]);
    }
    Object.defineProperty(styles, groupName, {
      value: group,
      enumerable: false
    });
  }
  Object.defineProperty(styles, "codes", {
    value: codes,
    enumerable: false
  });
  styles.color.close = "\x1B[39m";
  styles.bgColor.close = "\x1B[49m";
  styles.color.ansi = wrapAnsi16();
  styles.color.ansi256 = wrapAnsi256();
  styles.color.ansi16m = wrapAnsi16m();
  styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
  styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
  styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
  Object.defineProperties(styles, {
    rgbToAnsi256: {
      value(red, green, blue) {
        if (red === green && green === blue) {
          if (red < 8) {
            return 16;
          }
          if (red > 248) {
            return 231;
          }
          return Math.round((red - 8) / 247 * 24) + 232;
        }
        return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
      },
      enumerable: false
    },
    hexToRgb: {
      value(hex) {
        const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
        if (!matches) {
          return [0, 0, 0];
        }
        let [colorString] = matches;
        if (colorString.length === 3) {
          colorString = [...colorString].map((character) => character + character).join("");
        }
        const integer = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer >> 16 & 255,
          integer >> 8 & 255,
          integer & 255
          /* eslint-enable no-bitwise */
        ];
      },
      enumerable: false
    },
    hexToAnsi256: {
      value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
      enumerable: false
    },
    ansi256ToAnsi: {
      value(code) {
        if (code < 8) {
          return 30 + code;
        }
        if (code < 16) {
          return 90 + (code - 8);
        }
        let red;
        let green;
        let blue;
        if (code >= 232) {
          red = ((code - 232) * 10 + 8) / 255;
          green = red;
          blue = red;
        } else {
          code -= 16;
          const remainder = code % 36;
          red = Math.floor(code / 36) / 5;
          green = Math.floor(remainder / 6) / 5;
          blue = remainder % 6 / 5;
        }
        const value = Math.max(red, green, blue) * 2;
        if (value === 0) {
          return 30;
        }
        let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
        if (value === 2) {
          result += 60;
        }
        return result;
      },
      enumerable: false
    },
    rgbToAnsi: {
      value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
      enumerable: false
    },
    hexToAnsi: {
      value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
      enumerable: false
    }
  });
  return styles;
}
var ANSI_BACKGROUND_OFFSET, wrapAnsi16, wrapAnsi256, wrapAnsi16m, styles, modifierNames, foregroundColorNames, backgroundColorNames, colorNames, ansiStyles, ansi_styles_default;
var init_ansi_styles = __esm({
  "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/ansi-styles/index.js"() {
    "use strict";
    ANSI_BACKGROUND_OFFSET = 10;
    wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
    wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
    wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
    styles = {
      modifier: {
        reset: [0, 0],
        // 21 isn't widely supported and 22 does the same thing
        bold: [1, 22],
        dim: [2, 22],
        italic: [3, 23],
        underline: [4, 24],
        overline: [53, 55],
        inverse: [7, 27],
        hidden: [8, 28],
        strikethrough: [9, 29]
      },
      color: {
        black: [30, 39],
        red: [31, 39],
        green: [32, 39],
        yellow: [33, 39],
        blue: [34, 39],
        magenta: [35, 39],
        cyan: [36, 39],
        white: [37, 39],
        // Bright color
        blackBright: [90, 39],
        gray: [90, 39],
        // Alias of `blackBright`
        grey: [90, 39],
        // Alias of `blackBright`
        redBright: [91, 39],
        greenBright: [92, 39],
        yellowBright: [93, 39],
        blueBright: [94, 39],
        magentaBright: [95, 39],
        cyanBright: [96, 39],
        whiteBright: [97, 39]
      },
      bgColor: {
        bgBlack: [40, 49],
        bgRed: [41, 49],
        bgGreen: [42, 49],
        bgYellow: [43, 49],
        bgBlue: [44, 49],
        bgMagenta: [45, 49],
        bgCyan: [46, 49],
        bgWhite: [47, 49],
        // Bright color
        bgBlackBright: [100, 49],
        bgGray: [100, 49],
        // Alias of `bgBlackBright`
        bgGrey: [100, 49],
        // Alias of `bgBlackBright`
        bgRedBright: [101, 49],
        bgGreenBright: [102, 49],
        bgYellowBright: [103, 49],
        bgBlueBright: [104, 49],
        bgMagentaBright: [105, 49],
        bgCyanBright: [106, 49],
        bgWhiteBright: [107, 49]
      }
    };
    modifierNames = Object.keys(styles.modifier);
    foregroundColorNames = Object.keys(styles.color);
    backgroundColorNames = Object.keys(styles.bgColor);
    colorNames = [...foregroundColorNames, ...backgroundColorNames];
    ansiStyles = assembleStyles();
    ansi_styles_default = ansiStyles;
  }
});

// ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/supports-color/index.js
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.argv) {
  const prefix2 = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
  const position = argv.indexOf(prefix2 + flag);
  const terminatorPosition = argv.indexOf("--");
  return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
}
function envForceColor() {
  if ("FORCE_COLOR" in env) {
    if (env.FORCE_COLOR === "true") {
      return 1;
    }
    if (env.FORCE_COLOR === "false") {
      return 0;
    }
    return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
  }
}
function translateLevel(level) {
  if (level === 0) {
    return false;
  }
  return {
    level,
    hasBasic: true,
    has256: level >= 2,
    has16m: level >= 3
  };
}
function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
  const noFlagForceColor = envForceColor();
  if (noFlagForceColor !== void 0) {
    flagForceColor = noFlagForceColor;
  }
  const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
  if (forceColor === 0) {
    return 0;
  }
  if (sniffFlags) {
    if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
      return 3;
    }
    if (hasFlag("color=256")) {
      return 2;
    }
  }
  if ("TF_BUILD" in env && "AGENT_NAME" in env) {
    return 1;
  }
  if (haveStream && !streamIsTTY && forceColor === void 0) {
    return 0;
  }
  const min = forceColor || 0;
  if (env.TERM === "dumb") {
    return min;
  }
  if (import_node_process.default.platform === "win32") {
    const osRelease = import_node_os.default.release().split(".");
    if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
      return Number(osRelease[2]) >= 14931 ? 3 : 2;
    }
    return 1;
  }
  if ("CI" in env) {
    if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) {
      return 3;
    }
    if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
      return 1;
    }
    return min;
  }
  if ("TEAMCITY_VERSION" in env) {
    return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
  }
  if (env.COLORTERM === "truecolor") {
    return 3;
  }
  if (env.TERM === "xterm-kitty") {
    return 3;
  }
  if ("TERM_PROGRAM" in env) {
    const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
    switch (env.TERM_PROGRAM) {
      case "iTerm.app": {
        return version >= 3 ? 3 : 2;
      }
      case "Apple_Terminal": {
        return 2;
      }
    }
  }
  if (/-256(color)?$/i.test(env.TERM)) {
    return 2;
  }
  if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
    return 1;
  }
  if ("COLORTERM" in env) {
    return 1;
  }
  return min;
}
function createSupportsColor(stream, options = {}) {
  const level = _supportsColor(stream, {
    streamIsTTY: stream && stream.isTTY,
    ...options
  });
  return translateLevel(level);
}
var import_node_process, import_node_os, import_node_tty, env, flagForceColor, supportsColor, supports_color_default;
var init_supports_color = __esm({
  "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/supports-color/index.js"() {
    "use strict";
    import_node_process = __toESM(require("process"), 1);
    import_node_os = __toESM(require("os"), 1);
    import_node_tty = __toESM(require("tty"), 1);
    ({ env } = import_node_process.default);
    if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
      flagForceColor = 0;
    } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
      flagForceColor = 1;
    }
    supportsColor = {
      stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }),
      stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) })
    };
    supports_color_default = supportsColor;
  }
});

// ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/utilities.js
function stringReplaceAll(string, substring2, replacer) {
  let index6 = string.indexOf(substring2);
  if (index6 === -1) {
    return string;
  }
  const substringLength = substring2.length;
  let endIndex = 0;
  let returnValue = "";
  do {
    returnValue += string.slice(endIndex, index6) + substring2 + replacer;
    endIndex = index6 + substringLength;
    index6 = string.indexOf(substring2, endIndex);
  } while (index6 !== -1);
  returnValue += string.slice(endIndex);
  return returnValue;
}
function stringEncaseCRLFWithFirstIndex(string, prefix2, postfix, index6) {
  let endIndex = 0;
  let returnValue = "";
  do {
    const gotCR = string[index6 - 1] === "\r";
    returnValue += string.slice(endIndex, gotCR ? index6 - 1 : index6) + prefix2 + (gotCR ? "\r\n" : "\n") + postfix;
    endIndex = index6 + 1;
    index6 = string.indexOf("\n", endIndex);
  } while (index6 !== -1);
  returnValue += string.slice(endIndex);
  return returnValue;
}
var init_utilities = __esm({
  "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/utilities.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/index.js
function createChalk(options) {
  return chalkFactory(options);
}
var stdoutColor, stderrColor, GENERATOR, STYLER, IS_EMPTY, levelMapping, styles2, applyOptions, chalkFactory, getModelAnsi, usedModels, proto, createStyler, createBuilder, applyStyle, chalk, chalkStderr, source_default;
var init_source = __esm({
  "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/index.js"() {
    "use strict";
    init_ansi_styles();
    init_supports_color();
    init_utilities();
    ({ stdout: stdoutColor, stderr: stderrColor } = supports_color_default);
    GENERATOR = Symbol("GENERATOR");
    STYLER = Symbol("STYLER");
    IS_EMPTY = Symbol("IS_EMPTY");
    levelMapping = [
      "ansi",
      "ansi",
      "ansi256",
      "ansi16m"
    ];
    styles2 = /* @__PURE__ */ Object.create(null);
    applyOptions = (object, options = {}) => {
      if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
        throw new Error("The `level` option should be an integer from 0 to 3");
      }
      const colorLevel = stdoutColor ? stdoutColor.level : 0;
      object.level = options.level === void 0 ? colorLevel : options.level;
    };
    chalkFactory = (options) => {
      const chalk2 = (...strings) => strings.join(" ");
      applyOptions(chalk2, options);
      Object.setPrototypeOf(chalk2, createChalk.prototype);
      return chalk2;
    };
    Object.setPrototypeOf(createChalk.prototype, Function.prototype);
    for (const [styleName, style] of Object.entries(ansi_styles_default)) {
      styles2[styleName] = {
        get() {
          const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
          Object.defineProperty(this, styleName, { value: builder });
          return builder;
        }
      };
    }
    styles2.visible = {
      get() {
        const builder = createBuilder(this, this[STYLER], true);
        Object.defineProperty(this, "visible", { value: builder });
        return builder;
      }
    };
    getModelAnsi = (model, level, type, ...arguments_) => {
      if (model === "rgb") {
        if (level === "ansi16m") {
          return ansi_styles_default[type].ansi16m(...arguments_);
        }
        if (level === "ansi256") {
          return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
        }
        return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
      }
      if (model === "hex") {
        return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
      }
      return ansi_styles_default[type][model](...arguments_);
    };
    usedModels = ["rgb", "hex", "ansi256"];
    for (const model of usedModels) {
      styles2[model] = {
        get() {
          const { level } = this;
          return function(...arguments_) {
            const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
            return createBuilder(this, styler, this[IS_EMPTY]);
          };
        }
      };
      const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
      styles2[bgModel] = {
        get() {
          const { level } = this;
          return function(...arguments_) {
            const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
            return createBuilder(this, styler, this[IS_EMPTY]);
          };
        }
      };
    }
    proto = Object.defineProperties(() => {
    }, {
      ...styles2,
      level: {
        enumerable: true,
        get() {
          return this[GENERATOR].level;
        },
        set(level) {
          this[GENERATOR].level = level;
        }
      }
    });
    createStyler = (open, close, parent) => {
      let openAll;
      let closeAll;
      if (parent === void 0) {
        openAll = open;
        closeAll = close;
      } else {
        openAll = parent.openAll + open;
        closeAll = close + parent.closeAll;
      }
      return {
        open,
        close,
        openAll,
        closeAll,
        parent
      };
    };
    createBuilder = (self2, _styler, _isEmpty) => {
      const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
      Object.setPrototypeOf(builder, proto);
      builder[GENERATOR] = self2;
      builder[STYLER] = _styler;
      builder[IS_EMPTY] = _isEmpty;
      return builder;
    };
    applyStyle = (self2, string) => {
      if (self2.level <= 0 || !string) {
        return self2[IS_EMPTY] ? "" : string;
      }
      let styler = self2[STYLER];
      if (styler === void 0) {
        return string;
      }
      const { openAll, closeAll } = styler;
      if (string.includes("\x1B")) {
        while (styler !== void 0) {
          string = stringReplaceAll(string, styler.close, styler.open);
          styler = styler.parent;
        }
      }
      const lfIndex = string.indexOf("\n");
      if (lfIndex !== -1) {
        string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
      }
      return openAll + string + closeAll;
    };
    Object.defineProperties(createChalk.prototype, styles2);
    chalk = createChalk();
    chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
    source_default = chalk;
  }
});

// ../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/old.js
var require_old = __commonJS({
  "../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/old.js"(exports2) {
    "use strict";
    var pathModule = require("path");
    var isWindows = process.platform === "win32";
    var fs5 = require("fs");
    var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
    function rethrow() {
      var callback;
      if (DEBUG) {
        var backtrace = new Error();
        callback = debugCallback;
      } else
        callback = missingCallback;
      return callback;
      function debugCallback(err2) {
        if (err2) {
          backtrace.message = err2.message;
          err2 = backtrace;
          missingCallback(err2);
        }
      }
      function missingCallback(err2) {
        if (err2) {
          if (process.throwDeprecation)
            throw err2;
          else if (!process.noDeprecation) {
            var msg = "fs: missing callback " + (err2.stack || err2.message);
            if (process.traceDeprecation)
              console.trace(msg);
            else
              console.error(msg);
          }
        }
      }
    }
    function maybeCallback(cb) {
      return typeof cb === "function" ? cb : rethrow();
    }
    var normalize = pathModule.normalize;
    if (isWindows) {
      nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
    } else {
      nextPartRe = /(.*?)(?:[\/]+|$)/g;
    }
    var nextPartRe;
    if (isWindows) {
      splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
    } else {
      splitRootRe = /^[\/]*/;
    }
    var splitRootRe;
    exports2.realpathSync = function realpathSync(p5, cache5) {
      p5 = pathModule.resolve(p5);
      if (cache5 && Object.prototype.hasOwnProperty.call(cache5, p5)) {
        return cache5[p5];
      }
      var original = p5, seenLinks = {}, knownHard = {};
      var pos;
      var current;
      var base;
      var previous;
      start();
      function start() {
        var m6 = splitRootRe.exec(p5);
        pos = m6[0].length;
        current = m6[0];
        base = m6[0];
        previous = "";
        if (isWindows && !knownHard[base]) {
          fs5.lstatSync(base);
          knownHard[base] = true;
        }
      }
      while (pos < p5.length) {
        nextPartRe.lastIndex = pos;
        var result = nextPartRe.exec(p5);
        previous = current;
        current += result[0];
        base = previous + result[1];
        pos = nextPartRe.lastIndex;
        if (knownHard[base] || cache5 && cache5[base] === base) {
          continue;
        }
        var resolvedLink;
        if (cache5 && Object.prototype.hasOwnProperty.call(cache5, base)) {
          resolvedLink = cache5[base];
        } else {
          var stat2 = fs5.lstatSync(base);
          if (!stat2.isSymbolicLink()) {
            knownHard[base] = true;
            if (cache5) cache5[base] = base;
            continue;
          }
          var linkTarget = null;
          if (!isWindows) {
            var id = stat2.dev.toString(32) + ":" + stat2.ino.toString(32);
            if (seenLinks.hasOwnProperty(id)) {
              linkTarget = seenLinks[id];
            }
          }
          if (linkTarget === null) {
            fs5.statSync(base);
            linkTarget = fs5.readlinkSync(base);
          }
          resolvedLink = pathModule.resolve(previous, linkTarget);
          if (cache5) cache5[base] = resolvedLink;
          if (!isWindows) seenLinks[id] = linkTarget;
        }
        p5 = pathModule.resolve(resolvedLink, p5.slice(pos));
        start();
      }
      if (cache5) cache5[original] = p5;
      return p5;
    };
    exports2.realpath = function realpath(p5, cache5, cb) {
      if (typeof cb !== "function") {
        cb = maybeCallback(cache5);
        cache5 = null;
      }
      p5 = pathModule.resolve(p5);
      if (cache5 && Object.prototype.hasOwnProperty.call(cache5, p5)) {
        return process.nextTick(cb.bind(null, null, cache5[p5]));
      }
      var original = p5, seenLinks = {}, knownHard = {};
      var pos;
      var current;
      var base;
      var previous;
      start();
      function start() {
        var m6 = splitRootRe.exec(p5);
        pos = m6[0].length;
        current = m6[0];
        base = m6[0];
        previous = "";
        if (isWindows && !knownHard[base]) {
          fs5.lstat(base, function(err2) {
            if (err2) return cb(err2);
            knownHard[base] = true;
            LOOP();
          });
        } else {
          process.nextTick(LOOP);
        }
      }
      function LOOP() {
        if (pos >= p5.length) {
          if (cache5) cache5[original] = p5;
          return cb(null, p5);
        }
        nextPartRe.lastIndex = pos;
        var result = nextPartRe.exec(p5);
        previous = current;
        current += result[0];
        base = previous + result[1];
        pos = nextPartRe.lastIndex;
        if (knownHard[base] || cache5 && cache5[base] === base) {
          return process.nextTick(LOOP);
        }
        if (cache5 && Object.prototype.hasOwnProperty.call(cache5, base)) {
          return gotResolvedLink(cache5[base]);
        }
        return fs5.lstat(base, gotStat);
      }
      function gotStat(err2, stat2) {
        if (err2) return cb(err2);
        if (!stat2.isSymbolicLink()) {
          knownHard[base] = true;
          if (cache5) cache5[base] = base;
          return process.nextTick(LOOP);
        }
        if (!isWindows) {
          var id = stat2.dev.toString(32) + ":" + stat2.ino.toString(32);
          if (seenLinks.hasOwnProperty(id)) {
            return gotTarget(null, seenLinks[id], base);
          }
        }
        fs5.stat(base, function(err3) {
          if (err3) return cb(err3);
          fs5.readlink(base, function(err4, target) {
            if (!isWindows) seenLinks[id] = target;
            gotTarget(err4, target);
          });
        });
      }
      function gotTarget(err2, target, base2) {
        if (err2) return cb(err2);
        var resolvedLink = pathModule.resolve(previous, target);
        if (cache5) cache5[base2] = resolvedLink;
        gotResolvedLink(resolvedLink);
      }
      function gotResolvedLink(resolvedLink) {
        p5 = pathModule.resolve(resolvedLink, p5.slice(pos));
        start();
      }
    };
  }
});

// ../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/index.js
var require_fs = __commonJS({
  "../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/index.js"(exports2, module2) {
    "use strict";
    module2.exports = realpath;
    realpath.realpath = realpath;
    realpath.sync = realpathSync;
    realpath.realpathSync = realpathSync;
    realpath.monkeypatch = monkeypatch;
    realpath.unmonkeypatch = unmonkeypatch;
    var fs5 = require("fs");
    var origRealpath = fs5.realpath;
    var origRealpathSync = fs5.realpathSync;
    var version = process.version;
    var ok = /^v[0-5]\./.test(version);
    var old = require_old();
    function newError(er) {
      return er && er.syscall === "realpath" && (er.code === "ELOOP" || er.code === "ENOMEM" || er.code === "ENAMETOOLONG");
    }
    function realpath(p5, cache5, cb) {
      if (ok) {
        return origRealpath(p5, cache5, cb);
      }
      if (typeof cache5 === "function") {
        cb = cache5;
        cache5 = null;
      }
      origRealpath(p5, cache5, function(er, result) {
        if (newError(er)) {
          old.realpath(p5, cache5, cb);
        } else {
          cb(er, result);
        }
      });
    }
    function realpathSync(p5, cache5) {
      if (ok) {
        return origRealpathSync(p5, cache5);
      }
      try {
        return origRealpathSync(p5, cache5);
      } catch (er) {
        if (newError(er)) {
          return old.realpathSync(p5, cache5);
        } else {
          throw er;
        }
      }
    }
    function monkeypatch() {
      fs5.realpath = realpath;
      fs5.realpathSync = realpathSync;
    }
    function unmonkeypatch() {
      fs5.realpath = origRealpath;
      fs5.realpathSync = origRealpathSync;
    }
  }
});

// ../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/lib/path.js
var require_path = __commonJS({
  "../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/lib/path.js"(exports2, module2) {
    "use strict";
    var isWindows = typeof process === "object" && process && process.platform === "win32";
    module2.exports = isWindows ? { sep: "\\" } : { sep: "/" };
  }
});

// ../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
var require_balanced_match = __commonJS({
  "../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js"(exports2, module2) {
    "use strict";
    module2.exports = balanced;
    function balanced(a5, b5, str) {
      if (a5 instanceof RegExp) a5 = maybeMatch(a5, str);
      if (b5 instanceof RegExp) b5 = maybeMatch(b5, str);
      var r6 = range(a5, b5, str);
      return r6 && {
        start: r6[0],
        end: r6[1],
        pre: str.slice(0, r6[0]),
        body: str.slice(r6[0] + a5.length, r6[1]),
        post: str.slice(r6[1] + b5.length)
      };
    }
    function maybeMatch(reg, str) {
      var m6 = str.match(reg);
      return m6 ? m6[0] : null;
    }
    balanced.range = range;
    function range(a5, b5, str) {
      var begs, beg, left, right, result;
      var ai = str.indexOf(a5);
      var bi = str.indexOf(b5, ai + 1);
      var i6 = ai;
      if (ai >= 0 && bi > 0) {
        if (a5 === b5) {
          return [ai, bi];
        }
        begs = [];
        left = str.length;
        while (i6 >= 0 && !result) {
          if (i6 == ai) {
            begs.push(i6);
            ai = str.indexOf(a5, i6 + 1);
          } else if (begs.length == 1) {
            result = [begs.pop(), bi];
          } else {
            beg = begs.pop();
            if (beg < left) {
              left = beg;
              right = bi;
            }
            bi = str.indexOf(b5, i6 + 1);
          }
          i6 = ai < bi && ai >= 0 ? ai : bi;
        }
        if (begs.length) {
          result = [left, right];
        }
      }
      return result;
    }
  }
});

// ../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js
var require_brace_expansion = __commonJS({
  "../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js"(exports2, module2) {
    "use strict";
    var balanced = require_balanced_match();
    module2.exports = expandTop;
    var escSlash = "\0SLASH" + Math.random() + "\0";
    var escOpen = "\0OPEN" + Math.random() + "\0";
    var escClose = "\0CLOSE" + Math.random() + "\0";
    var escComma = "\0COMMA" + Math.random() + "\0";
    var escPeriod = "\0PERIOD" + Math.random() + "\0";
    function numeric(str) {
      return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
    }
    function escapeBraces(str) {
      return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
    }
    function unescapeBraces(str) {
      return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
    }
    function parseCommaParts(str) {
      if (!str)
        return [""];
      var parts = [];
      var m6 = balanced("{", "}", str);
      if (!m6)
        return str.split(",");
      var pre = m6.pre;
      var body = m6.body;
      var post = m6.post;
      var p5 = pre.split(",");
      p5[p5.length - 1] += "{" + body + "}";
      var postParts = parseCommaParts(post);
      if (post.length) {
        p5[p5.length - 1] += postParts.shift();
        p5.push.apply(p5, postParts);
      }
      parts.push.apply(parts, p5);
      return parts;
    }
    function expandTop(str) {
      if (!str)
        return [];
      if (str.substr(0, 2) === "{}") {
        str = "\\{\\}" + str.substr(2);
      }
      return expand2(escapeBraces(str), true).map(unescapeBraces);
    }
    function embrace(str) {
      return "{" + str + "}";
    }
    function isPadded(el) {
      return /^-?0\d/.test(el);
    }
    function lte(i6, y2) {
      return i6 <= y2;
    }
    function gte(i6, y2) {
      return i6 >= y2;
    }
    function expand2(str, isTop) {
      var expansions = [];
      var m6 = balanced("{", "}", str);
      if (!m6) return [str];
      var pre = m6.pre;
      var post = m6.post.length ? expand2(m6.post, false) : [""];
      if (/\$$/.test(m6.pre)) {
        for (var k5 = 0; k5 < post.length; k5++) {
          var expansion = pre + "{" + m6.body + "}" + post[k5];
          expansions.push(expansion);
        }
      } else {
        var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m6.body);
        var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m6.body);
        var isSequence = isNumericSequence || isAlphaSequence;
        var isOptions = m6.body.indexOf(",") >= 0;
        if (!isSequence && !isOptions) {
          if (m6.post.match(/,.*\}/)) {
            str = m6.pre + "{" + m6.body + escClose + m6.post;
            return expand2(str);
          }
          return [str];
        }
        var n5;
        if (isSequence) {
          n5 = m6.body.split(/\.\./);
        } else {
          n5 = parseCommaParts(m6.body);
          if (n5.length === 1) {
            n5 = expand2(n5[0], false).map(embrace);
            if (n5.length === 1) {
              return post.map(function(p5) {
                return m6.pre + n5[0] + p5;
              });
            }
          }
        }
        var N;
        if (isSequence) {
          var x5 = numeric(n5[0]);
          var y2 = numeric(n5[1]);
          var width = Math.max(n5[0].length, n5[1].length);
          var incr = n5.length == 3 ? Math.abs(numeric(n5[2])) : 1;
          var test = lte;
          var reverse = y2 < x5;
          if (reverse) {
            incr *= -1;
            test = gte;
          }
          var pad = n5.some(isPadded);
          N = [];
          for (var i6 = x5; test(i6, y2); i6 += incr) {
            var c5;
            if (isAlphaSequence) {
              c5 = String.fromCharCode(i6);
              if (c5 === "\\")
                c5 = "";
            } else {
              c5 = String(i6);
              if (pad) {
                var need = width - c5.length;
                if (need > 0) {
                  var z2 = new Array(need + 1).join("0");
                  if (i6 < 0)
                    c5 = "-" + z2 + c5.slice(1);
                  else
                    c5 = z2 + c5;
                }
              }
            }
            N.push(c5);
          }
        } else {
          N = [];
          for (var j5 = 0; j5 < n5.length; j5++) {
            N.push.apply(N, expand2(n5[j5], false));
          }
        }
        for (var j5 = 0; j5 < N.length; j5++) {
          for (var k5 = 0; k5 < post.length; k5++) {
            var expansion = pre + N[j5] + post[k5];
            if (!isTop || isSequence || expansion)
              expansions.push(expansion);
          }
        }
      }
      return expansions;
    }
  }
});

// ../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/minimatch.js
var require_minimatch = __commonJS({
  "../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/minimatch.js"(exports2, module2) {
    "use strict";
    var minimatch2 = module2.exports = (p5, pattern, options = {}) => {
      assertValidPattern2(pattern);
      if (!options.nocomment && pattern.charAt(0) === "#") {
        return false;
      }
      return new Minimatch2(pattern, options).match(p5);
    };
    module2.exports = minimatch2;
    var path3 = require_path();
    minimatch2.sep = path3.sep;
    var GLOBSTAR2 = Symbol("globstar **");
    minimatch2.GLOBSTAR = GLOBSTAR2;
    var expand2 = require_brace_expansion();
    var plTypes2 = {
      "!": { open: "(?:(?!(?:", close: "))[^/]*?)" },
      "?": { open: "(?:", close: ")?" },
      "+": { open: "(?:", close: ")+" },
      "*": { open: "(?:", close: ")*" },
      "@": { open: "(?:", close: ")" }
    };
    var qmark2 = "[^/]";
    var star2 = qmark2 + "*?";
    var twoStarDot2 = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
    var twoStarNoDot2 = "(?:(?!(?:\\/|^)\\.).)*?";
    var charSet2 = (s6) => s6.split("").reduce((set, c5) => {
      set[c5] = true;
      return set;
    }, {});
    var reSpecials2 = charSet2("().*{}+?[]^$\\!");
    var addPatternStartSet2 = charSet2("[.(");
    var slashSplit = /\/+/;
    minimatch2.filter = (pattern, options = {}) => (p5, i6, list) => minimatch2(p5, pattern, options);
    var ext2 = (a5, b5 = {}) => {
      const t6 = {};
      Object.keys(a5).forEach((k5) => t6[k5] = a5[k5]);
      Object.keys(b5).forEach((k5) => t6[k5] = b5[k5]);
      return t6;
    };
    minimatch2.defaults = (def) => {
      if (!def || typeof def !== "object" || !Object.keys(def).length) {
        return minimatch2;
      }
      const orig = minimatch2;
      const m6 = (p5, pattern, options) => orig(p5, pattern, ext2(def, options));
      m6.Minimatch = class Minimatch extends orig.Minimatch {
        constructor(pattern, options) {
          super(pattern, ext2(def, options));
        }
      };
      m6.Minimatch.defaults = (options) => orig.defaults(ext2(def, options)).Minimatch;
      m6.filter = (pattern, options) => orig.filter(pattern, ext2(def, options));
      m6.defaults = (options) => orig.defaults(ext2(def, options));
      m6.makeRe = (pattern, options) => orig.makeRe(pattern, ext2(def, options));
      m6.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext2(def, options));
      m6.match = (list, pattern, options) => orig.match(list, pattern, ext2(def, options));
      return m6;
    };
    minimatch2.braceExpand = (pattern, options) => braceExpand2(pattern, options);
    var braceExpand2 = (pattern, options = {}) => {
      assertValidPattern2(pattern);
      if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
        return [pattern];
      }
      return expand2(pattern);
    };
    var MAX_PATTERN_LENGTH2 = 1024 * 64;
    var assertValidPattern2 = (pattern) => {
      if (typeof pattern !== "string") {
        throw new TypeError("invalid pattern");
      }
      if (pattern.length > MAX_PATTERN_LENGTH2) {
        throw new TypeError("pattern is too long");
      }
    };
    var SUBPARSE = Symbol("subparse");
    minimatch2.makeRe = (pattern, options) => new Minimatch2(pattern, options || {}).makeRe();
    minimatch2.match = (list, pattern, options = {}) => {
      const mm = new Minimatch2(pattern, options);
      list = list.filter((f7) => mm.match(f7));
      if (mm.options.nonull && !list.length) {
        list.push(pattern);
      }
      return list;
    };
    var globUnescape2 = (s6) => s6.replace(/\\(.)/g, "$1");
    var charUnescape = (s6) => s6.replace(/\\([^-\]])/g, "$1");
    var regExpEscape2 = (s6) => s6.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    var braExpEscape = (s6) => s6.replace(/[[\]\\]/g, "\\$&");
    var Minimatch2 = class {
      constructor(pattern, options) {
        assertValidPattern2(pattern);
        if (!options) options = {};
        this.options = options;
        this.set = [];
        this.pattern = pattern;
        this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
        if (this.windowsPathsNoEscape) {
          this.pattern = this.pattern.replace(/\\/g, "/");
        }
        this.regexp = null;
        this.negate = false;
        this.comment = false;
        this.empty = false;
        this.partial = !!options.partial;
        this.make();
      }
      debug() {
      }
      make() {
        const pattern = this.pattern;
        const options = this.options;
        if (!options.nocomment && pattern.charAt(0) === "#") {
          this.comment = true;
          return;
        }
        if (!pattern) {
          this.empty = true;
          return;
        }
        this.parseNegate();
        let set = this.globSet = this.braceExpand();
        if (options.debug) this.debug = (...args) => console.error(...args);
        this.debug(this.pattern, set);
        set = this.globParts = set.map((s6) => s6.split(slashSplit));
        this.debug(this.pattern, set);
        set = set.map((s6, si, set2) => s6.map(this.parse, this));
        this.debug(this.pattern, set);
        set = set.filter((s6) => s6.indexOf(false) === -1);
        this.debug(this.pattern, set);
        this.set = set;
      }
      parseNegate() {
        if (this.options.nonegate) return;
        const pattern = this.pattern;
        let negate2 = false;
        let negateOffset = 0;
        for (let i6 = 0; i6 < pattern.length && pattern.charAt(i6) === "!"; i6++) {
          negate2 = !negate2;
          negateOffset++;
        }
        if (negateOffset) this.pattern = pattern.slice(negateOffset);
        this.negate = negate2;
      }
      // set partial to true to test if, for example,
      // "/a/b" matches the start of "/*/b/*/d"
      // Partial means, if you run out of file before you run
      // out of pattern, then that's fine, as long as all
      // the parts match.
      matchOne(file, pattern, partial) {
        var options = this.options;
        this.debug(
          "matchOne",
          { "this": this, file, pattern }
        );
        this.debug("matchOne", file.length, pattern.length);
        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
          this.debug("matchOne loop");
          var p5 = pattern[pi];
          var f7 = file[fi];
          this.debug(pattern, p5, f7);
          if (p5 === false) return false;
          if (p5 === GLOBSTAR2) {
            this.debug("GLOBSTAR", [pattern, p5, f7]);
            var fr = fi;
            var pr = pi + 1;
            if (pr === pl) {
              this.debug("** at the end");
              for (; fi < fl; fi++) {
                if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".") return false;
              }
              return true;
            }
            while (fr < fl) {
              var swallowee = file[fr];
              this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
              if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
                this.debug("globstar found match!", fr, fl, swallowee);
                return true;
              } else {
                if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
                  this.debug("dot detected!", file, fr, pattern, pr);
                  break;
                }
                this.debug("globstar swallow a segment, and continue");
                fr++;
              }
            }
            if (partial) {
              this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
              if (fr === fl) return true;
            }
            return false;
          }
          var hit;
          if (typeof p5 === "string") {
            hit = f7 === p5;
            this.debug("string match", p5, f7, hit);
          } else {
            hit = f7.match(p5);
            this.debug("pattern match", p5, f7, hit);
          }
          if (!hit) return false;
        }
        if (fi === fl && pi === pl) {
          return true;
        } else if (fi === fl) {
          return partial;
        } else if (pi === pl) {
          return fi === fl - 1 && file[fi] === "";
        }
        throw new Error("wtf?");
      }
      braceExpand() {
        return braceExpand2(this.pattern, this.options);
      }
      parse(pattern, isSub) {
        assertValidPattern2(pattern);
        const options = this.options;
        if (pattern === "**") {
          if (!options.noglobstar)
            return GLOBSTAR2;
          else
            pattern = "*";
        }
        if (pattern === "") return "";
        let re = "";
        let hasMagic = false;
        let escaping = false;
        const patternListStack = [];
        const negativeLists = [];
        let stateChar;
        let inClass = false;
        let reClassStart = -1;
        let classStart = -1;
        let cs;
        let pl;
        let sp;
        let dotTravAllowed = pattern.charAt(0) === ".";
        let dotFileAllowed = options.dot || dotTravAllowed;
        const patternStart = () => dotTravAllowed ? "" : dotFileAllowed ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
        const subPatternStart = (p5) => p5.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
        const clearStateChar = () => {
          if (stateChar) {
            switch (stateChar) {
              case "*":
                re += star2;
                hasMagic = true;
                break;
              case "?":
                re += qmark2;
                hasMagic = true;
                break;
              default:
                re += "\\" + stateChar;
                break;
            }
            this.debug("clearStateChar %j %j", stateChar, re);
            stateChar = false;
          }
        };
        for (let i6 = 0, c5; i6 < pattern.length && (c5 = pattern.charAt(i6)); i6++) {
          this.debug("%s	%s %s %j", pattern, i6, re, c5);
          if (escaping) {
            if (c5 === "/") {
              return false;
            }
            if (reSpecials2[c5]) {
              re += "\\";
            }
            re += c5;
            escaping = false;
            continue;
          }
          switch (c5) {
            /* istanbul ignore next */
            case "/": {
              return false;
            }
            case "\\":
              if (inClass && pattern.charAt(i6 + 1) === "-") {
                re += c5;
                continue;
              }
              clearStateChar();
              escaping = true;
              continue;
            // the various stateChar values
            // for the "extglob" stuff.
            case "?":
            case "*":
            case "+":
            case "@":
            case "!":
              this.debug("%s	%s %s %j <-- stateChar", pattern, i6, re, c5);
              if (inClass) {
                this.debug("  in class");
                if (c5 === "!" && i6 === classStart + 1) c5 = "^";
                re += c5;
                continue;
              }
              this.debug("call clearStateChar %j", stateChar);
              clearStateChar();
              stateChar = c5;
              if (options.noext) clearStateChar();
              continue;
            case "(": {
              if (inClass) {
                re += "(";
                continue;
              }
              if (!stateChar) {
                re += "\\(";
                continue;
              }
              const plEntry = {
                type: stateChar,
                start: i6 - 1,
                reStart: re.length,
                open: plTypes2[stateChar].open,
                close: plTypes2[stateChar].close
              };
              this.debug(this.pattern, "	", plEntry);
              patternListStack.push(plEntry);
              re += plEntry.open;
              if (plEntry.start === 0 && plEntry.type !== "!") {
                dotTravAllowed = true;
                re += subPatternStart(pattern.slice(i6 + 1));
              }
              this.debug("plType %j %j", stateChar, re);
              stateChar = false;
              continue;
            }
            case ")": {
              const plEntry = patternListStack[patternListStack.length - 1];
              if (inClass || !plEntry) {
                re += "\\)";
                continue;
              }
              patternListStack.pop();
              clearStateChar();
              hasMagic = true;
              pl = plEntry;
              re += pl.close;
              if (pl.type === "!") {
                negativeLists.push(Object.assign(pl, { reEnd: re.length }));
              }
              continue;
            }
            case "|": {
              const plEntry = patternListStack[patternListStack.length - 1];
              if (inClass || !plEntry) {
                re += "\\|";
                continue;
              }
              clearStateChar();
              re += "|";
              if (plEntry.start === 0 && plEntry.type !== "!") {
                dotTravAllowed = true;
                re += subPatternStart(pattern.slice(i6 + 1));
              }
              continue;
            }
            // these are mostly the same in regexp and glob
            case "[":
              clearStateChar();
              if (inClass) {
                re += "\\" + c5;
                continue;
              }
              inClass = true;
              classStart = i6;
              reClassStart = re.length;
              re += c5;
              continue;
            case "]":
              if (i6 === classStart + 1 || !inClass) {
                re += "\\" + c5;
                continue;
              }
              cs = pattern.substring(classStart + 1, i6);
              try {
                RegExp("[" + braExpEscape(charUnescape(cs)) + "]");
                re += c5;
              } catch (er) {
                re = re.substring(0, reClassStart) + "(?:$.)";
              }
              hasMagic = true;
              inClass = false;
              continue;
            default:
              clearStateChar();
              if (reSpecials2[c5] && !(c5 === "^" && inClass)) {
                re += "\\";
              }
              re += c5;
              break;
          }
        }
        if (inClass) {
          cs = pattern.slice(classStart + 1);
          sp = this.parse(cs, SUBPARSE);
          re = re.substring(0, reClassStart) + "\\[" + sp[0];
          hasMagic = hasMagic || sp[1];
        }
        for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
          let tail;
          tail = re.slice(pl.reStart + pl.open.length);
          this.debug("setting tail", re, pl);
          tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_3, $1, $2) => {
            if (!$2) {
              $2 = "\\";
            }
            return $1 + $1 + $2 + "|";
          });
          this.debug("tail=%j\n   %s", tail, tail, pl, re);
          const t6 = pl.type === "*" ? star2 : pl.type === "?" ? qmark2 : "\\" + pl.type;
          hasMagic = true;
          re = re.slice(0, pl.reStart) + t6 + "\\(" + tail;
        }
        clearStateChar();
        if (escaping) {
          re += "\\\\";
        }
        const addPatternStart = addPatternStartSet2[re.charAt(0)];
        for (let n5 = negativeLists.length - 1; n5 > -1; n5--) {
          const nl = negativeLists[n5];
          const nlBefore = re.slice(0, nl.reStart);
          const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
          let nlAfter = re.slice(nl.reEnd);
          const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
          const closeParensBefore = nlBefore.split(")").length;
          const openParensBefore = nlBefore.split("(").length - closeParensBefore;
          let cleanAfter = nlAfter;
          for (let i6 = 0; i6 < openParensBefore; i6++) {
            cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
          }
          nlAfter = cleanAfter;
          const dollar = nlAfter === "" && isSub !== SUBPARSE ? "(?:$|\\/)" : "";
          re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
        }
        if (re !== "" && hasMagic) {
          re = "(?=.)" + re;
        }
        if (addPatternStart) {
          re = patternStart() + re;
        }
        if (isSub === SUBPARSE) {
          return [re, hasMagic];
        }
        if (options.nocase && !hasMagic) {
          hasMagic = pattern.toUpperCase() !== pattern.toLowerCase();
        }
        if (!hasMagic) {
          return globUnescape2(pattern);
        }
        const flags = options.nocase ? "i" : "";
        try {
          return Object.assign(new RegExp("^" + re + "$", flags), {
            _glob: pattern,
            _src: re
          });
        } catch (er) {
          return new RegExp("$.");
        }
      }
      makeRe() {
        if (this.regexp || this.regexp === false) return this.regexp;
        const set = this.set;
        if (!set.length) {
          this.regexp = false;
          return this.regexp;
        }
        const options = this.options;
        const twoStar = options.noglobstar ? star2 : options.dot ? twoStarDot2 : twoStarNoDot2;
        const flags = options.nocase ? "i" : "";
        let re = set.map((pattern) => {
          pattern = pattern.map(
            (p5) => typeof p5 === "string" ? regExpEscape2(p5) : p5 === GLOBSTAR2 ? GLOBSTAR2 : p5._src
          ).reduce((set2, p5) => {
            if (!(set2[set2.length - 1] === GLOBSTAR2 && p5 === GLOBSTAR2)) {
              set2.push(p5);
            }
            return set2;
          }, []);
          pattern.forEach((p5, i6) => {
            if (p5 !== GLOBSTAR2 || pattern[i6 - 1] === GLOBSTAR2) {
              return;
            }
            if (i6 === 0) {
              if (pattern.length > 1) {
                pattern[i6 + 1] = "(?:\\/|" + twoStar + "\\/)?" + pattern[i6 + 1];
              } else {
                pattern[i6] = twoStar;
              }
            } else if (i6 === pattern.length - 1) {
              pattern[i6 - 1] += "(?:\\/|" + twoStar + ")?";
            } else {
              pattern[i6 - 1] += "(?:\\/|\\/" + twoStar + "\\/)" + pattern[i6 + 1];
              pattern[i6 + 1] = GLOBSTAR2;
            }
          });
          return pattern.filter((p5) => p5 !== GLOBSTAR2).join("/");
        }).join("|");
        re = "^(?:" + re + ")$";
        if (this.negate) re = "^(?!" + re + ").*$";
        try {
          this.regexp = new RegExp(re, flags);
        } catch (ex) {
          this.regexp = false;
        }
        return this.regexp;
      }
      match(f7, partial = this.partial) {
        this.debug("match", f7, this.pattern);
        if (this.comment) return false;
        if (this.empty) return f7 === "";
        if (f7 === "/" && partial) return true;
        const options = this.options;
        if (path3.sep !== "/") {
          f7 = f7.split(path3.sep).join("/");
        }
        f7 = f7.split(slashSplit);
        this.debug(this.pattern, "split", f7);
        const set = this.set;
        this.debug(this.pattern, "set", set);
        let filename;
        for (let i6 = f7.length - 1; i6 >= 0; i6--) {
          filename = f7[i6];
          if (filename) break;
        }
        for (let i6 = 0; i6 < set.length; i6++) {
          const pattern = set[i6];
          let file = f7;
          if (options.matchBase && pattern.length === 1) {
            file = [filename];
          }
          const hit = this.matchOne(file, pattern, partial);
          if (hit) {
            if (options.flipNegate) return true;
            return !this.negate;
          }
        }
        if (options.flipNegate) return false;
        return this.negate;
      }
      static defaults(def) {
        return minimatch2.defaults(def).Minimatch;
      }
    };
    minimatch2.Minimatch = Minimatch2;
  }
});

// ../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js
var require_inherits_browser = __commonJS({
  "../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js"(exports2, module2) {
    "use strict";
    if (typeof Object.create === "function") {
      module2.exports = function inherits(ctor, superCtor) {
        if (superCtor) {
          ctor.super_ = superCtor;
          ctor.prototype = Object.create(superCtor.prototype, {
            constructor: {
              value: ctor,
              enumerable: false,
              writable: true,
              configurable: true
            }
          });
        }
      };
    } else {
      module2.exports = function inherits(ctor, superCtor) {
        if (superCtor) {
          ctor.super_ = superCtor;
          var TempCtor = function() {
          };
          TempCtor.prototype = superCtor.prototype;
          ctor.prototype = new TempCtor();
          ctor.prototype.constructor = ctor;
        }
      };
    }
  }
});

// ../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js
var require_inherits = __commonJS({
  "../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js"(exports2, module2) {
    "use strict";
    try {
      util2 = require("util");
      if (typeof util2.inherits !== "function") throw "";
      module2.exports = util2.inherits;
    } catch (e6) {
      module2.exports = require_inherits_browser();
    }
    var util2;
  }
});

// ../node_modules/.pnpm/glob@8.1.0/node_modules/glob/common.js
var require_common = __commonJS({
  "../node_modules/.pnpm/glob@8.1.0/node_modules/glob/common.js"(exports2) {
    "use strict";
    exports2.setopts = setopts;
    exports2.ownProp = ownProp;
    exports2.makeAbs = makeAbs;
    exports2.finish = finish;
    exports2.mark = mark;
    exports2.isIgnored = isIgnored;
    exports2.childrenIgnored = childrenIgnored;
    function ownProp(obj, field) {
      return Object.prototype.hasOwnProperty.call(obj, field);
    }
    var fs5 = require("fs");
    var path3 = require("path");
    var minimatch2 = require_minimatch();
    var isAbsolute = require("path").isAbsolute;
    var Minimatch2 = minimatch2.Minimatch;
    function alphasort(a5, b5) {
      return a5.localeCompare(b5, "en");
    }
    function setupIgnores(self2, options) {
      self2.ignore = options.ignore || [];
      if (!Array.isArray(self2.ignore))
        self2.ignore = [self2.ignore];
      if (self2.ignore.length) {
        self2.ignore = self2.ignore.map(ignoreMap);
      }
    }
    function ignoreMap(pattern) {
      var gmatcher = null;
      if (pattern.slice(-3) === "/**") {
        var gpattern = pattern.replace(/(\/\*\*)+$/, "");
        gmatcher = new Minimatch2(gpattern, { dot: true });
      }
      return {
        matcher: new Minimatch2(pattern, { dot: true }),
        gmatcher
      };
    }
    function setopts(self2, pattern, options) {
      if (!options)
        options = {};
      if (options.matchBase && -1 === pattern.indexOf("/")) {
        if (options.noglobstar) {
          throw new Error("base matching requires globstar");
        }
        pattern = "**/" + pattern;
      }
      self2.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
      if (self2.windowsPathsNoEscape) {
        pattern = pattern.replace(/\\/g, "/");
      }
      self2.silent = !!options.silent;
      self2.pattern = pattern;
      self2.strict = options.strict !== false;
      self2.realpath = !!options.realpath;
      self2.realpathCache = options.realpathCache || /* @__PURE__ */ Object.create(null);
      self2.follow = !!options.follow;
      self2.dot = !!options.dot;
      self2.mark = !!options.mark;
      self2.nodir = !!options.nodir;
      if (self2.nodir)
        self2.mark = true;
      self2.sync = !!options.sync;
      self2.nounique = !!options.nounique;
      self2.nonull = !!options.nonull;
      self2.nosort = !!options.nosort;
      self2.nocase = !!options.nocase;
      self2.stat = !!options.stat;
      self2.noprocess = !!options.noprocess;
      self2.absolute = !!options.absolute;
      self2.fs = options.fs || fs5;
      self2.maxLength = options.maxLength || Infinity;
      self2.cache = options.cache || /* @__PURE__ */ Object.create(null);
      self2.statCache = options.statCache || /* @__PURE__ */ Object.create(null);
      self2.symlinks = options.symlinks || /* @__PURE__ */ Object.create(null);
      setupIgnores(self2, options);
      self2.changedCwd = false;
      var cwd = process.cwd();
      if (!ownProp(options, "cwd"))
        self2.cwd = path3.resolve(cwd);
      else {
        self2.cwd = path3.resolve(options.cwd);
        self2.changedCwd = self2.cwd !== cwd;
      }
      self2.root = options.root || path3.resolve(self2.cwd, "/");
      self2.root = path3.resolve(self2.root);
      self2.cwdAbs = isAbsolute(self2.cwd) ? self2.cwd : makeAbs(self2, self2.cwd);
      self2.nomount = !!options.nomount;
      if (process.platform === "win32") {
        self2.root = self2.root.replace(/\\/g, "/");
        self2.cwd = self2.cwd.replace(/\\/g, "/");
        self2.cwdAbs = self2.cwdAbs.replace(/\\/g, "/");
      }
      options.nonegate = true;
      options.nocomment = true;
      self2.minimatch = new Minimatch2(pattern, options);
      self2.options = self2.minimatch.options;
    }
    function finish(self2) {
      var nou = self2.nounique;
      var all = nou ? [] : /* @__PURE__ */ Object.create(null);
      for (var i6 = 0, l5 = self2.matches.length; i6 < l5; i6++) {
        var matches = self2.matches[i6];
        if (!matches || Object.keys(matches).length === 0) {
          if (self2.nonull) {
            var literal = self2.minimatch.globSet[i6];
            if (nou)
              all.push(literal);
            else
              all[literal] = true;
          }
        } else {
          var m6 = Object.keys(matches);
          if (nou)
            all.push.apply(all, m6);
          else
            m6.forEach(function(m7) {
              all[m7] = true;
            });
        }
      }
      if (!nou)
        all = Object.keys(all);
      if (!self2.nosort)
        all = all.sort(alphasort);
      if (self2.mark) {
        for (var i6 = 0; i6 < all.length; i6++) {
          all[i6] = self2._mark(all[i6]);
        }
        if (self2.nodir) {
          all = all.filter(function(e6) {
            var notDir = !/\/$/.test(e6);
            var c5 = self2.cache[e6] || self2.cache[makeAbs(self2, e6)];
            if (notDir && c5)
              notDir = c5 !== "DIR" && !Array.isArray(c5);
            return notDir;
          });
        }
      }
      if (self2.ignore.length)
        all = all.filter(function(m7) {
          return !isIgnored(self2, m7);
        });
      self2.found = all;
    }
    function mark(self2, p5) {
      var abs = makeAbs(self2, p5);
      var c5 = self2.cache[abs];
      var m6 = p5;
      if (c5) {
        var isDir = c5 === "DIR" || Array.isArray(c5);
        var slash = p5.slice(-1) === "/";
        if (isDir && !slash)
          m6 += "/";
        else if (!isDir && slash)
          m6 = m6.slice(0, -1);
        if (m6 !== p5) {
          var mabs = makeAbs(self2, m6);
          self2.statCache[mabs] = self2.statCache[abs];
          self2.cache[mabs] = self2.cache[abs];
        }
      }
      return m6;
    }
    function makeAbs(self2, f7) {
      var abs = f7;
      if (f7.charAt(0) === "/") {
        abs = path3.join(self2.root, f7);
      } else if (isAbsolute(f7) || f7 === "") {
        abs = f7;
      } else if (self2.changedCwd) {
        abs = path3.resolve(self2.cwd, f7);
      } else {
        abs = path3.resolve(f7);
      }
      if (process.platform === "win32")
        abs = abs.replace(/\\/g, "/");
      return abs;
    }
    function isIgnored(self2, path4) {
      if (!self2.ignore.length)
        return false;
      return self2.ignore.some(function(item) {
        return item.matcher.match(path4) || !!(item.gmatcher && item.gmatcher.match(path4));
      });
    }
    function childrenIgnored(self2, path4) {
      if (!self2.ignore.length)
        return false;
      return self2.ignore.some(function(item) {
        return !!(item.gmatcher && item.gmatcher.match(path4));
      });
    }
  }
});

// ../node_modules/.pnpm/glob@8.1.0/node_modules/glob/sync.js
var require_sync = __commonJS({
  "../node_modules/.pnpm/glob@8.1.0/node_modules/glob/sync.js"(exports2, module2) {
    "use strict";
    module2.exports = globSync;
    globSync.GlobSync = GlobSync;
    var rp = require_fs();
    var minimatch2 = require_minimatch();
    var Minimatch2 = minimatch2.Minimatch;
    var Glob = require_glob().Glob;
    var util2 = require("util");
    var path3 = require("path");
    var assert = require("assert");
    var isAbsolute = require("path").isAbsolute;
    var common = require_common();
    var setopts = common.setopts;
    var ownProp = common.ownProp;
    var childrenIgnored = common.childrenIgnored;
    var isIgnored = common.isIgnored;
    function globSync(pattern, options) {
      if (typeof options === "function" || arguments.length === 3)
        throw new TypeError("callback provided to sync glob\nSee: https://github.com/isaacs/node-glob/issues/167");
      return new GlobSync(pattern, options).found;
    }
    function GlobSync(pattern, options) {
      if (!pattern)
        throw new Error("must provide pattern");
      if (typeof options === "function" || arguments.length === 3)
        throw new TypeError("callback provided to sync glob\nSee: https://github.com/isaacs/node-glob/issues/167");
      if (!(this instanceof GlobSync))
        return new GlobSync(pattern, options);
      setopts(this, pattern, options);
      if (this.noprocess)
        return this;
      var n5 = this.minimatch.set.length;
      this.matches = new Array(n5);
      for (var i6 = 0; i6 < n5; i6++) {
        this._process(this.minimatch.set[i6], i6, false);
      }
      this._finish();
    }
    GlobSync.prototype._finish = function() {
      assert.ok(this instanceof GlobSync);
      if (this.realpath) {
        var self2 = this;
        this.matches.forEach(function(matchset, index6) {
          var set = self2.matches[index6] = /* @__PURE__ */ Object.create(null);
          for (var p5 in matchset) {
            try {
              p5 = self2._makeAbs(p5);
              var real = rp.realpathSync(p5, self2.realpathCache);
              set[real] = true;
            } catch (er) {
              if (er.syscall === "stat")
                set[self2._makeAbs(p5)] = true;
              else
                throw er;
            }
          }
        });
      }
      common.finish(this);
    };
    GlobSync.prototype._process = function(pattern, index6, inGlobStar) {
      assert.ok(this instanceof GlobSync);
      var n5 = 0;
      while (typeof pattern[n5] === "string") {
        n5++;
      }
      var prefix2;
      switch (n5) {
        // if not, then this is rather simple
        case pattern.length:
          this._processSimple(pattern.join("/"), index6);
          return;
        case 0:
          prefix2 = null;
          break;
        default:
          prefix2 = pattern.slice(0, n5).join("/");
          break;
      }
      var remain = pattern.slice(n5);
      var read;
      if (prefix2 === null)
        read = ".";
      else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p5) {
        return typeof p5 === "string" ? p5 : "[*]";
      }).join("/"))) {
        if (!prefix2 || !isAbsolute(prefix2))
          prefix2 = "/" + prefix2;
        read = prefix2;
      } else
        read = prefix2;
      var abs = this._makeAbs(read);
      if (childrenIgnored(this, read))
        return;
      var isGlobStar = remain[0] === minimatch2.GLOBSTAR;
      if (isGlobStar)
        this._processGlobStar(prefix2, read, abs, remain, index6, inGlobStar);
      else
        this._processReaddir(prefix2, read, abs, remain, index6, inGlobStar);
    };
    GlobSync.prototype._processReaddir = function(prefix2, read, abs, remain, index6, inGlobStar) {
      var entries = this._readdir(abs, inGlobStar);
      if (!entries)
        return;
      var pn = remain[0];
      var negate2 = !!this.minimatch.negate;
      var rawGlob = pn._glob;
      var dotOk = this.dot || rawGlob.charAt(0) === ".";
      var matchedEntries = [];
      for (var i6 = 0; i6 < entries.length; i6++) {
        var e6 = entries[i6];
        if (e6.charAt(0) !== "." || dotOk) {
          var m6;
          if (negate2 && !prefix2) {
            m6 = !e6.match(pn);
          } else {
            m6 = e6.match(pn);
          }
          if (m6)
            matchedEntries.push(e6);
        }
      }
      var len = matchedEntries.length;
      if (len === 0)
        return;
      if (remain.length === 1 && !this.mark && !this.stat) {
        if (!this.matches[index6])
          this.matches[index6] = /* @__PURE__ */ Object.create(null);
        for (var i6 = 0; i6 < len; i6++) {
          var e6 = matchedEntries[i6];
          if (prefix2) {
            if (prefix2.slice(-1) !== "/")
              e6 = prefix2 + "/" + e6;
            else
              e6 = prefix2 + e6;
          }
          if (e6.charAt(0) === "/" && !this.nomount) {
            e6 = path3.join(this.root, e6);
          }
          this._emitMatch(index6, e6);
        }
        return;
      }
      remain.shift();
      for (var i6 = 0; i6 < len; i6++) {
        var e6 = matchedEntries[i6];
        var newPattern;
        if (prefix2)
          newPattern = [prefix2, e6];
        else
          newPattern = [e6];
        this._process(newPattern.concat(remain), index6, inGlobStar);
      }
    };
    GlobSync.prototype._emitMatch = function(index6, e6) {
      if (isIgnored(this, e6))
        return;
      var abs = this._makeAbs(e6);
      if (this.mark)
        e6 = this._mark(e6);
      if (this.absolute) {
        e6 = abs;
      }
      if (this.matches[index6][e6])
        return;
      if (this.nodir) {
        var c5 = this.cache[abs];
        if (c5 === "DIR" || Array.isArray(c5))
          return;
      }
      this.matches[index6][e6] = true;
      if (this.stat)
        this._stat(e6);
    };
    GlobSync.prototype._readdirInGlobStar = function(abs) {
      if (this.follow)
        return this._readdir(abs, false);
      var entries;
      var lstat;
      var stat2;
      try {
        lstat = this.fs.lstatSync(abs);
      } catch (er) {
        if (er.code === "ENOENT") {
          return null;
        }
      }
      var isSym = lstat && lstat.isSymbolicLink();
      this.symlinks[abs] = isSym;
      if (!isSym && lstat && !lstat.isDirectory())
        this.cache[abs] = "FILE";
      else
        entries = this._readdir(abs, false);
      return entries;
    };
    GlobSync.prototype._readdir = function(abs, inGlobStar) {
      var entries;
      if (inGlobStar && !ownProp(this.symlinks, abs))
        return this._readdirInGlobStar(abs);
      if (ownProp(this.cache, abs)) {
        var c5 = this.cache[abs];
        if (!c5 || c5 === "FILE")
          return null;
        if (Array.isArray(c5))
          return c5;
      }
      try {
        return this._readdirEntries(abs, this.fs.readdirSync(abs));
      } catch (er) {
        this._readdirError(abs, er);
        return null;
      }
    };
    GlobSync.prototype._readdirEntries = function(abs, entries) {
      if (!this.mark && !this.stat) {
        for (var i6 = 0; i6 < entries.length; i6++) {
          var e6 = entries[i6];
          if (abs === "/")
            e6 = abs + e6;
          else
            e6 = abs + "/" + e6;
          this.cache[e6] = true;
        }
      }
      this.cache[abs] = entries;
      return entries;
    };
    GlobSync.prototype._readdirError = function(f7, er) {
      switch (er.code) {
        case "ENOTSUP":
        // https://github.com/isaacs/node-glob/issues/205
        case "ENOTDIR":
          var abs = this._makeAbs(f7);
          this.cache[abs] = "FILE";
          if (abs === this.cwdAbs) {
            var error2 = new Error(er.code + " invalid cwd " + this.cwd);
            error2.path = this.cwd;
            error2.code = er.code;
            throw error2;
          }
          break;
        case "ENOENT":
        // not terribly unusual
        case "ELOOP":
        case "ENAMETOOLONG":
        case "UNKNOWN":
          this.cache[this._makeAbs(f7)] = false;
          break;
        default:
          this.cache[this._makeAbs(f7)] = false;
          if (this.strict)
            throw er;
          if (!this.silent)
            console.error("glob error", er);
          break;
      }
    };
    GlobSync.prototype._processGlobStar = function(prefix2, read, abs, remain, index6, inGlobStar) {
      var entries = this._readdir(abs, inGlobStar);
      if (!entries)
        return;
      var remainWithoutGlobStar = remain.slice(1);
      var gspref = prefix2 ? [prefix2] : [];
      var noGlobStar = gspref.concat(remainWithoutGlobStar);
      this._process(noGlobStar, index6, false);
      var len = entries.length;
      var isSym = this.symlinks[abs];
      if (isSym && inGlobStar)
        return;
      for (var i6 = 0; i6 < len; i6++) {
        var e6 = entries[i6];
        if (e6.charAt(0) === "." && !this.dot)
          continue;
        var instead = gspref.concat(entries[i6], remainWithoutGlobStar);
        this._process(instead, index6, true);
        var below = gspref.concat(entries[i6], remain);
        this._process(below, index6, true);
      }
    };
    GlobSync.prototype._processSimple = function(prefix2, index6) {
      var exists = this._stat(prefix2);
      if (!this.matches[index6])
        this.matches[index6] = /* @__PURE__ */ Object.create(null);
      if (!exists)
        return;
      if (prefix2 && isAbsolute(prefix2) && !this.nomount) {
        var trail = /[\/\\]$/.test(prefix2);
        if (prefix2.charAt(0) === "/") {
          prefix2 = path3.join(this.root, prefix2);
        } else {
          prefix2 = path3.resolve(this.root, prefix2);
          if (trail)
            prefix2 += "/";
        }
      }
      if (process.platform === "win32")
        prefix2 = prefix2.replace(/\\/g, "/");
      this._emitMatch(index6, prefix2);
    };
    GlobSync.prototype._stat = function(f7) {
      var abs = this._makeAbs(f7);
      var needDir = f7.slice(-1) === "/";
      if (f7.length > this.maxLength)
        return false;
      if (!this.stat && ownProp(this.cache, abs)) {
        var c5 = this.cache[abs];
        if (Array.isArray(c5))
          c5 = "DIR";
        if (!needDir || c5 === "DIR")
          return c5;
        if (needDir && c5 === "FILE")
          return false;
      }
      var exists;
      var stat2 = this.statCache[abs];
      if (!stat2) {
        var lstat;
        try {
          lstat = this.fs.lstatSync(abs);
        } catch (er) {
          if (er && (er.code === "ENOENT" || er.code === "ENOTDIR")) {
            this.statCache[abs] = false;
            return false;
          }
        }
        if (lstat && lstat.isSymbolicLink()) {
          try {
            stat2 = this.fs.statSync(abs);
          } catch (er) {
            stat2 = lstat;
          }
        } else {
          stat2 = lstat;
        }
      }
      this.statCache[abs] = stat2;
      var c5 = true;
      if (stat2)
        c5 = stat2.isDirectory() ? "DIR" : "FILE";
      this.cache[abs] = this.cache[abs] || c5;
      if (needDir && c5 === "FILE")
        return false;
      return c5;
    };
    GlobSync.prototype._mark = function(p5) {
      return common.mark(this, p5);
    };
    GlobSync.prototype._makeAbs = function(f7) {
      return common.makeAbs(this, f7);
    };
  }
});

// ../node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js
var require_wrappy = __commonJS({
  "../node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js"(exports2, module2) {
    "use strict";
    module2.exports = wrappy;
    function wrappy(fn, cb) {
      if (fn && cb) return wrappy(fn)(cb);
      if (typeof fn !== "function")
        throw new TypeError("need wrapper function");
      Object.keys(fn).forEach(function(k5) {
        wrapper[k5] = fn[k5];
      });
      return wrapper;
      function wrapper() {
        var args = new Array(arguments.length);
        for (var i6 = 0; i6 < args.length; i6++) {
          args[i6] = arguments[i6];
        }
        var ret = fn.apply(this, args);
        var cb2 = args[args.length - 1];
        if (typeof ret === "function" && ret !== cb2) {
          Object.keys(cb2).forEach(function(k5) {
            ret[k5] = cb2[k5];
          });
        }
        return ret;
      }
    }
  }
});

// ../node_modules/.pnpm/once@1.4.0/node_modules/once/once.js
var require_once = __commonJS({
  "../node_modules/.pnpm/once@1.4.0/node_modules/once/once.js"(exports2, module2) {
    "use strict";
    var wrappy = require_wrappy();
    module2.exports = wrappy(once);
    module2.exports.strict = wrappy(onceStrict);
    once.proto = once(function() {
      Object.defineProperty(Function.prototype, "once", {
        value: function() {
          return once(this);
        },
        configurable: true
      });
      Object.defineProperty(Function.prototype, "onceStrict", {
        value: function() {
          return onceStrict(this);
        },
        configurable: true
      });
    });
    function once(fn) {
      var f7 = function() {
        if (f7.called) return f7.value;
        f7.called = true;
        return f7.value = fn.apply(this, arguments);
      };
      f7.called = false;
      return f7;
    }
    function onceStrict(fn) {
      var f7 = function() {
        if (f7.called)
          throw new Error(f7.onceError);
        f7.called = true;
        return f7.value = fn.apply(this, arguments);
      };
      var name = fn.name || "Function wrapped with `once`";
      f7.onceError = name + " shouldn't be called more than once";
      f7.called = false;
      return f7;
    }
  }
});

// ../node_modules/.pnpm/inflight@1.0.6/node_modules/inflight/inflight.js
var require_inflight = __commonJS({
  "../node_modules/.pnpm/inflight@1.0.6/node_modules/inflight/inflight.js"(exports2, module2) {
    "use strict";
    var wrappy = require_wrappy();
    var reqs = /* @__PURE__ */ Object.create(null);
    var once = require_once();
    module2.exports = wrappy(inflight);
    function inflight(key, cb) {
      if (reqs[key]) {
        reqs[key].push(cb);
        return null;
      } else {
        reqs[key] = [cb];
        return makeres(key);
      }
    }
    function makeres(key) {
      return once(function RES() {
        var cbs = reqs[key];
        var len = cbs.length;
        var args = slice(arguments);
        try {
          for (var i6 = 0; i6 < len; i6++) {
            cbs[i6].apply(null, args);
          }
        } finally {
          if (cbs.length > len) {
            cbs.splice(0, len);
            process.nextTick(function() {
              RES.apply(null, args);
            });
          } else {
            delete reqs[key];
          }
        }
      });
    }
    function slice(args) {
      var length = args.length;
      var array2 = [];
      for (var i6 = 0; i6 < length; i6++) array2[i6] = args[i6];
      return array2;
    }
  }
});

// ../node_modules/.pnpm/glob@8.1.0/node_modules/glob/glob.js
var require_glob = __commonJS({
  "../node_modules/.pnpm/glob@8.1.0/node_modules/glob/glob.js"(exports2, module2) {
    "use strict";
    module2.exports = glob2;
    var rp = require_fs();
    var minimatch2 = require_minimatch();
    var Minimatch2 = minimatch2.Minimatch;
    var inherits = require_inherits();
    var EE = require("events").EventEmitter;
    var path3 = require("path");
    var assert = require("assert");
    var isAbsolute = require("path").isAbsolute;
    var globSync = require_sync();
    var common = require_common();
    var setopts = common.setopts;
    var ownProp = common.ownProp;
    var inflight = require_inflight();
    var util2 = require("util");
    var childrenIgnored = common.childrenIgnored;
    var isIgnored = common.isIgnored;
    var once = require_once();
    function glob2(pattern, options, cb) {
      if (typeof options === "function") cb = options, options = {};
      if (!options) options = {};
      if (options.sync) {
        if (cb)
          throw new TypeError("callback provided to sync glob");
        return globSync(pattern, options);
      }
      return new Glob(pattern, options, cb);
    }
    glob2.sync = globSync;
    var GlobSync = glob2.GlobSync = globSync.GlobSync;
    glob2.glob = glob2;
    function extend(origin, add) {
      if (add === null || typeof add !== "object") {
        return origin;
      }
      var keys = Object.keys(add);
      var i6 = keys.length;
      while (i6--) {
        origin[keys[i6]] = add[keys[i6]];
      }
      return origin;
    }
    glob2.hasMagic = function(pattern, options_) {
      var options = extend({}, options_);
      options.noprocess = true;
      var g5 = new Glob(pattern, options);
      var set = g5.minimatch.set;
      if (!pattern)
        return false;
      if (set.length > 1)
        return true;
      for (var j5 = 0; j5 < set[0].length; j5++) {
        if (typeof set[0][j5] !== "string")
          return true;
      }
      return false;
    };
    glob2.Glob = Glob;
    inherits(Glob, EE);
    function Glob(pattern, options, cb) {
      if (typeof options === "function") {
        cb = options;
        options = null;
      }
      if (options && options.sync) {
        if (cb)
          throw new TypeError("callback provided to sync glob");
        return new GlobSync(pattern, options);
      }
      if (!(this instanceof Glob))
        return new Glob(pattern, options, cb);
      setopts(this, pattern, options);
      this._didRealPath = false;
      var n5 = this.minimatch.set.length;
      this.matches = new Array(n5);
      if (typeof cb === "function") {
        cb = once(cb);
        this.on("error", cb);
        this.on("end", function(matches) {
          cb(null, matches);
        });
      }
      var self2 = this;
      this._processing = 0;
      this._emitQueue = [];
      this._processQueue = [];
      this.paused = false;
      if (this.noprocess)
        return this;
      if (n5 === 0)
        return done();
      var sync2 = true;
      for (var i6 = 0; i6 < n5; i6++) {
        this._process(this.minimatch.set[i6], i6, false, done);
      }
      sync2 = false;
      function done() {
        --self2._processing;
        if (self2._processing <= 0) {
          if (sync2) {
            process.nextTick(function() {
              self2._finish();
            });
          } else {
            self2._finish();
          }
        }
      }
    }
    Glob.prototype._finish = function() {
      assert(this instanceof Glob);
      if (this.aborted)
        return;
      if (this.realpath && !this._didRealpath)
        return this._realpath();
      common.finish(this);
      this.emit("end", this.found);
    };
    Glob.prototype._realpath = function() {
      if (this._didRealpath)
        return;
      this._didRealpath = true;
      var n5 = this.matches.length;
      if (n5 === 0)
        return this._finish();
      var self2 = this;
      for (var i6 = 0; i6 < this.matches.length; i6++)
        this._realpathSet(i6, next);
      function next() {
        if (--n5 === 0)
          self2._finish();
      }
    };
    Glob.prototype._realpathSet = function(index6, cb) {
      var matchset = this.matches[index6];
      if (!matchset)
        return cb();
      var found = Object.keys(matchset);
      var self2 = this;
      var n5 = found.length;
      if (n5 === 0)
        return cb();
      var set = this.matches[index6] = /* @__PURE__ */ Object.create(null);
      found.forEach(function(p5, i6) {
        p5 = self2._makeAbs(p5);
        rp.realpath(p5, self2.realpathCache, function(er, real) {
          if (!er)
            set[real] = true;
          else if (er.syscall === "stat")
            set[p5] = true;
          else
            self2.emit("error", er);
          if (--n5 === 0) {
            self2.matches[index6] = set;
            cb();
          }
        });
      });
    };
    Glob.prototype._mark = function(p5) {
      return common.mark(this, p5);
    };
    Glob.prototype._makeAbs = function(f7) {
      return common.makeAbs(this, f7);
    };
    Glob.prototype.abort = function() {
      this.aborted = true;
      this.emit("abort");
    };
    Glob.prototype.pause = function() {
      if (!this.paused) {
        this.paused = true;
        this.emit("pause");
      }
    };
    Glob.prototype.resume = function() {
      if (this.paused) {
        this.emit("resume");
        this.paused = false;
        if (this._emitQueue.length) {
          var eq = this._emitQueue.slice(0);
          this._emitQueue.length = 0;
          for (var i6 = 0; i6 < eq.length; i6++) {
            var e6 = eq[i6];
            this._emitMatch(e6[0], e6[1]);
          }
        }
        if (this._processQueue.length) {
          var pq = this._processQueue.slice(0);
          this._processQueue.length = 0;
          for (var i6 = 0; i6 < pq.length; i6++) {
            var p5 = pq[i6];
            this._processing--;
            this._process(p5[0], p5[1], p5[2], p5[3]);
          }
        }
      }
    };
    Glob.prototype._process = function(pattern, index6, inGlobStar, cb) {
      assert(this instanceof Glob);
      assert(typeof cb === "function");
      if (this.aborted)
        return;
      this._processing++;
      if (this.paused) {
        this._processQueue.push([pattern, index6, inGlobStar, cb]);
        return;
      }
      var n5 = 0;
      while (typeof pattern[n5] === "string") {
        n5++;
      }
      var prefix2;
      switch (n5) {
        // if not, then this is rather simple
        case pattern.length:
          this._processSimple(pattern.join("/"), index6, cb);
          return;
        case 0:
          prefix2 = null;
          break;
        default:
          prefix2 = pattern.slice(0, n5).join("/");
          break;
      }
      var remain = pattern.slice(n5);
      var read;
      if (prefix2 === null)
        read = ".";
      else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p5) {
        return typeof p5 === "string" ? p5 : "[*]";
      }).join("/"))) {
        if (!prefix2 || !isAbsolute(prefix2))
          prefix2 = "/" + prefix2;
        read = prefix2;
      } else
        read = prefix2;
      var abs = this._makeAbs(read);
      if (childrenIgnored(this, read))
        return cb();
      var isGlobStar = remain[0] === minimatch2.GLOBSTAR;
      if (isGlobStar)
        this._processGlobStar(prefix2, read, abs, remain, index6, inGlobStar, cb);
      else
        this._processReaddir(prefix2, read, abs, remain, index6, inGlobStar, cb);
    };
    Glob.prototype._processReaddir = function(prefix2, read, abs, remain, index6, inGlobStar, cb) {
      var self2 = this;
      this._readdir(abs, inGlobStar, function(er, entries) {
        return self2._processReaddir2(prefix2, read, abs, remain, index6, inGlobStar, entries, cb);
      });
    };
    Glob.prototype._processReaddir2 = function(prefix2, read, abs, remain, index6, inGlobStar, entries, cb) {
      if (!entries)
        return cb();
      var pn = remain[0];
      var negate2 = !!this.minimatch.negate;
      var rawGlob = pn._glob;
      var dotOk = this.dot || rawGlob.charAt(0) === ".";
      var matchedEntries = [];
      for (var i6 = 0; i6 < entries.length; i6++) {
        var e6 = entries[i6];
        if (e6.charAt(0) !== "." || dotOk) {
          var m6;
          if (negate2 && !prefix2) {
            m6 = !e6.match(pn);
          } else {
            m6 = e6.match(pn);
          }
          if (m6)
            matchedEntries.push(e6);
        }
      }
      var len = matchedEntries.length;
      if (len === 0)
        return cb();
      if (remain.length === 1 && !this.mark && !this.stat) {
        if (!this.matches[index6])
          this.matches[index6] = /* @__PURE__ */ Object.create(null);
        for (var i6 = 0; i6 < len; i6++) {
          var e6 = matchedEntries[i6];
          if (prefix2) {
            if (prefix2 !== "/")
              e6 = prefix2 + "/" + e6;
            else
              e6 = prefix2 + e6;
          }
          if (e6.charAt(0) === "/" && !this.nomount) {
            e6 = path3.join(this.root, e6);
          }
          this._emitMatch(index6, e6);
        }
        return cb();
      }
      remain.shift();
      for (var i6 = 0; i6 < len; i6++) {
        var e6 = matchedEntries[i6];
        var newPattern;
        if (prefix2) {
          if (prefix2 !== "/")
            e6 = prefix2 + "/" + e6;
          else
            e6 = prefix2 + e6;
        }
        this._process([e6].concat(remain), index6, inGlobStar, cb);
      }
      cb();
    };
    Glob.prototype._emitMatch = function(index6, e6) {
      if (this.aborted)
        return;
      if (isIgnored(this, e6))
        return;
      if (this.paused) {
        this._emitQueue.push([index6, e6]);
        return;
      }
      var abs = isAbsolute(e6) ? e6 : this._makeAbs(e6);
      if (this.mark)
        e6 = this._mark(e6);
      if (this.absolute)
        e6 = abs;
      if (this.matches[index6][e6])
        return;
      if (this.nodir) {
        var c5 = this.cache[abs];
        if (c5 === "DIR" || Array.isArray(c5))
          return;
      }
      this.matches[index6][e6] = true;
      var st = this.statCache[abs];
      if (st)
        this.emit("stat", e6, st);
      this.emit("match", e6);
    };
    Glob.prototype._readdirInGlobStar = function(abs, cb) {
      if (this.aborted)
        return;
      if (this.follow)
        return this._readdir(abs, false, cb);
      var lstatkey = "lstat\0" + abs;
      var self2 = this;
      var lstatcb = inflight(lstatkey, lstatcb_);
      if (lstatcb)
        self2.fs.lstat(abs, lstatcb);
      function lstatcb_(er, lstat) {
        if (er && er.code === "ENOENT")
          return cb();
        var isSym = lstat && lstat.isSymbolicLink();
        self2.symlinks[abs] = isSym;
        if (!isSym && lstat && !lstat.isDirectory()) {
          self2.cache[abs] = "FILE";
          cb();
        } else
          self2._readdir(abs, false, cb);
      }
    };
    Glob.prototype._readdir = function(abs, inGlobStar, cb) {
      if (this.aborted)
        return;
      cb = inflight("readdir\0" + abs + "\0" + inGlobStar, cb);
      if (!cb)
        return;
      if (inGlobStar && !ownProp(this.symlinks, abs))
        return this._readdirInGlobStar(abs, cb);
      if (ownProp(this.cache, abs)) {
        var c5 = this.cache[abs];
        if (!c5 || c5 === "FILE")
          return cb();
        if (Array.isArray(c5))
          return cb(null, c5);
      }
      var self2 = this;
      self2.fs.readdir(abs, readdirCb(this, abs, cb));
    };
    function readdirCb(self2, abs, cb) {
      return function(er, entries) {
        if (er)
          self2._readdirError(abs, er, cb);
        else
          self2._readdirEntries(abs, entries, cb);
      };
    }
    Glob.prototype._readdirEntries = function(abs, entries, cb) {
      if (this.aborted)
        return;
      if (!this.mark && !this.stat) {
        for (var i6 = 0; i6 < entries.length; i6++) {
          var e6 = entries[i6];
          if (abs === "/")
            e6 = abs + e6;
          else
            e6 = abs + "/" + e6;
          this.cache[e6] = true;
        }
      }
      this.cache[abs] = entries;
      return cb(null, entries);
    };
    Glob.prototype._readdirError = function(f7, er, cb) {
      if (this.aborted)
        return;
      switch (er.code) {
        case "ENOTSUP":
        // https://github.com/isaacs/node-glob/issues/205
        case "ENOTDIR":
          var abs = this._makeAbs(f7);
          this.cache[abs] = "FILE";
          if (abs === this.cwdAbs) {
            var error2 = new Error(er.code + " invalid cwd " + this.cwd);
            error2.path = this.cwd;
            error2.code = er.code;
            this.emit("error", error2);
            this.abort();
          }
          break;
        case "ENOENT":
        // not terribly unusual
        case "ELOOP":
        case "ENAMETOOLONG":
        case "UNKNOWN":
          this.cache[this._makeAbs(f7)] = false;
          break;
        default:
          this.cache[this._makeAbs(f7)] = false;
          if (this.strict) {
            this.emit("error", er);
            this.abort();
          }
          if (!this.silent)
            console.error("glob error", er);
          break;
      }
      return cb();
    };
    Glob.prototype._processGlobStar = function(prefix2, read, abs, remain, index6, inGlobStar, cb) {
      var self2 = this;
      this._readdir(abs, inGlobStar, function(er, entries) {
        self2._processGlobStar2(prefix2, read, abs, remain, index6, inGlobStar, entries, cb);
      });
    };
    Glob.prototype._processGlobStar2 = function(prefix2, read, abs, remain, index6, inGlobStar, entries, cb) {
      if (!entries)
        return cb();
      var remainWithoutGlobStar = remain.slice(1);
      var gspref = prefix2 ? [prefix2] : [];
      var noGlobStar = gspref.concat(remainWithoutGlobStar);
      this._process(noGlobStar, index6, false, cb);
      var isSym = this.symlinks[abs];
      var len = entries.length;
      if (isSym && inGlobStar)
        return cb();
      for (var i6 = 0; i6 < len; i6++) {
        var e6 = entries[i6];
        if (e6.charAt(0) === "." && !this.dot)
          continue;
        var instead = gspref.concat(entries[i6], remainWithoutGlobStar);
        this._process(instead, index6, true, cb);
        var below = gspref.concat(entries[i6], remain);
        this._process(below, index6, true, cb);
      }
      cb();
    };
    Glob.prototype._processSimple = function(prefix2, index6, cb) {
      var self2 = this;
      this._stat(prefix2, function(er, exists) {
        self2._processSimple2(prefix2, index6, er, exists, cb);
      });
    };
    Glob.prototype._processSimple2 = function(prefix2, index6, er, exists, cb) {
      if (!this.matches[index6])
        this.matches[index6] = /* @__PURE__ */ Object.create(null);
      if (!exists)
        return cb();
      if (prefix2 && isAbsolute(prefix2) && !this.nomount) {
        var trail = /[\/\\]$/.test(prefix2);
        if (prefix2.charAt(0) === "/") {
          prefix2 = path3.join(this.root, prefix2);
        } else {
          prefix2 = path3.resolve(this.root, prefix2);
          if (trail)
            prefix2 += "/";
        }
      }
      if (process.platform === "win32")
        prefix2 = prefix2.replace(/\\/g, "/");
      this._emitMatch(index6, prefix2);
      cb();
    };
    Glob.prototype._stat = function(f7, cb) {
      var abs = this._makeAbs(f7);
      var needDir = f7.slice(-1) === "/";
      if (f7.length > this.maxLength)
        return cb();
      if (!this.stat && ownProp(this.cache, abs)) {
        var c5 = this.cache[abs];
        if (Array.isArray(c5))
          c5 = "DIR";
        if (!needDir || c5 === "DIR")
          return cb(null, c5);
        if (needDir && c5 === "FILE")
          return cb();
      }
      var exists;
      var stat2 = this.statCache[abs];
      if (stat2 !== void 0) {
        if (stat2 === false)
          return cb(null, stat2);
        else {
          var type = stat2.isDirectory() ? "DIR" : "FILE";
          if (needDir && type === "FILE")
            return cb();
          else
            return cb(null, type, stat2);
        }
      }
      var self2 = this;
      var statcb = inflight("stat\0" + abs, lstatcb_);
      if (statcb)
        self2.fs.lstat(abs, statcb);
      function lstatcb_(er, lstat) {
        if (lstat && lstat.isSymbolicLink()) {
          return self2.fs.stat(abs, function(er2, stat3) {
            if (er2)
              self2._stat2(f7, abs, null, lstat, cb);
            else
              self2._stat2(f7, abs, er2, stat3, cb);
          });
        } else {
          self2._stat2(f7, abs, er, lstat, cb);
        }
      }
    };
    Glob.prototype._stat2 = function(f7, abs, er, stat2, cb) {
      if (er && (er.code === "ENOENT" || er.code === "ENOTDIR")) {
        this.statCache[abs] = false;
        return cb();
      }
      var needDir = f7.slice(-1) === "/";
      this.statCache[abs] = stat2;
      if (abs.slice(-1) === "/" && stat2 && !stat2.isDirectory())
        return cb(null, false, stat2);
      var c5 = true;
      if (stat2)
        c5 = stat2.isDirectory() ? "DIR" : "FILE";
      this.cache[abs] = this.cache[abs] || c5;
      if (needDir && c5 === "FILE")
        return cb();
      return cb(null, c5, stat2);
    };
  }
});

// ../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/readline.js
var require_readline = __commonJS({
  "../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/readline.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.prepareReadLine = void 0;
    var prepareReadLine = () => {
      const stdin = process.stdin;
      const stdout = process.stdout;
      const readline = require("readline");
      const rl = readline.createInterface({
        input: stdin,
        escapeCodeTimeout: 50
      });
      readline.emitKeypressEvents(stdin, rl);
      return {
        stdin,
        stdout,
        closable: rl
      };
    };
    exports2.prepareReadLine = prepareReadLine;
  }
});

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

// ../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/utils.js
var require_utils = __commonJS({
  "../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/utils.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.clear = void 0;
    var sisteransi_1 = require_src();
    var strip = (str) => {
      const pattern = [
        "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
        "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
      ].join("|");
      const RGX = new RegExp(pattern, "g");
      return typeof str === "string" ? str.replace(RGX, "") : str;
    };
    var stringWidth = (str) => [...strip(str)].length;
    var clear = function(prompt, perLine) {
      if (!perLine)
        return sisteransi_1.erase.line + sisteransi_1.cursor.to(0);
      let rows = 0;
      const lines = prompt.split(/\r?\n/);
      for (let line of lines) {
        rows += 1 + Math.floor(Math.max(stringWidth(line) - 1, 0) / perLine);
      }
      return sisteransi_1.erase.lines(rows);
    };
    exports2.clear = clear;
  }
});

// ../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js
var require_lodash = __commonJS({
  "../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js"(exports2, module2) {
    "use strict";
    var FUNC_ERROR_TEXT = "Expected a function";
    var NAN = 0 / 0;
    var symbolTag = "[object Symbol]";
    var reTrim = /^\s+|\s+$/g;
    var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
    var reIsBinary = /^0b[01]+$/i;
    var reIsOctal = /^0o[0-7]+$/i;
    var freeParseInt = parseInt;
    var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
    var freeSelf = typeof self == "object" && self && self.Object === Object && self;
    var root = freeGlobal || freeSelf || Function("return this")();
    var objectProto = Object.prototype;
    var objectToString = objectProto.toString;
    var nativeMax = Math.max;
    var nativeMin = Math.min;
    var now = function() {
      return root.Date.now();
    };
    function debounce(func, wait, options) {
      var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
      if (typeof func != "function") {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      wait = toNumber(wait) || 0;
      if (isObject(options)) {
        leading = !!options.leading;
        maxing = "maxWait" in options;
        maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
        trailing = "trailing" in options ? !!options.trailing : trailing;
      }
      function invokeFunc(time) {
        var args = lastArgs, thisArg = lastThis;
        lastArgs = lastThis = void 0;
        lastInvokeTime = time;
        result = func.apply(thisArg, args);
        return result;
      }
      function leadingEdge(time) {
        lastInvokeTime = time;
        timerId = setTimeout(timerExpired, wait);
        return leading ? invokeFunc(time) : result;
      }
      function remainingWait(time) {
        var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result2 = wait - timeSinceLastCall;
        return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2;
      }
      function shouldInvoke(time) {
        var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
        return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
      }
      function timerExpired() {
        var time = now();
        if (shouldInvoke(time)) {
          return trailingEdge(time);
        }
        timerId = setTimeout(timerExpired, remainingWait(time));
      }
      function trailingEdge(time) {
        timerId = void 0;
        if (trailing && lastArgs) {
          return invokeFunc(time);
        }
        lastArgs = lastThis = void 0;
        return result;
      }
      function cancel() {
        if (timerId !== void 0) {
          clearTimeout(timerId);
        }
        lastInvokeTime = 0;
        lastArgs = lastCallTime = lastThis = timerId = void 0;
      }
      function flush2() {
        return timerId === void 0 ? result : trailingEdge(now());
      }
      function debounced() {
        var time = now(), isInvoking = shouldInvoke(time);
        lastArgs = arguments;
        lastThis = this;
        lastCallTime = time;
        if (isInvoking) {
          if (timerId === void 0) {
            return leadingEdge(lastCallTime);
          }
          if (maxing) {
            timerId = setTimeout(timerExpired, wait);
            return invokeFunc(lastCallTime);
          }
        }
        if (timerId === void 0) {
          timerId = setTimeout(timerExpired, wait);
        }
        return result;
      }
      debounced.cancel = cancel;
      debounced.flush = flush2;
      return debounced;
    }
    function throttle(func, wait, options) {
      var leading = true, trailing = true;
      if (typeof func != "function") {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      if (isObject(options)) {
        leading = "leading" in options ? !!options.leading : leading;
        trailing = "trailing" in options ? !!options.trailing : trailing;
      }
      return debounce(func, wait, {
        "leading": leading,
        "maxWait": wait,
        "trailing": trailing
      });
    }
    function isObject(value) {
      var type = typeof value;
      return !!value && (type == "object" || type == "function");
    }
    function isObjectLike(value) {
      return !!value && typeof value == "object";
    }
    function isSymbol(value) {
      return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
    }
    function toNumber(value) {
      if (typeof value == "number") {
        return value;
      }
      if (isSymbol(value)) {
        return NAN;
      }
      if (isObject(value)) {
        var other = typeof value.valueOf == "function" ? value.valueOf() : value;
        value = isObject(other) ? other + "" : other;
      }
      if (typeof value != "string") {
        return value === 0 ? value : +value;
      }
      value = value.replace(reTrim, "");
      var isBinary = reIsBinary.test(value);
      return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
    }
    module2.exports = throttle;
  }
});

// ../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/index.js
var require_hanji = __commonJS({
  "../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/index.js"(exports2) {
    "use strict";
    var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e6) {
            reject(e6);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e6) {
            reject(e6);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __importDefault = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.onTerminate = exports2.renderWithTask = exports2.render = exports2.TaskTerminal = exports2.TaskView = exports2.Terminal = exports2.deferred = exports2.SelectState = exports2.Prompt = void 0;
    var readline_1 = require_readline();
    var sisteransi_1 = require_src();
    var utils_1 = require_utils();
    var lodash_throttle_1 = __importDefault(require_lodash());
    var Prompt3 = class {
      constructor() {
        this.attachCallbacks = [];
        this.detachCallbacks = [];
        this.inputCallbacks = [];
      }
      requestLayout() {
        this.terminal.requestLayout();
      }
      on(type, callback) {
        if (type === "attach") {
          this.attachCallbacks.push(callback);
        } else if (type === "detach") {
          this.detachCallbacks.push(callback);
        } else if (type === "input") {
          this.inputCallbacks.push(callback);
        }
      }
      attach(terminal) {
        this.terminal = terminal;
        this.attachCallbacks.forEach((it) => it(terminal));
      }
      detach(terminal) {
        this.detachCallbacks.forEach((it) => it(terminal));
        this.terminal = void 0;
      }
      input(str, key) {
        this.inputCallbacks.forEach((it) => it(str, key));
      }
    };
    exports2.Prompt = Prompt3;
    var SelectState3 = class {
      constructor(items) {
        this.items = items;
        this.selectedIdx = 0;
      }
      bind(prompt) {
        prompt.on("input", (str, key) => {
          const invalidate = this.consume(str, key);
          if (invalidate)
            prompt.requestLayout();
        });
      }
      consume(str, key) {
        if (!key)
          return false;
        if (key.name === "down") {
          this.selectedIdx = (this.selectedIdx + 1) % this.items.length;
          return true;
        }
        if (key.name === "up") {
          this.selectedIdx -= 1;
          this.selectedIdx = this.selectedIdx < 0 ? this.items.length - 1 : this.selectedIdx;
          return true;
        }
        return false;
      }
    };
    exports2.SelectState = SelectState3;
    var deferred = () => {
      let resolve;
      let reject;
      const promise = new Promise((res, rej) => {
        resolve = res;
        reject = rej;
      });
      return {
        resolve,
        reject,
        promise
      };
    };
    exports2.deferred = deferred;
    var Terminal = class {
      constructor(view5, stdin, stdout, closable) {
        this.view = view5;
        this.stdin = stdin;
        this.stdout = stdout;
        this.closable = closable;
        this.text = "";
        this.status = "idle";
        if (this.stdin.isTTY)
          this.stdin.setRawMode(true);
        const keypress = (str, key) => {
          if (key.name === "c" && key.ctrl === true) {
            this.requestLayout();
            this.view.detach(this);
            this.tearDown(keypress);
            if (terminateHandler) {
              terminateHandler(this.stdin, this.stdout);
              return;
            }
            this.stdout.write(`
^C
`);
            process.exit(1);
          }
          if (key.name === "escape") {
            this.status = "aborted";
            this.requestLayout();
            this.view.detach(this);
            this.tearDown(keypress);
            this.resolve({ status: "aborted", data: void 0 });
            return;
          }
          if (key.name === "return") {
            this.status = "submitted";
            this.requestLayout();
            this.view.detach(this);
            this.tearDown(keypress);
            this.resolve({ status: "submitted", data: this.view.result() });
            return;
          }
          view5.input(str, key);
        };
        this.stdin.on("keypress", keypress);
        this.view.attach(this);
        const { resolve, promise } = (0, exports2.deferred)();
        this.resolve = resolve;
        this.promise = promise;
        this.renderFunc = (0, lodash_throttle_1.default)((str) => {
          this.stdout.write(str);
        });
      }
      tearDown(keypress) {
        this.stdout.write(sisteransi_1.cursor.show);
        this.stdin.removeListener("keypress", keypress);
        if (this.stdin.isTTY)
          this.stdin.setRawMode(false);
        this.closable.close();
      }
      result() {
        return this.promise;
      }
      toggleCursor(state2) {
        if (state2 === "hide") {
          this.stdout.write(sisteransi_1.cursor.hide);
        } else {
          this.stdout.write(sisteransi_1.cursor.show);
        }
      }
      requestLayout() {
        const string = this.view.render(this.status);
        const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
        this.text = string;
        this.renderFunc(`${clearPrefix}${string}`);
      }
    };
    exports2.Terminal = Terminal;
    var TaskView2 = class {
      constructor() {
        this.attachCallbacks = [];
        this.detachCallbacks = [];
      }
      requestLayout() {
        this.terminal.requestLayout();
      }
      attach(terminal) {
        this.terminal = terminal;
        this.attachCallbacks.forEach((it) => it(terminal));
      }
      detach(terminal) {
        this.detachCallbacks.forEach((it) => it(terminal));
        this.terminal = void 0;
      }
      on(type, callback) {
        if (type === "attach") {
          this.attachCallbacks.push(callback);
        } else if (type === "detach") {
          this.detachCallbacks.push(callback);
        }
      }
    };
    exports2.TaskView = TaskView2;
    var TaskTerminal = class {
      constructor(view5, stdout) {
        this.view = view5;
        this.stdout = stdout;
        this.text = "";
        this.view.attach(this);
      }
      requestLayout() {
        const string = this.view.render("pending");
        const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
        this.text = string;
        this.stdout.write(`${clearPrefix}${string}`);
      }
      clear() {
        const string = this.view.render("done");
        this.view.detach(this);
        const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
        this.stdout.write(`${clearPrefix}${string}`);
      }
    };
    exports2.TaskTerminal = TaskTerminal;
    function render7(view5) {
      const { stdin, stdout, closable } = (0, readline_1.prepareReadLine)();
      if (view5 instanceof Prompt3) {
        const terminal = new Terminal(view5, stdin, stdout, closable);
        terminal.requestLayout();
        return terminal.result();
      }
      stdout.write(`${view5}
`);
      closable.close();
      return;
    }
    exports2.render = render7;
    function renderWithTask5(view5, task) {
      return __awaiter(this, void 0, void 0, function* () {
        const terminal = new TaskTerminal(view5, process.stdout);
        terminal.requestLayout();
        const result = yield task;
        terminal.clear();
        return result;
      });
    }
    exports2.renderWithTask = renderWithTask5;
    var terminateHandler;
    function onTerminate(callback) {
      terminateHandler = callback;
    }
    exports2.onTerminate = onTerminate;
  }
});

// src/global.ts
function assertUnreachable(x5) {
  throw new Error("Didn't expect to get here");
}
var originUUID, snapshotVersion, mapValues, mapKeys, mapEntries, customMapEntries;
var init_global = __esm({
  "src/global.ts"() {
    "use strict";
    originUUID = "00000000-0000-0000-0000-000000000000";
    snapshotVersion = "7";
    mapValues = (obj, map2) => {
      const result = Object.keys(obj).reduce(function(result2, key) {
        result2[key] = map2(obj[key]);
        return result2;
      }, {});
      return result;
    };
    mapKeys = (obj, map2) => {
      const result = Object.fromEntries(
        Object.entries(obj).map(([key, val2]) => {
          const newKey = map2(key, val2);
          return [newKey, val2];
        })
      );
      return result;
    };
    mapEntries = (obj, map2) => {
      const result = Object.fromEntries(
        Object.entries(obj).map(([key, val2]) => {
          const [newKey, newVal] = map2(key, val2);
          return [newKey, newVal];
        })
      );
      return result;
    };
    customMapEntries = (obj, map2) => {
      const result = Object.fromEntries(
        Object.entries(obj).map(([key, val2]) => {
          const [newKey, newVal] = map2(key, val2);
          return [newKey, newVal];
        })
      );
      return result;
    };
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/util.js
var util, objectUtil, ZodParsedType, getParsedType;
var init_util = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/util.js"() {
    "use strict";
    (function(util2) {
      util2.assertEqual = (_3) => {
      };
      function assertIs(_arg) {
      }
      util2.assertIs = assertIs;
      function assertNever(_x) {
        throw new Error();
      }
      util2.assertNever = assertNever;
      util2.arrayToEnum = (items) => {
        const obj = {};
        for (const item of items) {
          obj[item] = item;
        }
        return obj;
      };
      util2.getValidEnumValues = (obj) => {
        const validKeys = util2.objectKeys(obj).filter((k5) => typeof obj[obj[k5]] !== "number");
        const filtered = {};
        for (const k5 of validKeys) {
          filtered[k5] = obj[k5];
        }
        return util2.objectValues(filtered);
      };
      util2.objectValues = (obj) => {
        return util2.objectKeys(obj).map(function(e6) {
          return obj[e6];
        });
      };
      util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
        const keys = [];
        for (const key in object) {
          if (Object.prototype.hasOwnProperty.call(object, key)) {
            keys.push(key);
          }
        }
        return keys;
      };
      util2.find = (arr, checker) => {
        for (const item of arr) {
          if (checker(item))
            return item;
        }
        return void 0;
      };
      util2.isInteger = typeof Number.isInteger === "function" ? (val2) => Number.isInteger(val2) : (val2) => typeof val2 === "number" && Number.isFinite(val2) && Math.floor(val2) === val2;
      function joinValues(array2, separator = " | ") {
        return array2.map((val2) => typeof val2 === "string" ? `'${val2}'` : val2).join(separator);
      }
      util2.joinValues = joinValues;
      util2.jsonStringifyReplacer = (_3, value) => {
        if (typeof value === "bigint") {
          return value.toString();
        }
        return value;
      };
    })(util || (util = {}));
    (function(objectUtil2) {
      objectUtil2.mergeShapes = (first, second) => {
        return {
          ...first,
          ...second
          // second overwrites first
        };
      };
    })(objectUtil || (objectUtil = {}));
    ZodParsedType = util.arrayToEnum([
      "string",
      "nan",
      "number",
      "integer",
      "float",
      "boolean",
      "date",
      "bigint",
      "symbol",
      "function",
      "undefined",
      "null",
      "array",
      "object",
      "unknown",
      "promise",
      "void",
      "never",
      "map",
      "set"
    ]);
    getParsedType = (data) => {
      const t6 = typeof data;
      switch (t6) {
        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/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/ZodError.js
var ZodIssueCode, quotelessJson, ZodError;
var init_ZodError = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/ZodError.js"() {
    "use strict";
    init_util();
    ZodIssueCode = 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"
    ]);
    quotelessJson = (obj) => {
      const json = JSON.stringify(obj, null, 2);
      return json.replace(/"([^"]+)":/g, "$1:");
    };
    ZodError = 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(issue) {
          return issue.message;
        };
        const fieldErrors = { _errors: [] };
        const processError = (error2) => {
          for (const issue of error2.issues) {
            if (issue.code === "invalid_union") {
              issue.unionErrors.map(processError);
            } else if (issue.code === "invalid_return_type") {
              processError(issue.returnTypeError);
            } else if (issue.code === "invalid_arguments") {
              processError(issue.argumentsError);
            } else if (issue.path.length === 0) {
              fieldErrors._errors.push(mapper(issue));
            } else {
              let curr = fieldErrors;
              let i6 = 0;
              while (i6 < issue.path.length) {
                const el = issue.path[i6];
                const terminal = i6 === issue.path.length - 1;
                if (!terminal) {
                  curr[el] = curr[el] || { _errors: [] };
                } else {
                  curr[el] = curr[el] || { _errors: [] };
                  curr[el]._errors.push(mapper(issue));
                }
                curr = curr[el];
                i6++;
              }
            }
          }
        };
        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 = (issue) => issue.message) {
        const fieldErrors = {};
        const formErrors = [];
        for (const sub of this.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 };
      }
      get formErrors() {
        return this.flatten();
      }
    };
    ZodError.create = (issues) => {
      const error2 = new ZodError(issues);
      return error2;
    };
  }
});

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

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/errors.js
function setErrorMap(map2) {
  overrideErrorMap = map2;
}
function getErrorMap() {
  return overrideErrorMap;
}
var overrideErrorMap;
var init_errors = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/errors.js"() {
    "use strict";
    init_en();
    overrideErrorMap = en_default;
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/parseUtil.js
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue = makeIssue({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      // contextual error map is first priority
      ctx.schemaErrorMap,
      // then schema-bound map if available
      overrideMap,
      // then global override map
      overrideMap === en_default ? void 0 : en_default
      // then global default map
    ].filter((x5) => !!x5)
  });
  ctx.common.issues.push(issue);
}
var makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync;
var init_parseUtil = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/parseUtil.js"() {
    "use strict";
    init_errors();
    init_en();
    makeIssue = (params) => {
      const { data, path: path3, errorMaps, issueData } = params;
      const fullPath = [...path3, ...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((m6) => !!m6).slice().reverse();
      for (const map2 of maps) {
        errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message;
      }
      return {
        ...issueData,
        path: fullPath,
        message: errorMessage
      };
    };
    EMPTY_PATH = [];
    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 s6 of results) {
          if (s6.status === "aborted")
            return INVALID;
          if (s6.status === "dirty")
            status.dirty();
          arrayValue.push(s6.value);
        }
        return { status: status.value, value: arrayValue };
      }
      static async mergeObjectAsync(status, pairs) {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value
          });
        }
        return _ParseStatus.mergeObjectSync(status, syncPairs);
      }
      static mergeObjectSync(status, pairs) {
        const finalObject = {};
        for (const pair of pairs) {
          const { key, value } = pair;
          if (key.status === "aborted")
            return INVALID;
          if (value.status === "aborted")
            return INVALID;
          if (key.status === "dirty")
            status.dirty();
          if (value.status === "dirty")
            status.dirty();
          if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
            finalObject[key.value] = value.value;
          }
        }
        return { status: status.value, value: finalObject };
      }
    };
    INVALID = Object.freeze({
      status: "aborted"
    });
    DIRTY = (value) => ({ status: "dirty", value });
    OK = (value) => ({ status: "valid", value });
    isAborted = (x5) => x5.status === "aborted";
    isDirty = (x5) => x5.status === "dirty";
    isValid = (x5) => x5.status === "valid";
    isAsync = (x5) => typeof Promise !== "undefined" && x5 instanceof Promise;
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/typeAliases.js
var init_typeAliases = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/typeAliases.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/errorUtil.js
var errorUtil;
var init_errorUtil = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/errorUtil.js"() {
    "use strict";
    (function(errorUtil2) {
      errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
      errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
    })(errorUtil || (errorUtil = {}));
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/types.js
function processCreateParams(params) {
  if (!params)
    return {};
  const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
  if (errorMap2 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap2)
    return { errorMap: errorMap2, description };
  const customMap = (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 };
}
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, version) {
  if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
function isValidJWT(jwt, alg) {
  if (!jwtRegex.test(jwt))
    return false;
  try {
    const [header] = jwt.split(".");
    const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base64));
    if (typeof decoded !== "object" || decoded === null)
      return false;
    if ("typ" in decoded && decoded?.typ !== "JWT")
      return false;
    if (!decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch {
    return false;
  }
}
function isValidCidr(ip, version) {
  if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
    return true;
  }
  if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
    return true;
  }
  return false;
}
function floatSafeRemainder(val2, step) {
  const valDecCount = (val2.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = Number.parseInt(val2.toFixed(decCount).replace(".", ""));
  const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / 10 ** decCount;
}
function deepPartialify(schema6) {
  if (schema6 instanceof ZodObject) {
    const newShape = {};
    for (const key in schema6.shape) {
      const fieldSchema = schema6.shape[key];
      newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema6._def,
      shape: () => newShape
    });
  } else if (schema6 instanceof ZodArray) {
    return new ZodArray({
      ...schema6._def,
      type: deepPartialify(schema6.element)
    });
  } else if (schema6 instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema6.unwrap()));
  } else if (schema6 instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema6.unwrap()));
  } else if (schema6 instanceof ZodTuple) {
    return ZodTuple.create(schema6.items.map((item) => deepPartialify(item)));
  } else {
    return schema6;
  }
}
function mergeValues(a5, b5) {
  const aType = getParsedType(a5);
  const bType = getParsedType(b5);
  if (a5 === b5) {
    return { valid: true, data: a5 };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b5);
    const sharedKeys = util.objectKeys(a5).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a5, ...b5 };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a5[key], b5[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 (a5.length !== b5.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index6 = 0; index6 < a5.length; index6++) {
      const itemA = a5[index6];
      const itemB = b5[index6];
      const sharedValue = mergeValues(itemA, itemB);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a5 === +b5) {
    return { valid: true, data: a5 };
  } else {
    return { valid: false };
  }
}
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}
function cleanParams(params, data) {
  const p5 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
  const p22 = typeof p5 === "string" ? { message: p5 } : p5;
  return p22;
}
function custom(check, _params2 = {}, fatal) {
  if (check)
    return ZodAny.create().superRefine((data, ctx) => {
      const r6 = check(data);
      if (r6 instanceof Promise) {
        return r6.then((r7) => {
          if (!r7) {
            const params = cleanParams(_params2, data);
            const _fatal = params.fatal ?? fatal ?? true;
            ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
          }
        });
      }
      if (!r6) {
        const params = cleanParams(_params2, data);
        const _fatal = params.fatal ?? fatal ?? true;
        ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
      }
      return;
    });
  return ZodAny.create();
}
var ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce, NEVER;
var init_types = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/types.js"() {
    "use strict";
    init_ZodError();
    init_errors();
    init_errorUtil();
    init_parseUtil();
    init_util();
    ParseInputLazyPath = class {
      constructor(parent, value, path3, key) {
        this._cachedPath = [];
        this.parent = parent;
        this.data = value;
        this._path = path3;
        this._key = key;
      }
      get path() {
        if (!this._cachedPath.length) {
          if (Array.isArray(this._key)) {
            this._cachedPath.push(...this._path, ...this._key);
          } else {
            this._cachedPath.push(...this._path, this._key);
          }
        }
        return this._cachedPath;
      }
    };
    handleResult = (ctx, result) => {
      if (isValid(result)) {
        return { success: true, data: result.value };
      } else {
        if (!ctx.common.issues.length) {
          throw new Error("Validation failed but no issues detected.");
        }
        return {
          success: false,
          get error() {
            if (this._error)
              return this._error;
            const error2 = new ZodError(ctx.common.issues);
            this._error = error2;
            return this._error;
          }
        };
      }
    };
    ZodType = class {
      get description() {
        return this._def.description;
      }
      _getType(input) {
        return getParsedType(input.data);
      }
      _getOrReturnCtx(input, ctx) {
        return ctx || {
          common: input.parent.common,
          data: input.data,
          parsedType: getParsedType(input.data),
          schemaErrorMap: this._def.errorMap,
          path: input.path,
          parent: input.parent
        };
      }
      _processInputParams(input) {
        return {
          status: new ParseStatus(),
          ctx: {
            common: input.parent.common,
            data: input.data,
            parsedType: getParsedType(input.data),
            schemaErrorMap: this._def.errorMap,
            path: input.path,
            parent: input.parent
          }
        };
      }
      _parseSync(input) {
        const result = this._parse(input);
        if (isAsync(result)) {
          throw new Error("Synchronous parse encountered promise.");
        }
        return result;
      }
      _parseAsync(input) {
        const result = this._parse(input);
        return Promise.resolve(result);
      }
      parse(data, params) {
        const result = this.safeParse(data, params);
        if (result.success)
          return result.data;
        throw result.error;
      }
      safeParse(data, params) {
        const ctx = {
          common: {
            issues: [],
            async: params?.async ?? false,
            contextualErrorMap: params?.errorMap
          },
          path: params?.path || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        const result = this._parseSync({ data, path: ctx.path, parent: ctx });
        return handleResult(ctx, result);
      }
      "~validate"(data) {
        const ctx = {
          common: {
            issues: [],
            async: !!this["~standard"].async
          },
          path: [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        if (!this["~standard"].async) {
          try {
            const result = this._parseSync({ data, path: [], parent: ctx });
            return isValid(result) ? {
              value: result.value
            } : {
              issues: ctx.common.issues
            };
          } catch (err2) {
            if (err2?.message?.toLowerCase()?.includes("encountered")) {
              this["~standard"].async = true;
            }
            ctx.common = {
              issues: [],
              async: true
            };
          }
        }
        return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
          value: result.value
        } : {
          issues: ctx.common.issues
        });
      }
      async parseAsync(data, params) {
        const result = await this.safeParseAsync(data, params);
        if (result.success)
          return result.data;
        throw result.error;
      }
      async safeParseAsync(data, params) {
        const ctx = {
          common: {
            issues: [],
            contextualErrorMap: params?.errorMap,
            async: true
          },
          path: params?.path || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
        const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
        return handleResult(ctx, result);
      }
      refine(check, message) {
        const getIssueProperties = (val2) => {
          if (typeof message === "string" || typeof message === "undefined") {
            return { message };
          } else if (typeof message === "function") {
            return message(val2);
          } else {
            return message;
          }
        };
        return this._refinement((val2, ctx) => {
          const result = check(val2);
          const setError = () => ctx.addIssue({
            code: ZodIssueCode.custom,
            ...getIssueProperties(val2)
          });
          if (typeof Promise !== "undefined" && result instanceof Promise) {
            return result.then((data) => {
              if (!data) {
                setError();
                return false;
              } else {
                return true;
              }
            });
          }
          if (!result) {
            setError();
            return false;
          } else {
            return true;
          }
        });
      }
      refinement(check, refinementData) {
        return this._refinement((val2, ctx) => {
          if (!check(val2)) {
            ctx.addIssue(typeof refinementData === "function" ? refinementData(val2, ctx) : refinementData);
            return false;
          } else {
            return true;
          }
        });
      }
      _refinement(refinement) {
        return new ZodEffects({
          schema: this,
          typeName: ZodFirstPartyTypeKind.ZodEffects,
          effect: { type: "refinement", refinement }
        });
      }
      superRefine(refinement) {
        return this._refinement(refinement);
      }
      constructor(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 ZodOptional.create(this, this._def);
      }
      nullable() {
        return ZodNullable.create(this, this._def);
      }
      nullish() {
        return this.nullable().optional();
      }
      array() {
        return ZodArray.create(this);
      }
      promise() {
        return ZodPromise.create(this, this._def);
      }
      or(option) {
        return ZodUnion.create([this, option], this._def);
      }
      and(incoming) {
        return ZodIntersection.create(this, incoming, this._def);
      }
      transform(transform) {
        return new ZodEffects({
          ...processCreateParams(this._def),
          schema: this,
          typeName: ZodFirstPartyTypeKind.ZodEffects,
          effect: { type: "transform", transform }
        });
      }
      default(def) {
        const defaultValueFunc = typeof def === "function" ? def : () => def;
        return new ZodDefault({
          ...processCreateParams(this._def),
          innerType: this,
          defaultValue: defaultValueFunc,
          typeName: ZodFirstPartyTypeKind.ZodDefault
        });
      }
      brand() {
        return new ZodBranded({
          typeName: ZodFirstPartyTypeKind.ZodBranded,
          type: this,
          ...processCreateParams(this._def)
        });
      }
      catch(def) {
        const catchValueFunc = typeof def === "function" ? def : () => def;
        return new ZodCatch({
          ...processCreateParams(this._def),
          innerType: this,
          catchValue: catchValueFunc,
          typeName: ZodFirstPartyTypeKind.ZodCatch
        });
      }
      describe(description) {
        const This = this.constructor;
        return new This({
          ...this._def,
          description
        });
      }
      pipe(target) {
        return ZodPipeline.create(this, target);
      }
      readonly() {
        return ZodReadonly.create(this);
      }
      isOptional() {
        return this.safeParse(void 0).success;
      }
      isNullable() {
        return this.safeParse(null).success;
      }
    };
    cuidRegex = /^c[^\s-]{8,}$/i;
    cuid2Regex = /^[0-9a-z]+$/;
    ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
    uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
    nanoidRegex = /^[a-z0-9_-]{21}$/i;
    jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
    durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
    emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
    _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
    ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
    ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
    ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
    ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
    base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
    base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
    dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
    dateRegex = new RegExp(`^${dateRegexSource}$`);
    ZodString = class _ZodString extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = String(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.string) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.string,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        const status = new ParseStatus();
        let ctx = void 0;
        for (const check of this._def.checks) {
          if (check.kind === "min") {
            if (input.data.length < check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            if (input.data.length > check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "length") {
            const tooBig = input.data.length > check.value;
            const tooSmall = input.data.length < check.value;
            if (tooBig || tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              if (tooBig) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_big,
                  maximum: check.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check.message
                });
              } else if (tooSmall) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_small,
                  minimum: check.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check.message
                });
              }
              status.dirty();
            }
          } else if (check.kind === "email") {
            if (!emailRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "email",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "emoji") {
            if (!emojiRegex) {
              emojiRegex = new RegExp(_emojiRegex, "u");
            }
            if (!emojiRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "emoji",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "uuid") {
            if (!uuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "uuid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "nanoid") {
            if (!nanoidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "nanoid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cuid") {
            if (!cuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cuid2") {
            if (!cuid2Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid2",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "ulid") {
            if (!ulidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ulid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "url") {
            try {
              new URL(input.data);
            } catch {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "url",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "regex") {
            check.regex.lastIndex = 0;
            const testResult = check.regex.test(input.data);
            if (!testResult) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "regex",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "trim") {
            input.data = input.data.trim();
          } else if (check.kind === "includes") {
            if (!input.data.includes(check.value, check.position)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { includes: check.value, position: check.position },
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "toLowerCase") {
            input.data = input.data.toLowerCase();
          } else if (check.kind === "toUpperCase") {
            input.data = input.data.toUpperCase();
          } else if (check.kind === "startsWith") {
            if (!input.data.startsWith(check.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { startsWith: check.value },
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "endsWith") {
            if (!input.data.endsWith(check.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { endsWith: check.value },
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "datetime") {
            const regex = datetimeRegex(check);
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "datetime",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "date") {
            const regex = dateRegex;
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "date",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "time") {
            const regex = timeRegex(check);
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "time",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "duration") {
            if (!durationRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "duration",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "ip") {
            if (!isValidIP(input.data, check.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ip",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "jwt") {
            if (!isValidJWT(input.data, check.alg)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "jwt",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cidr") {
            if (!isValidCidr(input.data, check.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cidr",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "base64") {
            if (!base64Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "base64url") {
            if (!base64urlRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64url",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        return { status: status.value, value: input.data };
      }
      _regex(regex, validation, message) {
        return this.refinement((data) => regex.test(data), {
          validation,
          code: ZodIssueCode.invalid_string,
          ...errorUtil.errToObj(message)
        });
      }
      _addCheck(check) {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      email(message) {
        return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
      }
      url(message) {
        return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
      }
      emoji(message) {
        return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
      }
      uuid(message) {
        return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
      }
      nanoid(message) {
        return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
      }
      cuid(message) {
        return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
      }
      cuid2(message) {
        return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
      }
      ulid(message) {
        return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
      }
      base64(message) {
        return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
      }
      base64url(message) {
        return this._addCheck({
          kind: "base64url",
          ...errorUtil.errToObj(message)
        });
      }
      jwt(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 _ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "trim" }]
        });
      }
      toLowerCase() {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "toLowerCase" }]
        });
      }
      toUpperCase() {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "toUpperCase" }]
        });
      }
      get isDatetime() {
        return !!this._def.checks.find((ch) => ch.kind === "datetime");
      }
      get isDate() {
        return !!this._def.checks.find((ch) => ch.kind === "date");
      }
      get isTime() {
        return !!this._def.checks.find((ch) => ch.kind === "time");
      }
      get isDuration() {
        return !!this._def.checks.find((ch) => ch.kind === "duration");
      }
      get isEmail() {
        return !!this._def.checks.find((ch) => ch.kind === "email");
      }
      get isURL() {
        return !!this._def.checks.find((ch) => ch.kind === "url");
      }
      get isEmoji() {
        return !!this._def.checks.find((ch) => ch.kind === "emoji");
      }
      get isUUID() {
        return !!this._def.checks.find((ch) => ch.kind === "uuid");
      }
      get isNANOID() {
        return !!this._def.checks.find((ch) => ch.kind === "nanoid");
      }
      get isCUID() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid");
      }
      get isCUID2() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid2");
      }
      get isULID() {
        return !!this._def.checks.find((ch) => ch.kind === "ulid");
      }
      get isIP() {
        return !!this._def.checks.find((ch) => ch.kind === "ip");
      }
      get isCIDR() {
        return !!this._def.checks.find((ch) => ch.kind === "cidr");
      }
      get isBase64() {
        return !!this._def.checks.find((ch) => ch.kind === "base64");
      }
      get isBase64url() {
        return !!this._def.checks.find((ch) => ch.kind === "base64url");
      }
      get minLength() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min;
      }
      get maxLength() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
    };
    ZodString.create = (params) => {
      return new ZodString({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodString,
        coerce: params?.coerce ?? false,
        ...processCreateParams(params)
      });
    };
    ZodNumber = class _ZodNumber extends ZodType {
      constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
        this.step = this.multipleOf;
      }
      _parse(input) {
        if (this._def.coerce) {
          input.data = Number(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.number) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.number,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        let ctx = void 0;
        const status = new ParseStatus();
        for (const check of this._def.checks) {
          if (check.kind === "int") {
            if (!util.isInteger(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: "integer",
                received: "float",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "min") {
            const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check.value,
                type: "number",
                inclusive: check.inclusive,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check.value,
                type: "number",
                inclusive: check.inclusive,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "multipleOf") {
            if (floatSafeRemainder(input.data, check.value) !== 0) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check.value,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "finite") {
            if (!Number.isFinite(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_finite,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        return { status: status.value, value: input.data };
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
      }
      setLimit(kind, value, inclusive, message) {
        return new _ZodNumber({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check) {
        return new _ZodNumber({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      int(message) {
        return this._addCheck({
          kind: "int",
          message: errorUtil.toString(message)
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      finite(message) {
        return this._addCheck({
          kind: "finite",
          message: errorUtil.toString(message)
        });
      }
      safe(message) {
        return this._addCheck({
          kind: "min",
          inclusive: true,
          value: Number.MIN_SAFE_INTEGER,
          message: errorUtil.toString(message)
        })._addCheck({
          kind: "max",
          inclusive: true,
          value: Number.MAX_SAFE_INTEGER,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min;
      }
      get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
      get isInt() {
        return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && 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);
      }
    };
    ZodNumber.create = (params) => {
      return new ZodNumber({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodNumber,
        coerce: params?.coerce || false,
        ...processCreateParams(params)
      });
    };
    ZodBigInt = class _ZodBigInt extends ZodType {
      constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
      }
      _parse(input) {
        if (this._def.coerce) {
          try {
            input.data = BigInt(input.data);
          } catch {
            return this._getInvalidInput(input);
          }
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.bigint) {
          return this._getInvalidInput(input);
        }
        let ctx = void 0;
        const status = new ParseStatus();
        for (const check of this._def.checks) {
          if (check.kind === "min") {
            const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                type: "bigint",
                minimum: check.value,
                inclusive: check.inclusive,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                type: "bigint",
                maximum: check.value,
                inclusive: check.inclusive,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "multipleOf") {
            if (input.data % check.value !== BigInt(0)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check.value,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        return { status: status.value, value: input.data };
      }
      _getInvalidInput(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_type,
          expected: ZodParsedType.bigint,
          received: ctx.parsedType
        });
        return INVALID;
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
      }
      setLimit(kind, value, inclusive, message) {
        return new _ZodBigInt({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check) {
        return new _ZodBigInt({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min;
      }
      get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
    };
    ZodBigInt.create = (params) => {
      return new ZodBigInt({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodBigInt,
        coerce: params?.coerce ?? false,
        ...processCreateParams(params)
      });
    };
    ZodBoolean = class extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = Boolean(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.boolean) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.boolean,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodBoolean.create = (params) => {
      return new ZodBoolean({
        typeName: ZodFirstPartyTypeKind.ZodBoolean,
        coerce: params?.coerce || false,
        ...processCreateParams(params)
      });
    };
    ZodDate = class _ZodDate extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = new Date(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.date) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.date,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        if (Number.isNaN(input.data.getTime())) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_date
          });
          return INVALID;
        }
        const status = new ParseStatus();
        let ctx = void 0;
        for (const check of this._def.checks) {
          if (check.kind === "min") {
            if (input.data.getTime() < check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                message: check.message,
                inclusive: true,
                exact: false,
                minimum: check.value,
                type: "date"
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            if (input.data.getTime() > check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                message: check.message,
                inclusive: true,
                exact: false,
                maximum: check.value,
                type: "date"
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        return {
          status: status.value,
          value: new Date(input.data.getTime())
        };
      }
      _addCheck(check) {
        return new _ZodDate({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      min(minDate, message) {
        return this._addCheck({
          kind: "min",
          value: minDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      max(maxDate, message) {
        return this._addCheck({
          kind: "max",
          value: maxDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      get minDate() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min != null ? new Date(min) : null;
      }
      get maxDate() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max != null ? new Date(max) : null;
      }
    };
    ZodDate.create = (params) => {
      return new ZodDate({
        checks: [],
        coerce: params?.coerce || false,
        typeName: ZodFirstPartyTypeKind.ZodDate,
        ...processCreateParams(params)
      });
    };
    ZodSymbol = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.symbol) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.symbol,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodSymbol.create = (params) => {
      return new ZodSymbol({
        typeName: ZodFirstPartyTypeKind.ZodSymbol,
        ...processCreateParams(params)
      });
    };
    ZodUndefined = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.undefined,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodUndefined.create = (params) => {
      return new ZodUndefined({
        typeName: ZodFirstPartyTypeKind.ZodUndefined,
        ...processCreateParams(params)
      });
    };
    ZodNull = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.null) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.null,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodNull.create = (params) => {
      return new ZodNull({
        typeName: ZodFirstPartyTypeKind.ZodNull,
        ...processCreateParams(params)
      });
    };
    ZodAny = class extends ZodType {
      constructor() {
        super(...arguments);
        this._any = true;
      }
      _parse(input) {
        return OK(input.data);
      }
    };
    ZodAny.create = (params) => {
      return new ZodAny({
        typeName: ZodFirstPartyTypeKind.ZodAny,
        ...processCreateParams(params)
      });
    };
    ZodUnknown = class extends ZodType {
      constructor() {
        super(...arguments);
        this._unknown = true;
      }
      _parse(input) {
        return OK(input.data);
      }
    };
    ZodUnknown.create = (params) => {
      return new ZodUnknown({
        typeName: ZodFirstPartyTypeKind.ZodUnknown,
        ...processCreateParams(params)
      });
    };
    ZodNever = class extends ZodType {
      _parse(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_type,
          expected: ZodParsedType.never,
          received: ctx.parsedType
        });
        return INVALID;
      }
    };
    ZodNever.create = (params) => {
      return new ZodNever({
        typeName: ZodFirstPartyTypeKind.ZodNever,
        ...processCreateParams(params)
      });
    };
    ZodVoid = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.void,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodVoid.create = (params) => {
      return new ZodVoid({
        typeName: ZodFirstPartyTypeKind.ZodVoid,
        ...processCreateParams(params)
      });
    };
    ZodArray = class _ZodArray extends ZodType {
      _parse(input) {
        const { ctx, status } = this._processInputParams(input);
        const def = this._def;
        if (ctx.parsedType !== ZodParsedType.array) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.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 ? ZodIssueCode.too_big : ZodIssueCode.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: ZodIssueCode.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: ZodIssueCode.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, i6) => {
            return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i6));
          })).then((result2) => {
            return ParseStatus.mergeArray(status, result2);
          });
        }
        const result = [...ctx.data].map((item, i6) => {
          return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i6));
        });
        return ParseStatus.mergeArray(status, result);
      }
      get element() {
        return this._def.type;
      }
      min(minLength, message) {
        return new _ZodArray({
          ...this._def,
          minLength: { value: minLength, message: errorUtil.toString(message) }
        });
      }
      max(maxLength, message) {
        return new _ZodArray({
          ...this._def,
          maxLength: { value: maxLength, message: errorUtil.toString(message) }
        });
      }
      length(len, message) {
        return new _ZodArray({
          ...this._def,
          exactLength: { value: len, message: errorUtil.toString(message) }
        });
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    ZodArray.create = (schema6, params) => {
      return new ZodArray({
        type: schema6,
        minLength: null,
        maxLength: null,
        exactLength: null,
        typeName: ZodFirstPartyTypeKind.ZodArray,
        ...processCreateParams(params)
      });
    };
    ZodObject = class _ZodObject extends ZodType {
      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 parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.object) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        const { status, ctx } = this._processInputParams(input);
        const { shape, keys: shapeKeys } = this._getCached();
        const extraKeys = [];
        if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
          for (const key in ctx.data) {
            if (!shapeKeys.includes(key)) {
              extraKeys.push(key);
            }
          }
        }
        const pairs = [];
        for (const key of shapeKeys) {
          const keyValidator = shape[key];
          const value = ctx.data[key];
          pairs.push({
            key: { status: "valid", value: key },
            value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
            alwaysSet: key in ctx.data
          });
        }
        if (this._def.catchall instanceof ZodNever) {
          const unknownKeys = this._def.unknownKeys;
          if (unknownKeys === "passthrough") {
            for (const key of extraKeys) {
              pairs.push({
                key: { status: "valid", value: key },
                value: { status: "valid", value: ctx.data[key] }
              });
            }
          } else if (unknownKeys === "strict") {
            if (extraKeys.length > 0) {
              addIssueToContext(ctx, {
                code: ZodIssueCode.unrecognized_keys,
                keys: extraKeys
              });
              status.dirty();
            }
          } else if (unknownKeys === "strip") {
          } else {
            throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
          }
        } else {
          const catchall = this._def.catchall;
          for (const key of extraKeys) {
            const value = ctx.data[key];
            pairs.push({
              key: { status: "valid", value: key },
              value: catchall._parse(
                new ParseInputLazyPath(ctx, value, ctx.path, key)
                //, ctx.child(key), value, getParsedType(value)
              ),
              alwaysSet: key in ctx.data
            });
          }
        }
        if (ctx.common.async) {
          return Promise.resolve().then(async () => {
            const syncPairs = [];
            for (const pair of pairs) {
              const key = await pair.key;
              const value = await pair.value;
              syncPairs.push({
                key,
                value,
                alwaysSet: pair.alwaysSet
              });
            }
            return syncPairs;
          }).then((syncPairs) => {
            return ParseStatus.mergeObjectSync(status, syncPairs);
          });
        } else {
          return ParseStatus.mergeObjectSync(status, pairs);
        }
      }
      get shape() {
        return this._def.shape();
      }
      strict(message) {
        errorUtil.errToObj;
        return new _ZodObject({
          ...this._def,
          unknownKeys: "strict",
          ...message !== void 0 ? {
            errorMap: (issue, ctx) => {
              const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
              if (issue.code === "unrecognized_keys")
                return {
                  message: errorUtil.errToObj(message).message ?? defaultError
                };
              return {
                message: defaultError
              };
            }
          } : {}
        });
      }
      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: ZodFirstPartyTypeKind.ZodObject
        });
        return merged;
      }
      // merge<
      //   Incoming extends AnyZodObject,
      //   Augmentation extends Incoming["shape"],
      //   NewOutput extends {
      //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
      //       ? Augmentation[k]["_output"]
      //       : k extends keyof Output
      //       ? Output[k]
      //       : never;
      //   },
      //   NewInput extends {
      //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
      //       ? Augmentation[k]["_input"]
      //       : k extends keyof Input
      //       ? Input[k]
      //       : never;
      //   }
      // >(
      //   merging: Incoming
      // ): ZodObject<
      //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
      //   Incoming["_def"]["unknownKeys"],
      //   Incoming["_def"]["catchall"],
      //   NewOutput,
      //   NewInput
      // > {
      //   const merged: any = new ZodObject({
      //     unknownKeys: merging._def.unknownKeys,
      //     catchall: merging._def.catchall,
      //     shape: () =>
      //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
      //     typeName: ZodFirstPartyTypeKind.ZodObject,
      //   }) as any;
      //   return merged;
      // }
      setKey(key, schema6) {
        return this.augment({ [key]: schema6 });
      }
      // 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(index6) {
        return new _ZodObject({
          ...this._def,
          catchall: index6
        });
      }
      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 ZodOptional) {
              newField = newField._def.innerType;
            }
            newShape[key] = newField;
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => newShape
        });
      }
      keyof() {
        return createZodEnum(util.objectKeys(this.shape));
      }
    };
    ZodObject.create = (shape, params) => {
      return new ZodObject({
        shape: () => shape,
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodObject.strictCreate = (shape, params) => {
      return new ZodObject({
        shape: () => shape,
        unknownKeys: "strict",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodObject.lazycreate = (shape, params) => {
      return new ZodObject({
        shape,
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodUnion = class extends ZodType {
      _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 ZodError(result.ctx.common.issues));
          addIssueToContext(ctx, {
            code: ZodIssueCode.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 ZodError(issues2));
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union,
            unionErrors
          });
          return INVALID;
        }
      }
      get options() {
        return this._def.options;
      }
    };
    ZodUnion.create = (types3, params) => {
      return new ZodUnion({
        options: types3,
        typeName: ZodFirstPartyTypeKind.ZodUnion,
        ...processCreateParams(params)
      });
    };
    getDiscriminator = (type) => {
      if (type instanceof ZodLazy) {
        return getDiscriminator(type.schema);
      } else if (type instanceof ZodEffects) {
        return getDiscriminator(type.innerType());
      } else if (type instanceof ZodLiteral) {
        return [type.value];
      } else if (type instanceof ZodEnum) {
        return type.options;
      } else if (type instanceof ZodNativeEnum) {
        return util.objectValues(type.enum);
      } else if (type instanceof ZodDefault) {
        return getDiscriminator(type._def.innerType);
      } else if (type instanceof ZodUndefined) {
        return [void 0];
      } else if (type instanceof ZodNull) {
        return [null];
      } else if (type instanceof ZodOptional) {
        return [void 0, ...getDiscriminator(type.unwrap())];
      } else if (type instanceof ZodNullable) {
        return [null, ...getDiscriminator(type.unwrap())];
      } else if (type instanceof ZodBranded) {
        return getDiscriminator(type.unwrap());
      } else if (type instanceof ZodReadonly) {
        return getDiscriminator(type.unwrap());
      } else if (type instanceof ZodCatch) {
        return getDiscriminator(type._def.innerType);
      } else {
        return [];
      }
    };
    ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const discriminator = this.discriminator;
        const discriminatorValue = ctx.data[discriminator];
        const option = this.optionsMap.get(discriminatorValue);
        if (!option) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.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: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
          discriminator,
          options,
          optionsMap,
          ...processCreateParams(params)
        });
      }
    };
    ZodIntersection = class extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const handleParsed = (parsedLeft, parsedRight) => {
          if (isAborted(parsedLeft) || isAborted(parsedRight)) {
            return INVALID;
          }
          const merged = mergeValues(parsedLeft.value, parsedRight.value);
          if (!merged.valid) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.invalid_intersection_types
            });
            return INVALID;
          }
          if (isDirty(parsedLeft) || isDirty(parsedRight)) {
            status.dirty();
          }
          return { status: status.value, value: merged.data };
        };
        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
          }));
        }
      }
    };
    ZodIntersection.create = (left, right, params) => {
      return new ZodIntersection({
        left,
        right,
        typeName: ZodFirstPartyTypeKind.ZodIntersection,
        ...processCreateParams(params)
      });
    };
    ZodTuple = class _ZodTuple extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.array) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.array,
            received: ctx.parsedType
          });
          return INVALID;
        }
        if (ctx.data.length < this._def.items.length) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: this._def.items.length,
            inclusive: true,
            exact: false,
            type: "array"
          });
          return INVALID;
        }
        const rest = this._def.rest;
        if (!rest && ctx.data.length > this._def.items.length) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: this._def.items.length,
            inclusive: true,
            exact: false,
            type: "array"
          });
          status.dirty();
        }
        const items = [...ctx.data].map((item, itemIndex) => {
          const schema6 = this._def.items[itemIndex] || this._def.rest;
          if (!schema6)
            return null;
          return schema6._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
        }).filter((x5) => !!x5);
        if (ctx.common.async) {
          return Promise.all(items).then((results) => {
            return ParseStatus.mergeArray(status, results);
          });
        } else {
          return ParseStatus.mergeArray(status, items);
        }
      }
      get items() {
        return this._def.items;
      }
      rest(rest) {
        return new _ZodTuple({
          ...this._def,
          rest
        });
      }
    };
    ZodTuple.create = (schemas, params) => {
      if (!Array.isArray(schemas)) {
        throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
      }
      return new ZodTuple({
        items: schemas,
        typeName: ZodFirstPartyTypeKind.ZodTuple,
        rest: null,
        ...processCreateParams(params)
      });
    };
    ZodRecord = class _ZodRecord extends ZodType {
      get keySchema() {
        return this._def.keyType;
      }
      get valueSchema() {
        return this._def.valueType;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const pairs = [];
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        for (const key in ctx.data) {
          pairs.push({
            key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
            value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
            alwaysSet: key in ctx.data
          });
        }
        if (ctx.common.async) {
          return ParseStatus.mergeObjectAsync(status, pairs);
        } else {
          return ParseStatus.mergeObjectSync(status, pairs);
        }
      }
      get element() {
        return this._def.valueType;
      }
      static create(first, second, third) {
        if (second instanceof ZodType) {
          return new _ZodRecord({
            keyType: first,
            valueType: second,
            typeName: ZodFirstPartyTypeKind.ZodRecord,
            ...processCreateParams(third)
          });
        }
        return new _ZodRecord({
          keyType: ZodString.create(),
          valueType: first,
          typeName: ZodFirstPartyTypeKind.ZodRecord,
          ...processCreateParams(second)
        });
      }
    };
    ZodMap = class extends ZodType {
      get keySchema() {
        return this._def.keyType;
      }
      get valueSchema() {
        return this._def.valueType;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.map) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.map,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        const pairs = [...ctx.data.entries()].map(([key, value], index6) => {
          return {
            key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index6, "key"])),
            value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index6, "value"]))
          };
        });
        if (ctx.common.async) {
          const finalMap = /* @__PURE__ */ new Map();
          return Promise.resolve().then(async () => {
            for (const pair of pairs) {
              const key = await pair.key;
              const value = await pair.value;
              if (key.status === "aborted" || value.status === "aborted") {
                return INVALID;
              }
              if (key.status === "dirty" || value.status === "dirty") {
                status.dirty();
              }
              finalMap.set(key.value, value.value);
            }
            return { status: status.value, value: finalMap };
          });
        } else {
          const finalMap = /* @__PURE__ */ new Map();
          for (const pair of pairs) {
            const key = pair.key;
            const value = pair.value;
            if (key.status === "aborted" || value.status === "aborted") {
              return INVALID;
            }
            if (key.status === "dirty" || value.status === "dirty") {
              status.dirty();
            }
            finalMap.set(key.value, value.value);
          }
          return { status: status.value, value: finalMap };
        }
      }
    };
    ZodMap.create = (keyType, valueType, params) => {
      return new ZodMap({
        valueType,
        keyType,
        typeName: ZodFirstPartyTypeKind.ZodMap,
        ...processCreateParams(params)
      });
    };
    ZodSet = class _ZodSet extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.set) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.set,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const def = this._def;
        if (def.minSize !== null) {
          if (ctx.data.size < def.minSize.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.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: ZodIssueCode.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, i6) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i6)));
        if (ctx.common.async) {
          return Promise.all(elements).then((elements2) => finalizeSet(elements2));
        } else {
          return finalizeSet(elements);
        }
      }
      min(minSize, message) {
        return new _ZodSet({
          ...this._def,
          minSize: { value: minSize, message: errorUtil.toString(message) }
        });
      }
      max(maxSize, message) {
        return new _ZodSet({
          ...this._def,
          maxSize: { value: maxSize, message: errorUtil.toString(message) }
        });
      }
      size(size, message) {
        return this.min(size, message).max(size, message);
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    ZodSet.create = (valueType, params) => {
      return new ZodSet({
        valueType,
        minSize: null,
        maxSize: null,
        typeName: ZodFirstPartyTypeKind.ZodSet,
        ...processCreateParams(params)
      });
    };
    ZodFunction = class _ZodFunction extends ZodType {
      constructor() {
        super(...arguments);
        this.validate = this.implement;
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.function) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.function,
            received: ctx.parsedType
          });
          return INVALID;
        }
        function makeArgsIssue(args, error2) {
          return makeIssue({
            data: args,
            path: ctx.path,
            errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x5) => !!x5),
            issueData: {
              code: ZodIssueCode.invalid_arguments,
              argumentsError: error2
            }
          });
        }
        function makeReturnsIssue(returns, error2) {
          return makeIssue({
            data: returns,
            path: ctx.path,
            errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x5) => !!x5),
            issueData: {
              code: ZodIssueCode.invalid_return_type,
              returnTypeError: error2
            }
          });
        }
        const params = { errorMap: ctx.common.contextualErrorMap };
        const fn = ctx.data;
        if (this._def.returns instanceof ZodPromise) {
          const me = this;
          return OK(async function(...args) {
            const error2 = new ZodError([]);
            const parsedArgs = await me._def.args.parseAsync(args, params).catch((e6) => {
              error2.addIssue(makeArgsIssue(args, e6));
              throw error2;
            });
            const result = await Reflect.apply(fn, this, parsedArgs);
            const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e6) => {
              error2.addIssue(makeReturnsIssue(result, e6));
              throw error2;
            });
            return parsedReturns;
          });
        } else {
          const me = this;
          return OK(function(...args) {
            const parsedArgs = me._def.args.safeParse(args, params);
            if (!parsedArgs.success) {
              throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
            }
            const result = Reflect.apply(fn, this, parsedArgs.data);
            const parsedReturns = me._def.returns.safeParse(result, params);
            if (!parsedReturns.success) {
              throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
            }
            return parsedReturns.data;
          });
        }
      }
      parameters() {
        return this._def.args;
      }
      returnType() {
        return this._def.returns;
      }
      args(...items) {
        return new _ZodFunction({
          ...this._def,
          args: ZodTuple.create(items).rest(ZodUnknown.create())
        });
      }
      returns(returnType) {
        return new _ZodFunction({
          ...this._def,
          returns: returnType
        });
      }
      implement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
      }
      strictImplement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
      }
      static create(args, returns, params) {
        return new _ZodFunction({
          args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
          returns: returns || ZodUnknown.create(),
          typeName: ZodFirstPartyTypeKind.ZodFunction,
          ...processCreateParams(params)
        });
      }
    };
    ZodLazy = class extends ZodType {
      get schema() {
        return this._def.getter();
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const lazySchema = this._def.getter();
        return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
      }
    };
    ZodLazy.create = (getter, params) => {
      return new ZodLazy({
        getter,
        typeName: ZodFirstPartyTypeKind.ZodLazy,
        ...processCreateParams(params)
      });
    };
    ZodLiteral = class extends ZodType {
      _parse(input) {
        if (input.data !== this._def.value) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_literal,
            expected: this._def.value
          });
          return INVALID;
        }
        return { status: "valid", value: input.data };
      }
      get value() {
        return this._def.value;
      }
    };
    ZodLiteral.create = (value, params) => {
      return new ZodLiteral({
        value,
        typeName: ZodFirstPartyTypeKind.ZodLiteral,
        ...processCreateParams(params)
      });
    };
    ZodEnum = class _ZodEnum extends ZodType {
      _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: ZodIssueCode.invalid_type
          });
          return INVALID;
        }
        if (!this._cache) {
          this._cache = new Set(this._def.values);
        }
        if (!this._cache.has(input.data)) {
          const ctx = this._getOrReturnCtx(input);
          const expectedValues = this._def.values;
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_enum_value,
            options: expectedValues
          });
          return INVALID;
        }
        return OK(input.data);
      }
      get options() {
        return this._def.values;
      }
      get enum() {
        const enumValues = {};
        for (const val2 of this._def.values) {
          enumValues[val2] = val2;
        }
        return enumValues;
      }
      get Values() {
        const enumValues = {};
        for (const val2 of this._def.values) {
          enumValues[val2] = val2;
        }
        return enumValues;
      }
      get Enum() {
        const enumValues = {};
        for (const val2 of this._def.values) {
          enumValues[val2] = val2;
        }
        return enumValues;
      }
      extract(values, newDef = this._def) {
        return _ZodEnum.create(values, {
          ...this._def,
          ...newDef
        });
      }
      exclude(values, newDef = this._def) {
        return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
          ...this._def,
          ...newDef
        });
      }
    };
    ZodEnum.create = createZodEnum;
    ZodNativeEnum = class extends ZodType {
      _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: ZodIssueCode.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: ZodIssueCode.invalid_enum_value,
            options: expectedValues
          });
          return INVALID;
        }
        return OK(input.data);
      }
      get enum() {
        return this._def.values;
      }
    };
    ZodNativeEnum.create = (values, params) => {
      return new ZodNativeEnum({
        values,
        typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
        ...processCreateParams(params)
      });
    };
    ZodPromise = class extends ZodType {
      unwrap() {
        return this._def.type;
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.promise,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
        return OK(promisified.then((data) => {
          return this._def.type.parseAsync(data, {
            path: ctx.path,
            errorMap: ctx.common.contextualErrorMap
          });
        }));
      }
    };
    ZodPromise.create = (schema6, params) => {
      return new ZodPromise({
        type: schema6,
        typeName: ZodFirstPartyTypeKind.ZodPromise,
        ...processCreateParams(params)
      });
    };
    ZodEffects = class extends ZodType {
      innerType() {
        return this._def.schema;
      }
      sourceType() {
        return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const effect = this._def.effect || null;
        const checkCtx = {
          addIssue: (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 = (schema6, effect, params) => {
      return new ZodEffects({
        schema: schema6,
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        effect,
        ...processCreateParams(params)
      });
    };
    ZodEffects.createWithPreprocess = (preprocess, schema6, params) => {
      return new ZodEffects({
        schema: schema6,
        effect: { type: "preprocess", transform: preprocess },
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        ...processCreateParams(params)
      });
    };
    ZodOptional = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.undefined) {
          return OK(void 0);
        }
        return this._def.innerType._parse(input);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodOptional.create = (type, params) => {
      return new ZodOptional({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodOptional,
        ...processCreateParams(params)
      });
    };
    ZodNullable = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.null) {
          return OK(null);
        }
        return this._def.innerType._parse(input);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodNullable.create = (type, params) => {
      return new ZodNullable({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodNullable,
        ...processCreateParams(params)
      });
    };
    ZodDefault = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        let data = ctx.data;
        if (ctx.parsedType === ZodParsedType.undefined) {
          data = this._def.defaultValue();
        }
        return this._def.innerType._parse({
          data,
          path: ctx.path,
          parent: ctx
        });
      }
      removeDefault() {
        return this._def.innerType;
      }
    };
    ZodDefault.create = (type, params) => {
      return new ZodDefault({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodDefault,
        defaultValue: typeof params.default === "function" ? params.default : () => params.default,
        ...processCreateParams(params)
      });
    };
    ZodCatch = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const newCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          }
        };
        const result = this._def.innerType._parse({
          data: newCtx.data,
          path: newCtx.path,
          parent: {
            ...newCtx
          }
        });
        if (isAsync(result)) {
          return result.then((result2) => {
            return {
              status: "valid",
              value: result2.status === "valid" ? result2.value : this._def.catchValue({
                get error() {
                  return new ZodError(newCtx.common.issues);
                },
                input: newCtx.data
              })
            };
          });
        } else {
          return {
            status: "valid",
            value: result.status === "valid" ? result.value : this._def.catchValue({
              get error() {
                return new ZodError(newCtx.common.issues);
              },
              input: newCtx.data
            })
          };
        }
      }
      removeCatch() {
        return this._def.innerType;
      }
    };
    ZodCatch.create = (type, params) => {
      return new ZodCatch({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodCatch,
        catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
        ...processCreateParams(params)
      });
    };
    ZodNaN = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.nan) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.nan,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return { status: "valid", value: input.data };
      }
    };
    ZodNaN.create = (params) => {
      return new ZodNaN({
        typeName: ZodFirstPartyTypeKind.ZodNaN,
        ...processCreateParams(params)
      });
    };
    BRAND = Symbol("zod_brand");
    ZodBranded = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const data = ctx.data;
        return this._def.type._parse({
          data,
          path: ctx.path,
          parent: ctx
        });
      }
      unwrap() {
        return this._def.type;
      }
    };
    ZodPipeline = class _ZodPipeline extends ZodType {
      _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(a5, b5) {
        return new _ZodPipeline({
          in: a5,
          out: b5,
          typeName: ZodFirstPartyTypeKind.ZodPipeline
        });
      }
    };
    ZodReadonly = class extends ZodType {
      _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;
      }
    };
    ZodReadonly.create = (type, params) => {
      return new ZodReadonly({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodReadonly,
        ...processCreateParams(params)
      });
    };
    late = {
      object: ZodObject.lazycreate
    };
    (function(ZodFirstPartyTypeKind2) {
      ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
      ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
      ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
      ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
      ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
      ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
      ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
      ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
      ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
      ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
      ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
      ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
      ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
      ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
      ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
      ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
      ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
      ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
      ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
      ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
      ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
      ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
      ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
      ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
      ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
      ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
      ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
      ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
      ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
      ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
      ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
      ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
      ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
      ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
      ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
      ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
    })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
    instanceOfType = (cls, params = {
      message: `Input not instance of ${cls.name}`
    }) => custom((data) => data instanceof cls, params);
    stringType = ZodString.create;
    numberType = ZodNumber.create;
    nanType = ZodNaN.create;
    bigIntType = ZodBigInt.create;
    booleanType = ZodBoolean.create;
    dateType = ZodDate.create;
    symbolType = ZodSymbol.create;
    undefinedType = ZodUndefined.create;
    nullType = ZodNull.create;
    anyType = ZodAny.create;
    unknownType = ZodUnknown.create;
    neverType = ZodNever.create;
    voidType = ZodVoid.create;
    arrayType = ZodArray.create;
    objectType = ZodObject.create;
    strictObjectType = ZodObject.strictCreate;
    unionType = ZodUnion.create;
    discriminatedUnionType = ZodDiscriminatedUnion.create;
    intersectionType = ZodIntersection.create;
    tupleType = ZodTuple.create;
    recordType = ZodRecord.create;
    mapType = ZodMap.create;
    setType = ZodSet.create;
    functionType = ZodFunction.create;
    lazyType = ZodLazy.create;
    literalType = ZodLiteral.create;
    enumType = ZodEnum.create;
    nativeEnumType = ZodNativeEnum.create;
    promiseType = ZodPromise.create;
    effectsType = ZodEffects.create;
    optionalType = ZodOptional.create;
    nullableType = ZodNullable.create;
    preprocessType = ZodEffects.createWithPreprocess;
    pipelineType = ZodPipeline.create;
    ostring = () => stringType().optional();
    onumber = () => numberType().optional();
    oboolean = () => booleanType().optional();
    coerce = {
      string: (arg) => ZodString.create({ ...arg, coerce: true }),
      number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
      boolean: (arg) => ZodBoolean.create({
        ...arg,
        coerce: true
      }),
      bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
      date: (arg) => ZodDate.create({ ...arg, coerce: true })
    };
    NEVER = INVALID;
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/external.js
var external_exports = {};
__export(external_exports, {
  BRAND: () => BRAND,
  DIRTY: () => DIRTY,
  EMPTY_PATH: () => EMPTY_PATH,
  INVALID: () => INVALID,
  NEVER: () => NEVER,
  OK: () => OK,
  ParseStatus: () => ParseStatus,
  Schema: () => ZodType,
  ZodAny: () => ZodAny,
  ZodArray: () => ZodArray,
  ZodBigInt: () => ZodBigInt,
  ZodBoolean: () => ZodBoolean,
  ZodBranded: () => ZodBranded,
  ZodCatch: () => ZodCatch,
  ZodDate: () => ZodDate,
  ZodDefault: () => ZodDefault,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
  ZodEffects: () => ZodEffects,
  ZodEnum: () => ZodEnum,
  ZodError: () => ZodError,
  ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
  ZodFunction: () => ZodFunction,
  ZodIntersection: () => ZodIntersection,
  ZodIssueCode: () => ZodIssueCode,
  ZodLazy: () => ZodLazy,
  ZodLiteral: () => ZodLiteral,
  ZodMap: () => ZodMap,
  ZodNaN: () => ZodNaN,
  ZodNativeEnum: () => ZodNativeEnum,
  ZodNever: () => ZodNever,
  ZodNull: () => ZodNull,
  ZodNullable: () => ZodNullable,
  ZodNumber: () => ZodNumber,
  ZodObject: () => ZodObject,
  ZodOptional: () => ZodOptional,
  ZodParsedType: () => ZodParsedType,
  ZodPipeline: () => ZodPipeline,
  ZodPromise: () => ZodPromise,
  ZodReadonly: () => ZodReadonly,
  ZodRecord: () => ZodRecord,
  ZodSchema: () => ZodType,
  ZodSet: () => ZodSet,
  ZodString: () => ZodString,
  ZodSymbol: () => ZodSymbol,
  ZodTransformer: () => ZodEffects,
  ZodTuple: () => ZodTuple,
  ZodType: () => ZodType,
  ZodUndefined: () => ZodUndefined,
  ZodUnion: () => ZodUnion,
  ZodUnknown: () => ZodUnknown,
  ZodVoid: () => ZodVoid,
  addIssueToContext: () => addIssueToContext,
  any: () => anyType,
  array: () => arrayType,
  bigint: () => bigIntType,
  boolean: () => booleanType,
  coerce: () => coerce,
  custom: () => custom,
  date: () => dateType,
  datetimeRegex: () => datetimeRegex,
  defaultErrorMap: () => en_default,
  discriminatedUnion: () => discriminatedUnionType,
  effect: () => effectsType,
  enum: () => enumType,
  function: () => functionType,
  getErrorMap: () => getErrorMap,
  getParsedType: () => getParsedType,
  instanceof: () => instanceOfType,
  intersection: () => intersectionType,
  isAborted: () => isAborted,
  isAsync: () => isAsync,
  isDirty: () => isDirty,
  isValid: () => isValid,
  late: () => late,
  lazy: () => lazyType,
  literal: () => literalType,
  makeIssue: () => makeIssue,
  map: () => mapType,
  nan: () => nanType,
  nativeEnum: () => nativeEnumType,
  never: () => neverType,
  null: () => nullType,
  nullable: () => nullableType,
  number: () => numberType,
  object: () => objectType,
  objectUtil: () => objectUtil,
  oboolean: () => oboolean,
  onumber: () => onumber,
  optional: () => optionalType,
  ostring: () => ostring,
  pipeline: () => pipelineType,
  preprocess: () => preprocessType,
  promise: () => promiseType,
  quotelessJson: () => quotelessJson,
  record: () => recordType,
  set: () => setType,
  setErrorMap: () => setErrorMap,
  strictObject: () => strictObjectType,
  string: () => stringType,
  symbol: () => symbolType,
  transformer: () => effectsType,
  tuple: () => tupleType,
  undefined: () => undefinedType,
  union: () => unionType,
  unknown: () => unknownType,
  util: () => util,
  void: () => voidType
});
var init_external = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/external.js"() {
    "use strict";
    init_errors();
    init_parseUtil();
    init_typeAliases();
    init_util();
    init_types();
    init_ZodError();
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/index.js
var init_v3 = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/index.js"() {
    "use strict";
    init_external();
    init_external();
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/index.js
var init_esm = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/index.js"() {
    "use strict";
    init_v3();
    init_v3();
  }
});

// src/serializer/gelSchema.ts
var enumSchema, enumSchemaV1, indexColumn, index, fk, sequenceSchema, roleSchema, sequenceSquashed, column, checkConstraint, columnSquashed, compositePK, uniqueConstraint, policy, policySquashed, viewWithOption, matViewWithOption, mergedViewWithOption, view, table, schemaHash, kitInternals, gelSchemaExternal, gelSchemaInternal, tableSquashed, gelSchemaSquashed, gelSchema, dryGel;
var init_gelSchema = __esm({
  "src/serializer/gelSchema.ts"() {
    "use strict";
    init_global();
    init_esm();
    enumSchema = objectType({
      name: stringType(),
      schema: stringType(),
      values: stringType().array()
    }).strict();
    enumSchemaV1 = objectType({
      name: stringType(),
      values: recordType(stringType(), stringType())
    }).strict();
    indexColumn = objectType({
      expression: stringType(),
      isExpression: booleanType(),
      asc: booleanType(),
      nulls: stringType().optional(),
      opclass: stringType().optional()
    });
    index = objectType({
      name: stringType(),
      columns: indexColumn.array(),
      isUnique: booleanType(),
      with: recordType(stringType(), anyType()).optional(),
      method: stringType().default("btree"),
      where: stringType().optional(),
      concurrently: booleanType().default(false)
    }).strict();
    fk = objectType({
      name: stringType(),
      tableFrom: stringType(),
      columnsFrom: stringType().array(),
      tableTo: stringType(),
      schemaTo: stringType().optional(),
      columnsTo: stringType().array(),
      onUpdate: stringType().optional(),
      onDelete: stringType().optional()
    }).strict();
    sequenceSchema = objectType({
      name: stringType(),
      increment: stringType().optional(),
      minValue: stringType().optional(),
      maxValue: stringType().optional(),
      startWith: stringType().optional(),
      cache: stringType().optional(),
      cycle: booleanType().optional(),
      schema: stringType()
    }).strict();
    roleSchema = objectType({
      name: stringType(),
      createDb: booleanType().optional(),
      createRole: booleanType().optional(),
      inherit: booleanType().optional()
    }).strict();
    sequenceSquashed = objectType({
      name: stringType(),
      schema: stringType(),
      values: stringType()
    }).strict();
    column = objectType({
      name: stringType(),
      type: stringType(),
      typeSchema: stringType().optional(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      isUnique: anyType().optional(),
      uniqueName: stringType().optional(),
      nullsNotDistinct: booleanType().optional(),
      generated: objectType({
        type: literalType("stored"),
        as: stringType()
      }).optional(),
      identity: sequenceSchema.merge(objectType({ type: enumType(["always", "byDefault"]) })).optional()
    }).strict();
    checkConstraint = objectType({
      name: stringType(),
      value: stringType()
    }).strict();
    columnSquashed = objectType({
      name: stringType(),
      type: stringType(),
      typeSchema: stringType().optional(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      isUnique: anyType().optional(),
      uniqueName: stringType().optional(),
      nullsNotDistinct: booleanType().optional(),
      generated: objectType({
        type: literalType("stored"),
        as: stringType()
      }).optional(),
      identity: stringType().optional()
    }).strict();
    compositePK = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    uniqueConstraint = objectType({
      name: stringType(),
      columns: stringType().array(),
      nullsNotDistinct: booleanType()
    }).strict();
    policy = objectType({
      name: stringType(),
      as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(),
      for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(),
      to: stringType().array().optional(),
      using: stringType().optional(),
      withCheck: stringType().optional(),
      on: stringType().optional(),
      schema: stringType().optional()
    }).strict();
    policySquashed = objectType({
      name: stringType(),
      values: stringType()
    }).strict();
    viewWithOption = objectType({
      checkOption: enumType(["local", "cascaded"]).optional(),
      securityBarrier: booleanType().optional(),
      securityInvoker: booleanType().optional()
    }).strict();
    matViewWithOption = objectType({
      fillfactor: numberType().optional(),
      toastTupleTarget: numberType().optional(),
      parallelWorkers: numberType().optional(),
      autovacuumEnabled: booleanType().optional(),
      vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
      vacuumTruncate: booleanType().optional(),
      autovacuumVacuumThreshold: numberType().optional(),
      autovacuumVacuumScaleFactor: numberType().optional(),
      autovacuumVacuumCostDelay: numberType().optional(),
      autovacuumVacuumCostLimit: numberType().optional(),
      autovacuumFreezeMinAge: numberType().optional(),
      autovacuumFreezeMaxAge: numberType().optional(),
      autovacuumFreezeTableAge: numberType().optional(),
      autovacuumMultixactFreezeMinAge: numberType().optional(),
      autovacuumMultixactFreezeMaxAge: numberType().optional(),
      autovacuumMultixactFreezeTableAge: numberType().optional(),
      logAutovacuumMinDuration: numberType().optional(),
      userCatalogTable: booleanType().optional()
    }).strict();
    mergedViewWithOption = viewWithOption.merge(matViewWithOption).strict();
    view = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column),
      definition: stringType().optional(),
      materialized: booleanType(),
      with: mergedViewWithOption.optional(),
      isExisting: booleanType(),
      withNoData: booleanType().optional(),
      using: stringType().optional(),
      tablespace: stringType().optional()
    }).strict();
    table = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column),
      indexes: recordType(stringType(), index),
      foreignKeys: recordType(stringType(), fk),
      compositePrimaryKeys: recordType(stringType(), compositePK),
      uniqueConstraints: recordType(stringType(), uniqueConstraint).default({}),
      policies: recordType(stringType(), policy).default({}),
      checkConstraints: recordType(stringType(), checkConstraint).default({}),
      isRLSEnabled: booleanType().default(false)
    }).strict();
    schemaHash = objectType({
      id: stringType(),
      prevId: stringType()
    });
    kitInternals = objectType({
      tables: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({
              isArray: booleanType().optional(),
              dimensions: numberType().optional(),
              rawType: stringType().optional(),
              isDefaultAnExpression: booleanType().optional()
            }).optional()
          )
        }).optional()
      )
    }).optional();
    gelSchemaExternal = objectType({
      version: literalType("1"),
      dialect: literalType("gel"),
      tables: arrayType(table),
      enums: arrayType(enumSchemaV1),
      schemas: arrayType(objectType({ name: stringType() })),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      })
    }).strict();
    gelSchemaInternal = objectType({
      version: literalType("1"),
      dialect: literalType("gel"),
      tables: recordType(stringType(), table),
      enums: recordType(stringType(), enumSchema),
      schemas: recordType(stringType(), stringType()),
      views: recordType(stringType(), view).default({}),
      sequences: recordType(stringType(), sequenceSchema).default({}),
      roles: recordType(stringType(), roleSchema).default({}),
      policies: recordType(stringType(), policy).default({}),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals
    }).strict();
    tableSquashed = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), columnSquashed),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()),
      uniqueConstraints: recordType(stringType(), stringType()),
      policies: recordType(stringType(), stringType()),
      checkConstraints: recordType(stringType(), stringType()),
      isRLSEnabled: booleanType().default(false)
    }).strict();
    gelSchemaSquashed = objectType({
      version: literalType("1"),
      dialect: literalType("gel"),
      tables: recordType(stringType(), tableSquashed),
      enums: recordType(stringType(), enumSchema),
      schemas: recordType(stringType(), stringType()),
      views: recordType(stringType(), view),
      sequences: recordType(stringType(), sequenceSquashed),
      roles: recordType(stringType(), roleSchema).default({}),
      policies: recordType(stringType(), policySquashed).default({})
    }).strict();
    gelSchema = gelSchemaInternal.merge(schemaHash);
    dryGel = gelSchema.parse({
      version: "1",
      dialect: "gel",
      id: originUUID,
      prevId: "",
      tables: {},
      enums: {},
      schemas: {},
      policies: {},
      roles: {},
      sequences: {},
      _meta: {
        schemas: {},
        tables: {},
        columns: {}
      }
    });
  }
});

// src/serializer/mysqlSchema.ts
var index2, fk2, column2, tableV3, compositePK2, uniqueConstraint2, checkConstraint2, tableV4, table2, viewMeta, view2, kitInternals2, dialect, schemaHash2, schemaInternalV3, schemaInternalV4, schemaInternalV5, schemaInternal, schemaV3, schemaV4, schemaV5, schema, tableSquashedV4, tableSquashed2, viewSquashed, schemaSquashed, schemaSquashedV4, MySqlSquasher, squashMysqlScheme, mysqlSchema, mysqlSchemaV5, mysqlSchemaSquashed, backwardCompatibleMysqlSchema, dryMySql;
var init_mysqlSchema = __esm({
  "src/serializer/mysqlSchema.ts"() {
    "use strict";
    init_esm();
    init_global();
    index2 = objectType({
      name: stringType(),
      columns: stringType().array(),
      isUnique: booleanType(),
      using: enumType(["btree", "hash"]).optional(),
      algorithm: enumType(["default", "inplace", "copy"]).optional(),
      lock: enumType(["default", "none", "shared", "exclusive"]).optional()
    }).strict();
    fk2 = objectType({
      name: stringType(),
      tableFrom: stringType(),
      columnsFrom: stringType().array(),
      tableTo: stringType(),
      columnsTo: stringType().array(),
      onUpdate: stringType().optional(),
      onDelete: stringType().optional()
    }).strict();
    column2 = objectType({
      name: stringType(),
      type: stringType(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      autoincrement: booleanType().optional(),
      default: anyType().optional(),
      onUpdate: anyType().optional(),
      generated: objectType({
        type: enumType(["stored", "virtual"]),
        as: stringType()
      }).optional()
    }).strict();
    tableV3 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), index2),
      foreignKeys: recordType(stringType(), fk2)
    }).strict();
    compositePK2 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    uniqueConstraint2 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    checkConstraint2 = objectType({
      name: stringType(),
      value: stringType()
    }).strict();
    tableV4 = objectType({
      name: stringType(),
      schema: stringType().optional(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), index2),
      foreignKeys: recordType(stringType(), fk2)
    }).strict();
    table2 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), index2),
      foreignKeys: recordType(stringType(), fk2),
      compositePrimaryKeys: recordType(stringType(), compositePK2),
      uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({}),
      checkConstraint: recordType(stringType(), checkConstraint2).default({})
    }).strict();
    viewMeta = objectType({
      algorithm: enumType(["undefined", "merge", "temptable"]),
      sqlSecurity: enumType(["definer", "invoker"]),
      withCheckOption: enumType(["local", "cascaded"]).optional()
    }).strict();
    view2 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column2),
      definition: stringType().optional(),
      isExisting: booleanType()
    }).strict().merge(viewMeta);
    kitInternals2 = objectType({
      tables: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({ isDefaultAnExpression: booleanType().optional() }).optional()
          )
        }).optional()
      ).optional(),
      indexes: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({ isExpression: booleanType().optional() }).optional()
          )
        }).optional()
      ).optional()
    }).optional();
    dialect = literalType("mysql");
    schemaHash2 = objectType({
      id: stringType(),
      prevId: stringType()
    });
    schemaInternalV3 = objectType({
      version: literalType("3"),
      dialect,
      tables: recordType(stringType(), tableV3)
    }).strict();
    schemaInternalV4 = objectType({
      version: literalType("4"),
      dialect,
      tables: recordType(stringType(), tableV4),
      schemas: recordType(stringType(), stringType())
    }).strict();
    schemaInternalV5 = objectType({
      version: literalType("5"),
      dialect,
      tables: recordType(stringType(), table2),
      schemas: recordType(stringType(), stringType()),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals2
    }).strict();
    schemaInternal = objectType({
      version: literalType("5"),
      dialect,
      tables: recordType(stringType(), table2),
      views: recordType(stringType(), view2).default({}),
      _meta: objectType({
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals2
    }).strict();
    schemaV3 = schemaInternalV3.merge(schemaHash2);
    schemaV4 = schemaInternalV4.merge(schemaHash2);
    schemaV5 = schemaInternalV5.merge(schemaHash2);
    schema = schemaInternal.merge(schemaHash2);
    tableSquashedV4 = objectType({
      name: stringType(),
      schema: stringType().optional(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType())
    }).strict();
    tableSquashed2 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()),
      uniqueConstraints: recordType(stringType(), stringType()).default({}),
      checkConstraints: recordType(stringType(), stringType()).default({})
    }).strict();
    viewSquashed = view2.omit({
      algorithm: true,
      sqlSecurity: true,
      withCheckOption: true
    }).extend({ meta: stringType() });
    schemaSquashed = objectType({
      version: literalType("5"),
      dialect,
      tables: recordType(stringType(), tableSquashed2),
      views: recordType(stringType(), viewSquashed)
    }).strict();
    schemaSquashedV4 = objectType({
      version: literalType("4"),
      dialect,
      tables: recordType(stringType(), tableSquashedV4),
      schemas: recordType(stringType(), stringType())
    }).strict();
    MySqlSquasher = {
      squashIdx: (idx) => {
        index2.parse(idx);
        return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.using ?? ""};${idx.algorithm ?? ""};${idx.lock ?? ""}`;
      },
      unsquashIdx: (input) => {
        const [name, columnsString, isUnique, using, algorithm, lock] = input.split(";");
        const destructed = {
          name,
          columns: columnsString.split(","),
          isUnique: isUnique === "true",
          using: using ? using : void 0,
          algorithm: algorithm ? algorithm : void 0,
          lock: lock ? lock : void 0
        };
        return index2.parse(destructed);
      },
      squashPK: (pk) => {
        return `${pk.name};${pk.columns.join(",")}`;
      },
      unsquashPK: (pk) => {
        const splitted = pk.split(";");
        return { name: splitted[0], columns: splitted[1].split(",") };
      },
      squashUnique: (unq) => {
        return `${unq.name};${unq.columns.join(",")}`;
      },
      unsquashUnique: (unq) => {
        const [name, columns] = unq.split(";");
        return { name, columns: columns.split(",") };
      },
      squashFK: (fk5) => {
        return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`;
      },
      unsquashFK: (input) => {
        const [
          name,
          tableFrom,
          columnsFromStr,
          tableTo,
          columnsToStr,
          onUpdate,
          onDelete
        ] = input.split(";");
        const result = fk2.parse({
          name,
          tableFrom,
          columnsFrom: columnsFromStr.split(","),
          tableTo,
          columnsTo: columnsToStr.split(","),
          onUpdate,
          onDelete
        });
        return result;
      },
      squashCheck: (input) => {
        return `${input.name};${input.value}`;
      },
      unsquashCheck: (input) => {
        const [name, value] = input.split(";");
        return { name, value };
      },
      squashView: (view5) => {
        return `${view5.algorithm};${view5.sqlSecurity};${view5.withCheckOption}`;
      },
      unsquashView: (meta) => {
        const [algorithm, sqlSecurity, withCheckOption] = meta.split(";");
        const toReturn = {
          algorithm,
          sqlSecurity,
          withCheckOption: withCheckOption !== "undefined" ? withCheckOption : void 0
        };
        return viewMeta.parse(toReturn);
      }
    };
    squashMysqlScheme = (json) => {
      const mappedTables = Object.fromEntries(
        Object.entries(json.tables).map((it) => {
          const squashedIndexes = mapValues(it[1].indexes, (index6) => {
            return MySqlSquasher.squashIdx(index6);
          });
          const squashedFKs = mapValues(it[1].foreignKeys, (fk5) => {
            return MySqlSquasher.squashFK(fk5);
          });
          const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
            return MySqlSquasher.squashPK(pk);
          });
          const squashedUniqueConstraints = mapValues(
            it[1].uniqueConstraints,
            (unq) => {
              return MySqlSquasher.squashUnique(unq);
            }
          );
          const squashedCheckConstraints = mapValues(it[1].checkConstraint, (check) => {
            return MySqlSquasher.squashCheck(check);
          });
          return [
            it[0],
            {
              name: it[1].name,
              columns: it[1].columns,
              indexes: squashedIndexes,
              foreignKeys: squashedFKs,
              compositePrimaryKeys: squashedPKs,
              uniqueConstraints: squashedUniqueConstraints,
              checkConstraints: squashedCheckConstraints
            }
          ];
        })
      );
      const mappedViews = Object.fromEntries(
        Object.entries(json.views).map(([key, value]) => {
          const meta = MySqlSquasher.squashView(value);
          return [key, {
            name: value.name,
            isExisting: value.isExisting,
            columns: value.columns,
            definition: value.definition,
            meta
          }];
        })
      );
      return {
        version: "5",
        dialect: json.dialect,
        tables: mappedTables,
        views: mappedViews
      };
    };
    mysqlSchema = schema;
    mysqlSchemaV5 = schemaV5;
    mysqlSchemaSquashed = schemaSquashed;
    backwardCompatibleMysqlSchema = unionType([mysqlSchemaV5, schema]);
    dryMySql = mysqlSchema.parse({
      version: "5",
      dialect: "mysql",
      id: originUUID,
      prevId: "",
      tables: {},
      schemas: {},
      views: {},
      _meta: {
        schemas: {},
        tables: {},
        columns: {}
      }
    });
  }
});

// src/serializer/pgSchema.ts
var indexV2, columnV2, tableV2, enumSchemaV12, enumSchema2, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, indexColumn2, index3, indexV4, indexV5, indexV6, fk3, sequenceSchema2, roleSchema2, sequenceSquashed2, columnV7, column3, checkConstraint3, columnSquashed2, tableV32, compositePK3, uniqueConstraint3, policy2, policySquashed2, viewWithOption2, matViewWithOption2, mergedViewWithOption2, view3, tableV42, tableV5, tableV6, tableV7, table3, schemaHash3, kitInternals3, pgSchemaInternalV3, pgSchemaInternalV4, pgSchemaInternalV5, pgSchemaInternalV6, pgSchemaExternal, pgSchemaInternalV7, pgSchemaInternal, tableSquashed3, tableSquashedV42, pgSchemaSquashedV4, pgSchemaSquashedV6, pgSchemaSquashed, pgSchemaV3, pgSchemaV4, pgSchemaV5, pgSchemaV6, pgSchemaV7, pgSchema, backwardCompatiblePgSchema, PgSquasher, squashPgScheme, dryPg;
var init_pgSchema = __esm({
  "src/serializer/pgSchema.ts"() {
    "use strict";
    init_global();
    init_esm();
    indexV2 = objectType({
      name: stringType(),
      columns: recordType(
        stringType(),
        objectType({
          name: stringType()
        })
      ),
      isUnique: booleanType()
    }).strict();
    columnV2 = objectType({
      name: stringType(),
      type: stringType(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      references: stringType().optional()
    }).strict();
    tableV2 = objectType({
      name: stringType(),
      columns: recordType(stringType(), columnV2),
      indexes: recordType(stringType(), indexV2)
    }).strict();
    enumSchemaV12 = objectType({
      name: stringType(),
      values: recordType(stringType(), stringType())
    }).strict();
    enumSchema2 = objectType({
      name: stringType(),
      schema: stringType(),
      values: stringType().array()
    }).strict();
    pgSchemaV2 = objectType({
      version: literalType("2"),
      tables: recordType(stringType(), tableV2),
      enums: recordType(stringType(), enumSchemaV12)
    }).strict();
    references = objectType({
      foreignKeyName: stringType(),
      table: stringType(),
      column: stringType(),
      onDelete: stringType().optional(),
      onUpdate: stringType().optional()
    }).strict();
    columnV1 = objectType({
      name: stringType(),
      type: stringType(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      references: references.optional()
    }).strict();
    tableV1 = objectType({
      name: stringType(),
      columns: recordType(stringType(), columnV1),
      indexes: recordType(stringType(), indexV2)
    }).strict();
    pgSchemaV1 = objectType({
      version: literalType("1"),
      tables: recordType(stringType(), tableV1),
      enums: recordType(stringType(), enumSchemaV12)
    }).strict();
    indexColumn2 = objectType({
      expression: stringType(),
      isExpression: booleanType(),
      asc: booleanType(),
      nulls: stringType().optional(),
      opclass: stringType().optional()
    });
    index3 = objectType({
      name: stringType(),
      columns: indexColumn2.array(),
      isUnique: booleanType(),
      with: recordType(stringType(), anyType()).optional(),
      method: stringType().default("btree"),
      where: stringType().optional(),
      concurrently: booleanType().default(false)
    }).strict();
    indexV4 = objectType({
      name: stringType(),
      columns: stringType().array(),
      isUnique: booleanType(),
      with: recordType(stringType(), stringType()).optional(),
      method: stringType().default("btree"),
      where: stringType().optional(),
      concurrently: booleanType().default(false)
    }).strict();
    indexV5 = objectType({
      name: stringType(),
      columns: stringType().array(),
      isUnique: booleanType(),
      with: recordType(stringType(), stringType()).optional(),
      method: stringType().default("btree"),
      where: stringType().optional(),
      concurrently: booleanType().default(false)
    }).strict();
    indexV6 = objectType({
      name: stringType(),
      columns: stringType().array(),
      isUnique: booleanType(),
      with: recordType(stringType(), stringType()).optional(),
      method: stringType().default("btree"),
      where: stringType().optional(),
      concurrently: booleanType().default(false)
    }).strict();
    fk3 = objectType({
      name: stringType(),
      tableFrom: stringType(),
      columnsFrom: stringType().array(),
      tableTo: stringType(),
      schemaTo: stringType().optional(),
      columnsTo: stringType().array(),
      onUpdate: stringType().optional(),
      onDelete: stringType().optional()
    }).strict();
    sequenceSchema2 = objectType({
      name: stringType(),
      increment: stringType().optional(),
      minValue: stringType().optional(),
      maxValue: stringType().optional(),
      startWith: stringType().optional(),
      cache: stringType().optional(),
      cycle: booleanType().optional(),
      schema: stringType()
    }).strict();
    roleSchema2 = objectType({
      name: stringType(),
      createDb: booleanType().optional(),
      createRole: booleanType().optional(),
      inherit: booleanType().optional()
    }).strict();
    sequenceSquashed2 = objectType({
      name: stringType(),
      schema: stringType(),
      values: stringType()
    }).strict();
    columnV7 = objectType({
      name: stringType(),
      type: stringType(),
      typeSchema: stringType().optional(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      isUnique: anyType().optional(),
      uniqueName: stringType().optional(),
      nullsNotDistinct: booleanType().optional()
    }).strict();
    column3 = objectType({
      name: stringType(),
      type: stringType(),
      typeSchema: stringType().optional(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      isUnique: anyType().optional(),
      uniqueName: stringType().optional(),
      nullsNotDistinct: booleanType().optional(),
      generated: objectType({
        type: literalType("stored"),
        as: stringType()
      }).optional(),
      identity: sequenceSchema2.merge(objectType({ type: enumType(["always", "byDefault"]) })).optional()
    }).strict();
    checkConstraint3 = objectType({
      name: stringType(),
      value: stringType()
    }).strict();
    columnSquashed2 = objectType({
      name: stringType(),
      type: stringType(),
      typeSchema: stringType().optional(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      isUnique: anyType().optional(),
      uniqueName: stringType().optional(),
      nullsNotDistinct: booleanType().optional(),
      generated: objectType({
        type: literalType("stored"),
        as: stringType()
      }).optional(),
      identity: stringType().optional()
    }).strict();
    tableV32 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column3),
      indexes: recordType(stringType(), index3),
      foreignKeys: recordType(stringType(), fk3)
    }).strict();
    compositePK3 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    uniqueConstraint3 = objectType({
      name: stringType(),
      columns: stringType().array(),
      nullsNotDistinct: booleanType()
    }).strict();
    policy2 = objectType({
      name: stringType(),
      as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(),
      for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(),
      to: stringType().array().optional(),
      using: stringType().optional(),
      withCheck: stringType().optional(),
      on: stringType().optional(),
      schema: stringType().optional()
    }).strict();
    policySquashed2 = objectType({
      name: stringType(),
      values: stringType()
    }).strict();
    viewWithOption2 = objectType({
      checkOption: enumType(["local", "cascaded"]).optional(),
      securityBarrier: booleanType().optional(),
      securityInvoker: booleanType().optional()
    }).strict();
    matViewWithOption2 = objectType({
      fillfactor: numberType().optional(),
      toastTupleTarget: numberType().optional(),
      parallelWorkers: numberType().optional(),
      autovacuumEnabled: booleanType().optional(),
      vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
      vacuumTruncate: booleanType().optional(),
      autovacuumVacuumThreshold: numberType().optional(),
      autovacuumVacuumScaleFactor: numberType().optional(),
      autovacuumVacuumCostDelay: numberType().optional(),
      autovacuumVacuumCostLimit: numberType().optional(),
      autovacuumFreezeMinAge: numberType().optional(),
      autovacuumFreezeMaxAge: numberType().optional(),
      autovacuumFreezeTableAge: numberType().optional(),
      autovacuumMultixactFreezeMinAge: numberType().optional(),
      autovacuumMultixactFreezeMaxAge: numberType().optional(),
      autovacuumMultixactFreezeTableAge: numberType().optional(),
      logAutovacuumMinDuration: numberType().optional(),
      userCatalogTable: booleanType().optional()
    }).strict();
    mergedViewWithOption2 = viewWithOption2.merge(matViewWithOption2).strict();
    view3 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column3),
      definition: stringType().optional(),
      materialized: booleanType(),
      with: mergedViewWithOption2.optional(),
      isExisting: booleanType(),
      withNoData: booleanType().optional(),
      using: stringType().optional(),
      tablespace: stringType().optional()
    }).strict();
    tableV42 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column3),
      indexes: recordType(stringType(), indexV4),
      foreignKeys: recordType(stringType(), fk3)
    }).strict();
    tableV5 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column3),
      indexes: recordType(stringType(), indexV5),
      foreignKeys: recordType(stringType(), fk3),
      compositePrimaryKeys: recordType(stringType(), compositePK3),
      uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
    }).strict();
    tableV6 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column3),
      indexes: recordType(stringType(), indexV6),
      foreignKeys: recordType(stringType(), fk3),
      compositePrimaryKeys: recordType(stringType(), compositePK3),
      uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
    }).strict();
    tableV7 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), columnV7),
      indexes: recordType(stringType(), index3),
      foreignKeys: recordType(stringType(), fk3),
      compositePrimaryKeys: recordType(stringType(), compositePK3),
      uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
    }).strict();
    table3 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column3),
      indexes: recordType(stringType(), index3),
      foreignKeys: recordType(stringType(), fk3),
      compositePrimaryKeys: recordType(stringType(), compositePK3),
      uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({}),
      policies: recordType(stringType(), policy2).default({}),
      checkConstraints: recordType(stringType(), checkConstraint3).default({}),
      isRLSEnabled: booleanType().default(false)
    }).strict();
    schemaHash3 = objectType({
      id: stringType(),
      prevId: stringType()
    });
    kitInternals3 = objectType({
      tables: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({
              isArray: booleanType().optional(),
              dimensions: numberType().optional(),
              rawType: stringType().optional(),
              isDefaultAnExpression: booleanType().optional()
            }).optional()
          )
        }).optional()
      )
    }).optional();
    pgSchemaInternalV3 = objectType({
      version: literalType("3"),
      dialect: literalType("pg"),
      tables: recordType(stringType(), tableV32),
      enums: recordType(stringType(), enumSchemaV12)
    }).strict();
    pgSchemaInternalV4 = objectType({
      version: literalType("4"),
      dialect: literalType("pg"),
      tables: recordType(stringType(), tableV42),
      enums: recordType(stringType(), enumSchemaV12),
      schemas: recordType(stringType(), stringType())
    }).strict();
    pgSchemaInternalV5 = objectType({
      version: literalType("5"),
      dialect: literalType("pg"),
      tables: recordType(stringType(), tableV5),
      enums: recordType(stringType(), enumSchemaV12),
      schemas: recordType(stringType(), stringType()),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals3
    }).strict();
    pgSchemaInternalV6 = objectType({
      version: literalType("6"),
      dialect: literalType("postgresql"),
      tables: recordType(stringType(), tableV6),
      enums: recordType(stringType(), enumSchema2),
      schemas: recordType(stringType(), stringType()),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals3
    }).strict();
    pgSchemaExternal = objectType({
      version: literalType("5"),
      dialect: literalType("pg"),
      tables: arrayType(table3),
      enums: arrayType(enumSchemaV12),
      schemas: arrayType(objectType({ name: stringType() })),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      })
    }).strict();
    pgSchemaInternalV7 = objectType({
      version: literalType("7"),
      dialect: literalType("postgresql"),
      tables: recordType(stringType(), tableV7),
      enums: recordType(stringType(), enumSchema2),
      schemas: recordType(stringType(), stringType()),
      sequences: recordType(stringType(), sequenceSchema2),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals3
    }).strict();
    pgSchemaInternal = objectType({
      version: literalType("7"),
      dialect: literalType("postgresql"),
      tables: recordType(stringType(), table3),
      enums: recordType(stringType(), enumSchema2),
      schemas: recordType(stringType(), stringType()),
      views: recordType(stringType(), view3).default({}),
      sequences: recordType(stringType(), sequenceSchema2).default({}),
      roles: recordType(stringType(), roleSchema2).default({}),
      policies: recordType(stringType(), policy2).default({}),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals3
    }).strict();
    tableSquashed3 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), columnSquashed2),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()),
      uniqueConstraints: recordType(stringType(), stringType()),
      policies: recordType(stringType(), stringType()),
      checkConstraints: recordType(stringType(), stringType()),
      isRLSEnabled: booleanType().default(false)
    }).strict();
    tableSquashedV42 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column3),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType())
    }).strict();
    pgSchemaSquashedV4 = objectType({
      version: literalType("4"),
      dialect: literalType("pg"),
      tables: recordType(stringType(), tableSquashedV42),
      enums: recordType(stringType(), enumSchemaV12),
      schemas: recordType(stringType(), stringType())
    }).strict();
    pgSchemaSquashedV6 = objectType({
      version: literalType("6"),
      dialect: literalType("postgresql"),
      tables: recordType(stringType(), tableSquashed3),
      enums: recordType(stringType(), enumSchema2),
      schemas: recordType(stringType(), stringType())
    }).strict();
    pgSchemaSquashed = objectType({
      version: literalType("7"),
      dialect: literalType("postgresql"),
      tables: recordType(stringType(), tableSquashed3),
      enums: recordType(stringType(), enumSchema2),
      schemas: recordType(stringType(), stringType()),
      views: recordType(stringType(), view3),
      sequences: recordType(stringType(), sequenceSquashed2),
      roles: recordType(stringType(), roleSchema2).default({}),
      policies: recordType(stringType(), policySquashed2).default({})
    }).strict();
    pgSchemaV3 = pgSchemaInternalV3.merge(schemaHash3);
    pgSchemaV4 = pgSchemaInternalV4.merge(schemaHash3);
    pgSchemaV5 = pgSchemaInternalV5.merge(schemaHash3);
    pgSchemaV6 = pgSchemaInternalV6.merge(schemaHash3);
    pgSchemaV7 = pgSchemaInternalV7.merge(schemaHash3);
    pgSchema = pgSchemaInternal.merge(schemaHash3);
    backwardCompatiblePgSchema = unionType([
      pgSchemaV5,
      pgSchemaV6,
      pgSchema
    ]);
    PgSquasher = {
      squashIdx: (idx) => {
        index3.parse(idx);
        return `${idx.name};${idx.columns.map(
          (c5) => `${c5.expression}--${c5.isExpression}--${c5.asc}--${c5.nulls}--${c5.opclass ? c5.opclass : ""}`
        ).join(",,")};${idx.isUnique};${idx.concurrently};${idx.method};${idx.where};${JSON.stringify(idx.with)}`;
      },
      unsquashIdx: (input) => {
        const [
          name,
          columnsString,
          isUnique,
          concurrently,
          method,
          where,
          idxWith
        ] = input.split(";");
        const columnString = columnsString.split(",,");
        const columns = [];
        for (const column6 of columnString) {
          const [expression, isExpression, asc, nulls, opclass] = column6.split("--");
          columns.push({
            nulls,
            isExpression: isExpression === "true",
            asc: asc === "true",
            expression,
            opclass: opclass === "undefined" ? void 0 : opclass
          });
        }
        const result = index3.parse({
          name,
          columns,
          isUnique: isUnique === "true",
          concurrently: concurrently === "true",
          method,
          where: where === "undefined" ? void 0 : where,
          with: !idxWith || idxWith === "undefined" ? void 0 : JSON.parse(idxWith)
        });
        return result;
      },
      squashIdxPush: (idx) => {
        index3.parse(idx);
        return `${idx.name};${idx.columns.map((c5) => `${c5.isExpression ? "" : c5.expression}--${c5.asc}--${c5.nulls}`).join(",,")};${idx.isUnique};${idx.method};${JSON.stringify(idx.with)}`;
      },
      unsquashIdxPush: (input) => {
        const [name, columnsString, isUnique, method, idxWith] = input.split(";");
        const columnString = columnsString.split("--");
        const columns = [];
        for (const column6 of columnString) {
          const [expression, asc, nulls, opclass] = column6.split(",");
          columns.push({
            nulls,
            isExpression: expression === "",
            asc: asc === "true",
            expression
          });
        }
        const result = index3.parse({
          name,
          columns,
          isUnique: isUnique === "true",
          concurrently: false,
          method,
          with: idxWith === "undefined" ? void 0 : JSON.parse(idxWith)
        });
        return result;
      },
      squashFK: (fk5) => {
        return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""};${fk5.schemaTo || "public"}`;
      },
      squashPolicy: (policy5) => {
        return `${policy5.name}--${policy5.as}--${policy5.for}--${policy5.to?.join(",")}--${policy5.using}--${policy5.withCheck}--${policy5.on}`;
      },
      unsquashPolicy: (policy5) => {
        const splitted = policy5.split("--");
        return {
          name: splitted[0],
          as: splitted[1],
          for: splitted[2],
          to: splitted[3].split(","),
          using: splitted[4] !== "undefined" ? splitted[4] : void 0,
          withCheck: splitted[5] !== "undefined" ? splitted[5] : void 0,
          on: splitted[6] !== "undefined" ? splitted[6] : void 0
        };
      },
      squashPolicyPush: (policy5) => {
        return `${policy5.name}--${policy5.as}--${policy5.for}--${policy5.to?.join(",")}--${policy5.on}`;
      },
      unsquashPolicyPush: (policy5) => {
        const splitted = policy5.split("--");
        return {
          name: splitted[0],
          as: splitted[1],
          for: splitted[2],
          to: splitted[3].split(","),
          on: splitted[4] !== "undefined" ? splitted[4] : void 0
        };
      },
      squashPK: (pk) => {
        return `${pk.columns.join(",")};${pk.name}`;
      },
      unsquashPK: (pk) => {
        const splitted = pk.split(";");
        return { name: splitted[1], columns: splitted[0].split(",") };
      },
      squashUnique: (unq) => {
        return `${unq.name};${unq.columns.join(",")};${unq.nullsNotDistinct}`;
      },
      unsquashUnique: (unq) => {
        const [name, columns, nullsNotDistinct] = unq.split(";");
        return {
          name,
          columns: columns.split(","),
          nullsNotDistinct: nullsNotDistinct === "true"
        };
      },
      unsquashFK: (input) => {
        const [
          name,
          tableFrom,
          columnsFromStr,
          tableTo,
          columnsToStr,
          onUpdate,
          onDelete,
          schemaTo
        ] = input.split(";");
        const result = fk3.parse({
          name,
          tableFrom,
          columnsFrom: columnsFromStr.split(","),
          schemaTo,
          tableTo,
          columnsTo: columnsToStr.split(","),
          onUpdate,
          onDelete
        });
        return result;
      },
      squashSequence: (seq) => {
        return `${seq.minValue};${seq.maxValue};${seq.increment};${seq.startWith};${seq.cache};${seq.cycle ?? ""}`;
      },
      unsquashSequence: (seq) => {
        const splitted = seq.split(";");
        return {
          minValue: splitted[0] !== "undefined" ? splitted[0] : void 0,
          maxValue: splitted[1] !== "undefined" ? splitted[1] : void 0,
          increment: splitted[2] !== "undefined" ? splitted[2] : void 0,
          startWith: splitted[3] !== "undefined" ? splitted[3] : void 0,
          cache: splitted[4] !== "undefined" ? splitted[4] : void 0,
          cycle: splitted[5] === "true"
        };
      },
      squashIdentity: (seq) => {
        return `${seq.name};${seq.type};${seq.minValue};${seq.maxValue};${seq.increment};${seq.startWith};${seq.cache};${seq.cycle ?? ""}`;
      },
      unsquashIdentity: (seq) => {
        const splitted = seq.split(";");
        return {
          name: splitted[0],
          type: splitted[1],
          minValue: splitted[2] !== "undefined" ? splitted[2] : void 0,
          maxValue: splitted[3] !== "undefined" ? splitted[3] : void 0,
          increment: splitted[4] !== "undefined" ? splitted[4] : void 0,
          startWith: splitted[5] !== "undefined" ? splitted[5] : void 0,
          cache: splitted[6] !== "undefined" ? splitted[6] : void 0,
          cycle: splitted[7] === "true"
        };
      },
      squashCheck: (check) => {
        return `${check.name};${check.value}`;
      },
      unsquashCheck: (input) => {
        const [
          name,
          value
        ] = input.split(";");
        return { name, value };
      }
    };
    squashPgScheme = (json, action) => {
      const mappedTables = Object.fromEntries(
        Object.entries(json.tables).map((it) => {
          const squashedIndexes = mapValues(it[1].indexes, (index6) => {
            return action === "push" ? PgSquasher.squashIdxPush(index6) : PgSquasher.squashIdx(index6);
          });
          const squashedFKs = mapValues(it[1].foreignKeys, (fk5) => {
            return PgSquasher.squashFK(fk5);
          });
          const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
            return PgSquasher.squashPK(pk);
          });
          const mappedColumns = Object.fromEntries(
            Object.entries(it[1].columns).map((it2) => {
              const mappedIdentity = it2[1].identity ? PgSquasher.squashIdentity(it2[1].identity) : void 0;
              return [
                it2[0],
                {
                  ...it2[1],
                  identity: mappedIdentity
                }
              ];
            })
          );
          const squashedUniqueConstraints = mapValues(
            it[1].uniqueConstraints,
            (unq) => {
              return PgSquasher.squashUnique(unq);
            }
          );
          const squashedPolicies = mapValues(it[1].policies, (policy5) => {
            return action === "push" ? PgSquasher.squashPolicyPush(policy5) : PgSquasher.squashPolicy(policy5);
          });
          const squashedChecksContraints = mapValues(
            it[1].checkConstraints,
            (check) => {
              return PgSquasher.squashCheck(check);
            }
          );
          return [
            it[0],
            {
              name: it[1].name,
              schema: it[1].schema,
              columns: mappedColumns,
              indexes: squashedIndexes,
              foreignKeys: squashedFKs,
              compositePrimaryKeys: squashedPKs,
              uniqueConstraints: squashedUniqueConstraints,
              policies: squashedPolicies,
              checkConstraints: squashedChecksContraints,
              isRLSEnabled: it[1].isRLSEnabled ?? false
            }
          ];
        })
      );
      const mappedSequences = Object.fromEntries(
        Object.entries(json.sequences).map((it) => {
          return [
            it[0],
            {
              name: it[1].name,
              schema: it[1].schema,
              values: PgSquasher.squashSequence(it[1])
            }
          ];
        })
      );
      const mappedPolicies = Object.fromEntries(
        Object.entries(json.policies).map((it) => {
          return [
            it[0],
            {
              name: it[1].name,
              values: action === "push" ? PgSquasher.squashPolicyPush(it[1]) : PgSquasher.squashPolicy(it[1])
            }
          ];
        })
      );
      return {
        version: "7",
        dialect: json.dialect,
        tables: mappedTables,
        enums: json.enums,
        schemas: json.schemas,
        views: json.views,
        policies: mappedPolicies,
        sequences: mappedSequences,
        roles: json.roles
      };
    };
    dryPg = pgSchema.parse({
      version: snapshotVersion,
      dialect: "postgresql",
      id: originUUID,
      prevId: "",
      tables: {},
      enums: {},
      schemas: {},
      policies: {},
      roles: {},
      sequences: {},
      _meta: {
        schemas: {},
        tables: {},
        columns: {}
      }
    });
  }
});

// src/serializer/singlestoreSchema.ts
var index4, column4, compositePK4, uniqueConstraint4, table4, viewMeta2, kitInternals4, dialect2, schemaHash4, schemaInternal2, schema2, tableSquashed4, schemaSquashed2, SingleStoreSquasher, squashSingleStoreScheme, singlestoreSchema, singlestoreSchemaSquashed, backwardCompatibleSingleStoreSchema, drySingleStore;
var init_singlestoreSchema = __esm({
  "src/serializer/singlestoreSchema.ts"() {
    "use strict";
    init_esm();
    init_global();
    index4 = objectType({
      name: stringType(),
      columns: stringType().array(),
      isUnique: booleanType(),
      using: enumType(["btree", "hash"]).optional(),
      algorithm: enumType(["default", "inplace", "copy"]).optional(),
      lock: enumType(["default", "none", "shared", "exclusive"]).optional()
    }).strict();
    column4 = objectType({
      name: stringType(),
      type: stringType(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      autoincrement: booleanType().optional(),
      default: anyType().optional(),
      onUpdate: anyType().optional(),
      generated: objectType({
        type: enumType(["stored", "virtual"]),
        as: stringType()
      }).optional()
    }).strict();
    compositePK4 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    uniqueConstraint4 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    table4 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column4),
      indexes: recordType(stringType(), index4),
      compositePrimaryKeys: recordType(stringType(), compositePK4),
      uniqueConstraints: recordType(stringType(), uniqueConstraint4).default({})
    }).strict();
    viewMeta2 = objectType({
      algorithm: enumType(["undefined", "merge", "temptable"]),
      sqlSecurity: enumType(["definer", "invoker"]),
      withCheckOption: enumType(["local", "cascaded"]).optional()
    }).strict();
    kitInternals4 = objectType({
      tables: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({ isDefaultAnExpression: booleanType().optional() }).optional()
          )
        }).optional()
      ).optional(),
      indexes: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({ isExpression: booleanType().optional() }).optional()
          )
        }).optional()
      ).optional()
    }).optional();
    dialect2 = literalType("singlestore");
    schemaHash4 = objectType({
      id: stringType(),
      prevId: stringType()
    });
    schemaInternal2 = objectType({
      version: literalType("1"),
      dialect: dialect2,
      tables: recordType(stringType(), table4),
      /* views: record(string(), view).default({}), */
      _meta: objectType({
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals4
    }).strict();
    schema2 = schemaInternal2.merge(schemaHash4);
    tableSquashed4 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column4),
      indexes: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()),
      uniqueConstraints: recordType(stringType(), stringType()).default({})
    }).strict();
    schemaSquashed2 = objectType({
      version: literalType("1"),
      dialect: dialect2,
      tables: recordType(stringType(), tableSquashed4)
      /* views: record(string(), viewSquashed), */
    }).strict();
    SingleStoreSquasher = {
      squashIdx: (idx) => {
        index4.parse(idx);
        return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.using ?? ""};${idx.algorithm ?? ""};${idx.lock ?? ""}`;
      },
      unsquashIdx: (input) => {
        const [name, columnsString, isUnique, using, algorithm, lock] = input.split(";");
        const destructed = {
          name,
          columns: columnsString.split(","),
          isUnique: isUnique === "true",
          using: using ? using : void 0,
          algorithm: algorithm ? algorithm : void 0,
          lock: lock ? lock : void 0
        };
        return index4.parse(destructed);
      },
      squashPK: (pk) => {
        return `${pk.name};${pk.columns.join(",")}`;
      },
      unsquashPK: (pk) => {
        const splitted = pk.split(";");
        return { name: splitted[0], columns: splitted[1].split(",") };
      },
      squashUnique: (unq) => {
        return `${unq.name};${unq.columns.join(",")}`;
      },
      unsquashUnique: (unq) => {
        const [name, columns] = unq.split(";");
        return { name, columns: columns.split(",") };
      }
      /* squashView: (view: View): string => {
      		return `${view.algorithm};${view.sqlSecurity};${view.withCheckOption}`;
      	},
      	unsquashView: (meta: string): SquasherViewMeta => {
      		const [algorithm, sqlSecurity, withCheckOption] = meta.split(';');
      		const toReturn = {
      			algorithm: algorithm,
      			sqlSecurity: sqlSecurity,
      			withCheckOption: withCheckOption !== 'undefined' ? withCheckOption : undefined,
      		};
      
      		return viewMeta.parse(toReturn);
      	}, */
    };
    squashSingleStoreScheme = (json) => {
      const mappedTables = Object.fromEntries(
        Object.entries(json.tables).map((it) => {
          const squashedIndexes = mapValues(it[1].indexes, (index6) => {
            return SingleStoreSquasher.squashIdx(index6);
          });
          const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
            return SingleStoreSquasher.squashPK(pk);
          });
          const squashedUniqueConstraints = mapValues(
            it[1].uniqueConstraints,
            (unq) => {
              return SingleStoreSquasher.squashUnique(unq);
            }
          );
          return [
            it[0],
            {
              name: it[1].name,
              columns: it[1].columns,
              indexes: squashedIndexes,
              compositePrimaryKeys: squashedPKs,
              uniqueConstraints: squashedUniqueConstraints
            }
          ];
        })
      );
      return {
        version: "1",
        dialect: json.dialect,
        tables: mappedTables
        /* views: mappedViews, */
      };
    };
    singlestoreSchema = schema2;
    singlestoreSchemaSquashed = schemaSquashed2;
    backwardCompatibleSingleStoreSchema = unionType([singlestoreSchema, schema2]);
    drySingleStore = singlestoreSchema.parse({
      version: "1",
      dialect: "singlestore",
      id: originUUID,
      prevId: "",
      tables: {},
      schemas: {},
      /* views: {}, */
      _meta: {
        schemas: {},
        tables: {},
        columns: {}
      }
    });
  }
});

// src/serializer/sqliteSchema.ts
var index5, fk4, compositePK5, column5, tableV33, uniqueConstraint5, checkConstraint4, table5, view4, dialect3, schemaHash5, schemaInternalV32, schemaInternalV42, schemaInternalV52, kitInternals5, latestVersion, schemaInternal3, schemaV32, schemaV42, schemaV52, schema3, tableSquashed5, schemaSquashed3, SQLiteSquasher, squashSqliteScheme, drySQLite, sqliteSchemaV5, sqliteSchema, SQLiteSchemaSquashed, backwardCompatibleSqliteSchema;
var init_sqliteSchema = __esm({
  "src/serializer/sqliteSchema.ts"() {
    "use strict";
    init_esm();
    init_global();
    index5 = objectType({
      name: stringType(),
      columns: stringType().array(),
      where: stringType().optional(),
      isUnique: booleanType()
    }).strict();
    fk4 = objectType({
      name: stringType(),
      tableFrom: stringType(),
      columnsFrom: stringType().array(),
      tableTo: stringType(),
      columnsTo: stringType().array(),
      onUpdate: stringType().optional(),
      onDelete: stringType().optional()
    }).strict();
    compositePK5 = objectType({
      columns: stringType().array(),
      name: stringType().optional()
    }).strict();
    column5 = objectType({
      name: stringType(),
      type: stringType(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      autoincrement: booleanType().optional(),
      default: anyType().optional(),
      generated: objectType({
        type: enumType(["stored", "virtual"]),
        as: stringType()
      }).optional()
    }).strict();
    tableV33 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column5),
      indexes: recordType(stringType(), index5),
      foreignKeys: recordType(stringType(), fk4)
    }).strict();
    uniqueConstraint5 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    checkConstraint4 = objectType({
      name: stringType(),
      value: stringType()
    }).strict();
    table5 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column5),
      indexes: recordType(stringType(), index5),
      foreignKeys: recordType(stringType(), fk4),
      compositePrimaryKeys: recordType(stringType(), compositePK5),
      uniqueConstraints: recordType(stringType(), uniqueConstraint5).default({}),
      checkConstraints: recordType(stringType(), checkConstraint4).default({})
    }).strict();
    view4 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column5),
      definition: stringType().optional(),
      isExisting: booleanType()
    }).strict();
    dialect3 = enumType(["sqlite"]);
    schemaHash5 = objectType({
      id: stringType(),
      prevId: stringType()
    }).strict();
    schemaInternalV32 = objectType({
      version: literalType("3"),
      dialect: dialect3,
      tables: recordType(stringType(), tableV33),
      enums: objectType({})
    }).strict();
    schemaInternalV42 = objectType({
      version: literalType("4"),
      dialect: dialect3,
      tables: recordType(stringType(), table5),
      views: recordType(stringType(), view4).default({}),
      enums: objectType({})
    }).strict();
    schemaInternalV52 = objectType({
      version: literalType("5"),
      dialect: dialect3,
      tables: recordType(stringType(), table5),
      enums: objectType({}),
      _meta: objectType({
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      })
    }).strict();
    kitInternals5 = objectType({
      indexes: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({ isExpression: booleanType().optional() }).optional()
          )
        }).optional()
      ).optional()
    }).optional();
    latestVersion = literalType("6");
    schemaInternal3 = objectType({
      version: latestVersion,
      dialect: dialect3,
      tables: recordType(stringType(), table5),
      views: recordType(stringType(), view4).default({}),
      enums: objectType({}),
      _meta: objectType({
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals5
    }).strict();
    schemaV32 = schemaInternalV32.merge(schemaHash5).strict();
    schemaV42 = schemaInternalV42.merge(schemaHash5).strict();
    schemaV52 = schemaInternalV52.merge(schemaHash5).strict();
    schema3 = schemaInternal3.merge(schemaHash5).strict();
    tableSquashed5 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column5),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()),
      uniqueConstraints: recordType(stringType(), stringType()).default({}),
      checkConstraints: recordType(stringType(), stringType()).default({})
    }).strict();
    schemaSquashed3 = objectType({
      version: latestVersion,
      dialect: dialect3,
      tables: recordType(stringType(), tableSquashed5),
      views: recordType(stringType(), view4),
      enums: anyType()
    }).strict();
    SQLiteSquasher = {
      squashIdx: (idx) => {
        index5.parse(idx);
        return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.where ?? ""}`;
      },
      unsquashIdx: (input) => {
        const [name, columnsString, isUnique, where] = input.split(";");
        const result = index5.parse({
          name,
          columns: columnsString.split(","),
          isUnique: isUnique === "true",
          where: where ?? void 0
        });
        return result;
      },
      squashUnique: (unq) => {
        return `${unq.name};${unq.columns.join(",")}`;
      },
      unsquashUnique: (unq) => {
        const [name, columns] = unq.split(";");
        return { name, columns: columns.split(",") };
      },
      squashFK: (fk5) => {
        return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`;
      },
      unsquashFK: (input) => {
        const [
          name,
          tableFrom,
          columnsFromStr,
          tableTo,
          columnsToStr,
          onUpdate,
          onDelete
        ] = input.split(";");
        const result = fk4.parse({
          name,
          tableFrom,
          columnsFrom: columnsFromStr.split(","),
          tableTo,
          columnsTo: columnsToStr.split(","),
          onUpdate,
          onDelete
        });
        return result;
      },
      squashPushFK: (fk5) => {
        return `${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`;
      },
      unsquashPushFK: (input) => {
        const [
          tableFrom,
          columnsFromStr,
          tableTo,
          columnsToStr,
          onUpdate,
          onDelete
        ] = input.split(";");
        const result = fk4.parse({
          name: "",
          tableFrom,
          columnsFrom: columnsFromStr.split(","),
          tableTo,
          columnsTo: columnsToStr.split(","),
          onUpdate,
          onDelete
        });
        return result;
      },
      squashPK: (pk) => {
        return pk.columns.join(",");
      },
      unsquashPK: (pk) => {
        return pk.split(",");
      },
      squashCheck: (check) => {
        return `${check.name};${check.value}`;
      },
      unsquashCheck: (input) => {
        const [
          name,
          value
        ] = input.split(";");
        return { name, value };
      }
    };
    squashSqliteScheme = (json, action) => {
      const mappedTables = Object.fromEntries(
        Object.entries(json.tables).map((it) => {
          const squashedIndexes = mapValues(it[1].indexes, (index6) => {
            return SQLiteSquasher.squashIdx(index6);
          });
          const squashedFKs = customMapEntries(
            it[1].foreignKeys,
            (key, value) => {
              return action === "push" ? [
                SQLiteSquasher.squashPushFK(value),
                SQLiteSquasher.squashPushFK(value)
              ] : [key, SQLiteSquasher.squashFK(value)];
            }
          );
          const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
            return SQLiteSquasher.squashPK(pk);
          });
          const squashedUniqueConstraints = mapValues(
            it[1].uniqueConstraints,
            (unq) => {
              return SQLiteSquasher.squashUnique(unq);
            }
          );
          const squashedCheckConstraints = mapValues(
            it[1].checkConstraints,
            (check) => {
              return SQLiteSquasher.squashCheck(check);
            }
          );
          return [
            it[0],
            {
              name: it[1].name,
              columns: it[1].columns,
              indexes: squashedIndexes,
              foreignKeys: squashedFKs,
              compositePrimaryKeys: squashedPKs,
              uniqueConstraints: squashedUniqueConstraints,
              checkConstraints: squashedCheckConstraints
            }
          ];
        })
      );
      return {
        version: "6",
        dialect: json.dialect,
        tables: mappedTables,
        views: json.views,
        enums: json.enums
      };
    };
    drySQLite = schema3.parse({
      version: "6",
      dialect: "sqlite",
      id: originUUID,
      prevId: "",
      tables: {},
      views: {},
      enums: {},
      _meta: {
        tables: {},
        columns: {}
      }
    });
    sqliteSchemaV5 = schemaV52;
    sqliteSchema = schema3;
    SQLiteSchemaSquashed = schemaSquashed3;
    backwardCompatibleSqliteSchema = unionType([sqliteSchemaV5, schema3]);
  }
});

// src/utils.ts
function isPgArrayType(sqlType) {
  return sqlType.match(/.*\[\d*\].*|.*\[\].*/g) !== null;
}
function findAddedAndRemoved(columnNames1, columnNames2) {
  const set1 = new Set(columnNames1);
  const set2 = new Set(columnNames2);
  const addedColumns = columnNames2.filter((it) => !set1.has(it));
  const removedColumns = columnNames1.filter((it) => !set2.has(it));
  return { addedColumns, removedColumns };
}
function escapeSingleQuotes(str) {
  return str.replace(/'/g, "''");
}
var import_url, copy, prepareMigrationMeta, schemaRenameKey, tableRenameKey, columnRenameKey, normaliseSQLiteUrl, normalisePGliteUrl;
var init_utils = __esm({
  "src/utils.ts"() {
    "use strict";
    import_url = require("url");
    init_views();
    init_global();
    init_gelSchema();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    copy = (it) => {
      return JSON.parse(JSON.stringify(it));
    };
    prepareMigrationMeta = (schemas, tables, columns) => {
      const _meta = {
        schemas: {},
        tables: {},
        columns: {}
      };
      schemas.forEach((it) => {
        const from = schemaRenameKey(it.from);
        const to = schemaRenameKey(it.to);
        _meta.schemas[from] = to;
      });
      tables.forEach((it) => {
        const from = tableRenameKey(it.from);
        const to = tableRenameKey(it.to);
        _meta.tables[from] = to;
      });
      columns.forEach((it) => {
        const from = columnRenameKey(it.from.table, it.from.schema, it.from.column);
        const to = columnRenameKey(it.to.table, it.to.schema, it.to.column);
        _meta.columns[from] = to;
      });
      return _meta;
    };
    schemaRenameKey = (it) => {
      return it;
    };
    tableRenameKey = (it) => {
      const out = it.schema ? `"${it.schema}"."${it.name}"` : `"${it.name}"`;
      return out;
    };
    columnRenameKey = (table6, schema6, column6) => {
      const out = schema6 ? `"${schema6}"."${table6}"."${column6}"` : `"${table6}"."${column6}"`;
      return out;
    };
    normaliseSQLiteUrl = (it, type) => {
      if (type === "libsql") {
        if (it.startsWith("file:")) {
          return it;
        }
        try {
          const url = (0, import_url.parse)(it);
          if (url.protocol === null) {
            return `file:${it}`;
          }
          return it;
        } catch (e6) {
          return `file:${it}`;
        }
      }
      if (type === "better-sqlite") {
        if (it.startsWith("file:")) {
          return it.substring(5);
        }
        return it;
      }
      assertUnreachable(type);
    };
    normalisePGliteUrl = (it) => {
      if (it.startsWith("file:")) {
        return it.substring(5);
      }
      return it;
    };
  }
});

// src/cli/views.ts
var import_hanji, warning, err, error, isRenamePromptItem, ResolveColumnSelect, tableKey, ResolveSelectNamed, ResolveSelect, ResolveSchemasSelect, Spinner, ProgressView;
var init_views = __esm({
  "src/cli/views.ts"() {
    "use strict";
    init_source();
    import_hanji = __toESM(require_hanji());
    init_utils();
    warning = (msg) => {
      (0, import_hanji.render)(`[${source_default.yellow("Warning")}] ${msg}`);
    };
    err = (msg) => {
      (0, import_hanji.render)(`${source_default.bold.red("Error")} ${msg}`);
    };
    error = (error2, greyMsg = "") => {
      return `${source_default.bgRed.bold(" Error ")} ${error2} ${greyMsg ? source_default.grey(greyMsg) : ""}`.trim();
    };
    isRenamePromptItem = (item) => {
      return "from" in item && "to" in item;
    };
    ResolveColumnSelect = class extends import_hanji.Prompt {
      constructor(tableName, base, data) {
        super();
        this.tableName = tableName;
        this.base = base;
        this.on("attach", (terminal) => terminal.toggleCursor("hide"));
        this.data = new import_hanji.SelectState(data);
        this.data.bind(this);
      }
      render(status) {
        if (status === "submitted" || status === "aborted") {
          return "\n";
        }
        let text = `
Is ${source_default.bold.blue(
          this.base.name
        )} column in ${source_default.bold.blue(
          this.tableName
        )} table created or renamed from another column?
`;
        const isSelectedRenamed = isRenamePromptItem(
          this.data.items[this.data.selectedIdx]
        );
        const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
        const labelLength = this.data.items.filter((it) => isRenamePromptItem(it)).map((it) => {
          return this.base.name.length + 3 + it["from"].name.length;
        }).reduce((a5, b5) => {
          if (a5 > b5) {
            return a5;
          }
          return b5;
        }, 0);
        this.data.items.forEach((it, idx) => {
          const isSelected = idx === this.data.selectedIdx;
          const isRenamed = isRenamePromptItem(it);
          const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " ");
          const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray("rename column")}` : `${source_default.green("+")} ${title} ${source_default.gray("create column")}`;
          text += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text += idx != this.data.items.length - 1 ? "\n" : "";
        });
        return text;
      }
      result() {
        return this.data.items[this.data.selectedIdx];
      }
    };
    tableKey = (it) => {
      return it.schema === "public" || !it.schema ? it.name : `${it.schema}.${it.name}`;
    };
    ResolveSelectNamed = class extends import_hanji.Prompt {
      constructor(base, data, entityType) {
        super();
        this.base = base;
        this.entityType = entityType;
        this.on("attach", (terminal) => terminal.toggleCursor("hide"));
        this.state = new import_hanji.SelectState(data);
        this.state.bind(this);
        this.base = base;
      }
      render(status) {
        if (status === "submitted" || status === "aborted") {
          return "";
        }
        const key = this.base.name;
        let text = `
Is ${source_default.bold.blue(key)} ${this.entityType} created or renamed from another ${this.entityType}?
`;
        const isSelectedRenamed = isRenamePromptItem(
          this.state.items[this.state.selectedIdx]
        );
        const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
        const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((_3) => {
          const it = _3;
          const keyFrom = it.from.name;
          return key.length + 3 + keyFrom.length;
        }).reduce((a5, b5) => {
          if (a5 > b5) {
            return a5;
          }
          return b5;
        }, 0);
        const entityType = this.entityType;
        this.state.items.forEach((it, idx) => {
          const isSelected = idx === this.state.selectedIdx;
          const isRenamed = isRenamePromptItem(it);
          const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " ");
          const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray(`rename ${entityType}`)}` : `${source_default.green("+")} ${title} ${source_default.gray(`create ${entityType}`)}`;
          text += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text += idx != this.state.items.length - 1 ? "\n" : "";
        });
        return text;
      }
      result() {
        return this.state.items[this.state.selectedIdx];
      }
    };
    ResolveSelect = class extends import_hanji.Prompt {
      constructor(base, data, entityType) {
        super();
        this.base = base;
        this.entityType = entityType;
        this.on("attach", (terminal) => terminal.toggleCursor("hide"));
        this.state = new import_hanji.SelectState(data);
        this.state.bind(this);
        this.base = base;
      }
      render(status) {
        if (status === "submitted" || status === "aborted") {
          return "";
        }
        const key = tableKey(this.base);
        let text = `
Is ${source_default.bold.blue(key)} ${this.entityType} created or renamed from another ${this.entityType}?
`;
        const isSelectedRenamed = isRenamePromptItem(
          this.state.items[this.state.selectedIdx]
        );
        const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
        const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((_3) => {
          const it = _3;
          const keyFrom = tableKey(it.from);
          return key.length + 3 + keyFrom.length;
        }).reduce((a5, b5) => {
          if (a5 > b5) {
            return a5;
          }
          return b5;
        }, 0);
        const entityType = this.entityType;
        this.state.items.forEach((it, idx) => {
          const isSelected = idx === this.state.selectedIdx;
          const isRenamed = isRenamePromptItem(it);
          const title = isRenamed ? `${tableKey(it.from)} \u203A ${tableKey(it.to)}`.padEnd(labelLength, " ") : tableKey(it).padEnd(labelLength, " ");
          const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray(`rename ${entityType}`)}` : `${source_default.green("+")} ${title} ${source_default.gray(`create ${entityType}`)}`;
          text += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text += idx != this.state.items.length - 1 ? "\n" : "";
        });
        return text;
      }
      result() {
        return this.state.items[this.state.selectedIdx];
      }
    };
    ResolveSchemasSelect = class extends import_hanji.Prompt {
      constructor(base, data) {
        super();
        this.base = base;
        this.on("attach", (terminal) => terminal.toggleCursor("hide"));
        this.state = new import_hanji.SelectState(data);
        this.state.bind(this);
        this.base = base;
      }
      render(status) {
        if (status === "submitted" || status === "aborted") {
          return "";
        }
        let text = `
Is ${source_default.bold.blue(
          this.base.name
        )} schema created or renamed from another schema?
`;
        const isSelectedRenamed = isRenamePromptItem(
          this.state.items[this.state.selectedIdx]
        );
        const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
        const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((it) => {
          return this.base.name.length + 3 + it["from"].name.length;
        }).reduce((a5, b5) => {
          if (a5 > b5) {
            return a5;
          }
          return b5;
        }, 0);
        this.state.items.forEach((it, idx) => {
          const isSelected = idx === this.state.selectedIdx;
          const isRenamed = isRenamePromptItem(it);
          const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " ");
          const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray("rename schema")}` : `${source_default.green("+")} ${title} ${source_default.gray("create schema")}`;
          text += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text += idx != this.state.items.length - 1 ? "\n" : "";
        });
        return text;
      }
      result() {
        return this.state.items[this.state.selectedIdx];
      }
    };
    Spinner = class {
      constructor(frames) {
        this.frames = frames;
        this.offset = 0;
        this.tick = () => {
          this.iterator();
        };
        this.value = () => {
          return this.frames[this.offset];
        };
        this.iterator = () => {
          this.offset += 1;
          this.offset %= frames.length - 1;
        };
      }
    };
    ProgressView = class extends import_hanji.TaskView {
      constructor(progressText, successText) {
        super();
        this.progressText = progressText;
        this.successText = successText;
        this.spinner = new Spinner("\u28F7\u28EF\u28DF\u287F\u28BF\u28FB\u28FD\u28FE".split(""));
        this.timeout = setInterval(() => {
          this.spinner.tick();
          this.requestLayout();
        }, 128);
        this.on("detach", () => clearInterval(this.timeout));
      }
      render(status) {
        if (status === "pending") {
          const spin = this.spinner.value();
          return `[${spin}] ${this.progressText}
`;
        }
        return `[${source_default.green("\u2713")}] ${this.successText}
`;
      }
    };
  }
});

// src/serializer/index.ts
var import_fs, glob, import_path, prepareFilenames;
var init_serializer = __esm({
  "src/serializer/index.ts"() {
    "use strict";
    import_fs = __toESM(require("fs"));
    glob = __toESM(require_glob());
    import_path = __toESM(require("path"));
    init_views();
    prepareFilenames = (path3) => {
      if (typeof path3 === "string") {
        path3 = [path3];
      }
      const prefix2 = process.env.TEST_CONFIG_PATH_PREFIX || "";
      const result = path3.reduce((result2, cur) => {
        const globbed = glob.sync(`${prefix2}${cur}`);
        globbed.forEach((it) => {
          const fileName = import_fs.default.lstatSync(it).isDirectory() ? null : import_path.default.resolve(it);
          const filenames = fileName ? [fileName] : import_fs.default.readdirSync(it).map((file) => import_path.default.join(import_path.default.resolve(it), file));
          filenames.filter((file) => !import_fs.default.lstatSync(file).isDirectory()).forEach((file) => result2.add(file));
        });
        return result2;
      }, /* @__PURE__ */ new Set());
      const res = [...result];
      const errors = res.filter((it) => {
        return !(it.endsWith(".ts") || it.endsWith(".js") || it.endsWith(".cjs") || it.endsWith(".mjs") || it.endsWith(".mts") || it.endsWith(".cts"));
      });
      if (res.length === 0) {
        console.log(
          error(
            `No schema files found for path config [${path3.map((it) => `'${it}'`).join(", ")}]`
          )
        );
        console.log(
          error(
            `If path represents a file - please make sure to use .ts or other extension in the path`
          )
        );
        process.exit(1);
      }
      return res;
    };
  }
});

// src/migrationPreparator.ts
var init_migrationPreparator = __esm({
  "src/migrationPreparator.ts"() {
    "use strict";
    init_serializer();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
  }
});

// ../node_modules/.pnpm/heap@0.2.7/node_modules/heap/lib/heap.js
var require_heap = __commonJS({
  "../node_modules/.pnpm/heap@0.2.7/node_modules/heap/lib/heap.js"(exports2, module2) {
    "use strict";
    (function() {
      var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;
      floor = Math.floor, min = Math.min;
      defaultCmp = function(x5, y2) {
        if (x5 < y2) {
          return -1;
        }
        if (x5 > y2) {
          return 1;
        }
        return 0;
      };
      insort = function(a5, x5, lo, hi, cmp) {
        var mid;
        if (lo == null) {
          lo = 0;
        }
        if (cmp == null) {
          cmp = defaultCmp;
        }
        if (lo < 0) {
          throw new Error("lo must be non-negative");
        }
        if (hi == null) {
          hi = a5.length;
        }
        while (lo < hi) {
          mid = floor((lo + hi) / 2);
          if (cmp(x5, a5[mid]) < 0) {
            hi = mid;
          } else {
            lo = mid + 1;
          }
        }
        return [].splice.apply(a5, [lo, lo - lo].concat(x5)), x5;
      };
      heappush = function(array2, item, cmp) {
        if (cmp == null) {
          cmp = defaultCmp;
        }
        array2.push(item);
        return _siftdown(array2, 0, array2.length - 1, cmp);
      };
      heappop = function(array2, cmp) {
        var lastelt, returnitem;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        lastelt = array2.pop();
        if (array2.length) {
          returnitem = array2[0];
          array2[0] = lastelt;
          _siftup(array2, 0, cmp);
        } else {
          returnitem = lastelt;
        }
        return returnitem;
      };
      heapreplace = function(array2, item, cmp) {
        var returnitem;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        returnitem = array2[0];
        array2[0] = item;
        _siftup(array2, 0, cmp);
        return returnitem;
      };
      heappushpop = function(array2, item, cmp) {
        var _ref;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        if (array2.length && cmp(array2[0], item) < 0) {
          _ref = [array2[0], item], item = _ref[0], array2[0] = _ref[1];
          _siftup(array2, 0, cmp);
        }
        return item;
      };
      heapify = function(array2, cmp) {
        var i6, _i, _j, _len, _ref, _ref1, _results, _results1;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        _ref1 = function() {
          _results1 = [];
          for (var _j2 = 0, _ref2 = floor(array2.length / 2); 0 <= _ref2 ? _j2 < _ref2 : _j2 > _ref2; 0 <= _ref2 ? _j2++ : _j2--) {
            _results1.push(_j2);
          }
          return _results1;
        }.apply(this).reverse();
        _results = [];
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          i6 = _ref1[_i];
          _results.push(_siftup(array2, i6, cmp));
        }
        return _results;
      };
      updateItem = function(array2, item, cmp) {
        var pos;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        pos = array2.indexOf(item);
        if (pos === -1) {
          return;
        }
        _siftdown(array2, 0, pos, cmp);
        return _siftup(array2, pos, cmp);
      };
      nlargest = function(array2, n5, cmp) {
        var elem, result, _i, _len, _ref;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        result = array2.slice(0, n5);
        if (!result.length) {
          return result;
        }
        heapify(result, cmp);
        _ref = array2.slice(n5);
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          elem = _ref[_i];
          heappushpop(result, elem, cmp);
        }
        return result.sort(cmp).reverse();
      };
      nsmallest = function(array2, n5, cmp) {
        var elem, i6, los, result, _i, _j, _len, _ref, _ref1, _results;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        if (n5 * 10 <= array2.length) {
          result = array2.slice(0, n5).sort(cmp);
          if (!result.length) {
            return result;
          }
          los = result[result.length - 1];
          _ref = array2.slice(n5);
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            elem = _ref[_i];
            if (cmp(elem, los) < 0) {
              insort(result, elem, 0, null, cmp);
              result.pop();
              los = result[result.length - 1];
            }
          }
          return result;
        }
        heapify(array2, cmp);
        _results = [];
        for (i6 = _j = 0, _ref1 = min(n5, array2.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i6 = 0 <= _ref1 ? ++_j : --_j) {
          _results.push(heappop(array2, cmp));
        }
        return _results;
      };
      _siftdown = function(array2, startpos, pos, cmp) {
        var newitem, parent, parentpos;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        newitem = array2[pos];
        while (pos > startpos) {
          parentpos = pos - 1 >> 1;
          parent = array2[parentpos];
          if (cmp(newitem, parent) < 0) {
            array2[pos] = parent;
            pos = parentpos;
            continue;
          }
          break;
        }
        return array2[pos] = newitem;
      };
      _siftup = function(array2, pos, cmp) {
        var childpos, endpos, newitem, rightpos, startpos;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        endpos = array2.length;
        startpos = pos;
        newitem = array2[pos];
        childpos = 2 * pos + 1;
        while (childpos < endpos) {
          rightpos = childpos + 1;
          if (rightpos < endpos && !(cmp(array2[childpos], array2[rightpos]) < 0)) {
            childpos = rightpos;
          }
          array2[pos] = array2[childpos];
          pos = childpos;
          childpos = 2 * pos + 1;
        }
        array2[pos] = newitem;
        return _siftdown(array2, startpos, pos, cmp);
      };
      Heap = function() {
        Heap2.push = heappush;
        Heap2.pop = heappop;
        Heap2.replace = heapreplace;
        Heap2.pushpop = heappushpop;
        Heap2.heapify = heapify;
        Heap2.updateItem = updateItem;
        Heap2.nlargest = nlargest;
        Heap2.nsmallest = nsmallest;
        function Heap2(cmp) {
          this.cmp = cmp != null ? cmp : defaultCmp;
          this.nodes = [];
        }
        Heap2.prototype.push = function(x5) {
          return heappush(this.nodes, x5, this.cmp);
        };
        Heap2.prototype.pop = function() {
          return heappop(this.nodes, this.cmp);
        };
        Heap2.prototype.peek = function() {
          return this.nodes[0];
        };
        Heap2.prototype.contains = function(x5) {
          return this.nodes.indexOf(x5) !== -1;
        };
        Heap2.prototype.replace = function(x5) {
          return heapreplace(this.nodes, x5, this.cmp);
        };
        Heap2.prototype.pushpop = function(x5) {
          return heappushpop(this.nodes, x5, this.cmp);
        };
        Heap2.prototype.heapify = function() {
          return heapify(this.nodes, this.cmp);
        };
        Heap2.prototype.updateItem = function(x5) {
          return updateItem(this.nodes, x5, this.cmp);
        };
        Heap2.prototype.clear = function() {
          return this.nodes = [];
        };
        Heap2.prototype.empty = function() {
          return this.nodes.length === 0;
        };
        Heap2.prototype.size = function() {
          return this.nodes.length;
        };
        Heap2.prototype.clone = function() {
          var heap;
          heap = new Heap2();
          heap.nodes = this.nodes.slice(0);
          return heap;
        };
        Heap2.prototype.toArray = function() {
          return this.nodes.slice(0);
        };
        Heap2.prototype.insert = Heap2.prototype.push;
        Heap2.prototype.top = Heap2.prototype.peek;
        Heap2.prototype.front = Heap2.prototype.peek;
        Heap2.prototype.has = Heap2.prototype.contains;
        Heap2.prototype.copy = Heap2.prototype.clone;
        return Heap2;
      }();
      (function(root, factory) {
        if (typeof define === "function" && define.amd) {
          return define([], factory);
        } else if (typeof exports2 === "object") {
          return module2.exports = factory();
        } else {
          return root.Heap = factory();
        }
      })(this, function() {
        return Heap;
      });
    }).call(exports2);
  }
});

// ../node_modules/.pnpm/heap@0.2.7/node_modules/heap/index.js
var require_heap2 = __commonJS({
  "../node_modules/.pnpm/heap@0.2.7/node_modules/heap/index.js"(exports2, module2) {
    "use strict";
    module2.exports = require_heap();
  }
});

// ../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/lib/difflib.js
var require_difflib = __commonJS({
  "../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/lib/difflib.js"(exports2) {
    "use strict";
    (function() {
      var Differ, Heap, IS_CHARACTER_JUNK, IS_LINE_JUNK, SequenceMatcher, _any, _arrayCmp, _calculateRatio, _countLeading, _formatRangeContext, _formatRangeUnified, _has, assert, contextDiff, floor, getCloseMatches, max, min, ndiff, restore, unifiedDiff, indexOf = [].indexOf;
      ({ floor, max, min } = Math);
      Heap = require_heap2();
      assert = require("assert");
      _calculateRatio = function(matches, length) {
        if (length) {
          return 2 * matches / length;
        } else {
          return 1;
        }
      };
      _arrayCmp = function(a5, b5) {
        var i6, l5, la, lb, ref;
        [la, lb] = [a5.length, b5.length];
        for (i6 = l5 = 0, ref = min(la, lb); 0 <= ref ? l5 < ref : l5 > ref; i6 = 0 <= ref ? ++l5 : --l5) {
          if (a5[i6] < b5[i6]) {
            return -1;
          }
          if (a5[i6] > b5[i6]) {
            return 1;
          }
        }
        return la - lb;
      };
      _has = function(obj, key) {
        return Object.prototype.hasOwnProperty.call(obj, key);
      };
      _any = function(items) {
        var item, l5, len;
        for (l5 = 0, len = items.length; l5 < len; l5++) {
          item = items[l5];
          if (item) {
            return true;
          }
        }
        return false;
      };
      SequenceMatcher = class SequenceMatcher {
        /*
            SequenceMatcher is a flexible class for comparing pairs of sequences of
            any type, so long as the sequence elements are hashable.  The basic
            algorithm predates, and is a little fancier than, an algorithm
            published in the late 1980's by Ratcliff and Obershelp under the
            hyperbolic name "gestalt pattern matching".  The basic idea is to find
            the longest contiguous matching subsequence that contains no "junk"
            elements (R-O doesn't address junk).  The same idea is then applied
            recursively to the pieces of the sequences to the left and to the right
            of the matching subsequence.  This does not yield minimal edit
            sequences, but does tend to yield matches that "look right" to people.
        
            SequenceMatcher tries to compute a "human-friendly diff" between two
            sequences.  Unlike e.g. UNIX(tm) diff, the fundamental notion is the
            longest *contiguous* & junk-free matching subsequence.  That's what
            catches peoples' eyes.  The Windows(tm) windiff has another interesting
            notion, pairing up elements that appear uniquely in each sequence.
            That, and the method here, appear to yield more intuitive difference
            reports than does diff.  This method appears to be the least vulnerable
            to synching up on blocks of "junk lines", though (like blank lines in
            ordinary text files, or maybe "<P>" lines in HTML files).  That may be
            because this is the only method of the 3 that has a *concept* of
            "junk" <wink>.
        
            Example, comparing two strings, and considering blanks to be "junk":
        
            >>> isjunk = (c) -> c is ' '
            >>> s = new SequenceMatcher(isjunk,
                                        'private Thread currentThread;',
                                        'private volatile Thread currentThread;')
        
            .ratio() returns a float in [0, 1], measuring the "similarity" of the
            sequences.  As a rule of thumb, a .ratio() value over 0.6 means the
            sequences are close matches:
        
            >>> s.ratio().toPrecision(3)
            '0.866'
        
            If you're only interested in where the sequences match,
            .getMatchingBlocks() is handy:
        
            >>> for [a, b, size] in s.getMatchingBlocks()
            ...   console.log("a[#{a}] and b[#{b}] match for #{size} elements");
            a[0] and b[0] match for 8 elements
            a[8] and b[17] match for 21 elements
            a[29] and b[38] match for 0 elements
        
            Note that the last tuple returned by .get_matching_blocks() is always a
            dummy, (len(a), len(b), 0), and this is the only case in which the last
            tuple element (number of elements matched) is 0.
        
            If you want to know how to change the first sequence into the second,
            use .get_opcodes():
        
            >>> for [op, a1, a2, b1, b2] in s.getOpcodes()
            ...   console.log "#{op} a[#{a1}:#{a2}] b[#{b1}:#{b2}]"
            equal a[0:8] b[0:8]
            insert a[8:8] b[8:17]
            equal a[8:29] b[17:38]
        
            See the Differ class for a fancy human-friendly file differencer, which
            uses SequenceMatcher both to compare sequences of lines, and to compare
            sequences of characters within similar (near-matching) lines.
        
            See also function getCloseMatches() in this module, which shows how
            simple code building on SequenceMatcher can be used to do useful work.
        
            Timing:  Basic R-O is cubic time worst case and quadratic time expected
            case.  SequenceMatcher is quadratic time for the worst case and has
            expected-case behavior dependent in a complicated way on how many
            elements the sequences have in common; best case time is linear.
        
            Methods:
        
            constructor(isjunk=null, a='', b='')
                Construct a SequenceMatcher.
        
            setSeqs(a, b)
                Set the two sequences to be compared.
        
            setSeq1(a)
                Set the first sequence to be compared.
        
            setSeq2(b)
                Set the second sequence to be compared.
        
            findLongestMatch(alo, ahi, blo, bhi)
                Find longest matching block in a[alo:ahi] and b[blo:bhi].
        
            getMatchingBlocks()
                Return list of triples describing matching subsequences.
        
            getOpcodes()
                Return list of 5-tuples describing how to turn a into b.
        
            ratio()
                Return a measure of the sequences' similarity (float in [0,1]).
        
            quickRatio()
                Return an upper bound on .ratio() relatively quickly.
        
            realQuickRatio()
                Return an upper bound on ratio() very quickly.
            */
        constructor(isjunk1, a5 = "", b5 = "", autojunk = true) {
          this.isjunk = isjunk1;
          this.autojunk = autojunk;
          this.a = this.b = null;
          this.setSeqs(a5, b5);
        }
        setSeqs(a5, b5) {
          this.setSeq1(a5);
          return this.setSeq2(b5);
        }
        setSeq1(a5) {
          if (a5 === this.a) {
            return;
          }
          this.a = a5;
          return this.matchingBlocks = this.opcodes = null;
        }
        setSeq2(b5) {
          if (b5 === this.b) {
            return;
          }
          this.b = b5;
          this.matchingBlocks = this.opcodes = null;
          this.fullbcount = null;
          return this._chainB();
        }
        // For each element x in b, set b2j[x] to a list of the indices in
        // b where x appears; the indices are in increasing order; note that
        // the number of times x appears in b is b2j[x].length ...
        // when @isjunk is defined, junk elements don't show up in this
        // map at all, which stops the central findLongestMatch method
        // from starting any matching block at a junk element ...
        // also creates the fast isbjunk function ...
        // b2j also does not contain entries for "popular" elements, meaning
        // elements that account for more than 1 + 1% of the total elements, and
        // when the sequence is reasonably large (>= 200 elements); this can
        // be viewed as an adaptive notion of semi-junk, and yields an enormous
        // speedup when, e.g., comparing program files with hundreds of
        // instances of "return null;" ...
        // note that this is only called when b changes; so for cross-product
        // kinds of matches, it's best to call setSeq2 once, then setSeq1
        // repeatedly
        _chainB() {
          var b5, b2j, elt, i6, indices, isjunk, junk, l5, len, n5, ntest, popular;
          b5 = this.b;
          this.b2j = b2j = /* @__PURE__ */ new Map();
          for (i6 = l5 = 0, len = b5.length; l5 < len; i6 = ++l5) {
            elt = b5[i6];
            if (!b2j.has(elt)) {
              b2j.set(elt, []);
            }
            indices = b2j.get(elt);
            indices.push(i6);
          }
          junk = /* @__PURE__ */ new Map();
          isjunk = this.isjunk;
          if (isjunk) {
            b2j.forEach(function(idxs, elt2) {
              if (isjunk(elt2)) {
                junk.set(elt2, true);
                return b2j.delete(elt2);
              }
            });
          }
          popular = /* @__PURE__ */ new Map();
          n5 = b5.length;
          if (this.autojunk && n5 >= 200) {
            ntest = floor(n5 / 100) + 1;
            b2j.forEach(function(idxs, elt2) {
              if (idxs.length > ntest) {
                popular.set(elt2, true);
                return b2j.delete(elt2);
              }
            });
          }
          this.isbjunk = function(b6) {
            return junk.has(b6);
          };
          return this.isbpopular = function(b6) {
            return popular.has(b6);
          };
        }
        findLongestMatch(alo, ahi, blo, bhi) {
          var a5, b5, b2j, besti, bestj, bestsize, i6, isbjunk, j5, j2len, jlist, k5, l5, len, m6, newj2len, ref, ref1;
          [a5, b5, b2j, isbjunk] = [this.a, this.b, this.b2j, this.isbjunk];
          [besti, bestj, bestsize] = [alo, blo, 0];
          j2len = {};
          for (i6 = l5 = ref = alo, ref1 = ahi; ref <= ref1 ? l5 < ref1 : l5 > ref1; i6 = ref <= ref1 ? ++l5 : --l5) {
            newj2len = {};
            jlist = [];
            if (b2j.has(a5[i6])) {
              jlist = b2j.get(a5[i6]);
            }
            for (m6 = 0, len = jlist.length; m6 < len; m6++) {
              j5 = jlist[m6];
              if (j5 < blo) {
                continue;
              }
              if (j5 >= bhi) {
                break;
              }
              k5 = newj2len[j5] = (j2len[j5 - 1] || 0) + 1;
              if (k5 > bestsize) {
                [besti, bestj, bestsize] = [i6 - k5 + 1, j5 - k5 + 1, k5];
              }
            }
            j2len = newj2len;
          }
          while (besti > alo && bestj > blo && !isbjunk(b5[bestj - 1]) && a5[besti - 1] === b5[bestj - 1]) {
            [besti, bestj, bestsize] = [besti - 1, bestj - 1, bestsize + 1];
          }
          while (besti + bestsize < ahi && bestj + bestsize < bhi && !isbjunk(b5[bestj + bestsize]) && a5[besti + bestsize] === b5[bestj + bestsize]) {
            bestsize++;
          }
          while (besti > alo && bestj > blo && isbjunk(b5[bestj - 1]) && a5[besti - 1] === b5[bestj - 1]) {
            [besti, bestj, bestsize] = [besti - 1, bestj - 1, bestsize + 1];
          }
          while (besti + bestsize < ahi && bestj + bestsize < bhi && isbjunk(b5[bestj + bestsize]) && a5[besti + bestsize] === b5[bestj + bestsize]) {
            bestsize++;
          }
          return [besti, bestj, bestsize];
        }
        getMatchingBlocks() {
          var ahi, alo, bhi, blo, i6, i1, i22, j5, j1, j22, k5, k1, k22, l5, la, lb, len, matchingBlocks, nonAdjacent, queue, x5;
          if (this.matchingBlocks) {
            return this.matchingBlocks;
          }
          [la, lb] = [this.a.length, this.b.length];
          queue = [[0, la, 0, lb]];
          matchingBlocks = [];
          while (queue.length) {
            [alo, ahi, blo, bhi] = queue.pop();
            [i6, j5, k5] = x5 = this.findLongestMatch(alo, ahi, blo, bhi);
            if (k5) {
              matchingBlocks.push(x5);
              if (alo < i6 && blo < j5) {
                queue.push([alo, i6, blo, j5]);
              }
              if (i6 + k5 < ahi && j5 + k5 < bhi) {
                queue.push([i6 + k5, ahi, j5 + k5, bhi]);
              }
            }
          }
          matchingBlocks.sort(_arrayCmp);
          i1 = j1 = k1 = 0;
          nonAdjacent = [];
          for (l5 = 0, len = matchingBlocks.length; l5 < len; l5++) {
            [i22, j22, k22] = matchingBlocks[l5];
            if (i1 + k1 === i22 && j1 + k1 === j22) {
              k1 += k22;
            } else {
              if (k1) {
                nonAdjacent.push([i1, j1, k1]);
              }
              [i1, j1, k1] = [i22, j22, k22];
            }
          }
          if (k1) {
            nonAdjacent.push([i1, j1, k1]);
          }
          nonAdjacent.push([la, lb, 0]);
          return this.matchingBlocks = nonAdjacent;
        }
        getOpcodes() {
          var ai, answer, bj, i6, j5, l5, len, ref, size, tag;
          if (this.opcodes) {
            return this.opcodes;
          }
          i6 = j5 = 0;
          this.opcodes = answer = [];
          ref = this.getMatchingBlocks();
          for (l5 = 0, len = ref.length; l5 < len; l5++) {
            [ai, bj, size] = ref[l5];
            tag = "";
            if (i6 < ai && j5 < bj) {
              tag = "replace";
            } else if (i6 < ai) {
              tag = "delete";
            } else if (j5 < bj) {
              tag = "insert";
            }
            if (tag) {
              answer.push([tag, i6, ai, j5, bj]);
            }
            [i6, j5] = [ai + size, bj + size];
            if (size) {
              answer.push(["equal", ai, i6, bj, j5]);
            }
          }
          return answer;
        }
        getGroupedOpcodes(n5 = 3) {
          var codes, group, groups, i1, i22, j1, j22, l5, len, nn, tag;
          codes = this.getOpcodes();
          if (!codes.length) {
            codes = [["equal", 0, 1, 0, 1]];
          }
          if (codes[0][0] === "equal") {
            [tag, i1, i22, j1, j22] = codes[0];
            codes[0] = [tag, max(i1, i22 - n5), i22, max(j1, j22 - n5), j22];
          }
          if (codes[codes.length - 1][0] === "equal") {
            [tag, i1, i22, j1, j22] = codes[codes.length - 1];
            codes[codes.length - 1] = [tag, i1, min(i22, i1 + n5), j1, min(j22, j1 + n5)];
          }
          nn = n5 + n5;
          groups = [];
          group = [];
          for (l5 = 0, len = codes.length; l5 < len; l5++) {
            [tag, i1, i22, j1, j22] = codes[l5];
            if (tag === "equal" && i22 - i1 > nn) {
              group.push([tag, i1, min(i22, i1 + n5), j1, min(j22, j1 + n5)]);
              groups.push(group);
              group = [];
              [i1, j1] = [max(i1, i22 - n5), max(j1, j22 - n5)];
            }
            group.push([tag, i1, i22, j1, j22]);
          }
          if (group.length && !(group.length === 1 && group[0][0] === "equal")) {
            groups.push(group);
          }
          return groups;
        }
        ratio() {
          var l5, len, match2, matches, ref;
          matches = 0;
          ref = this.getMatchingBlocks();
          for (l5 = 0, len = ref.length; l5 < len; l5++) {
            match2 = ref[l5];
            matches += match2[2];
          }
          return _calculateRatio(matches, this.a.length + this.b.length);
        }
        quickRatio() {
          var avail, elt, fullbcount, l5, len, len1, m6, matches, numb, ref, ref1;
          if (!this.fullbcount) {
            this.fullbcount = fullbcount = {};
            ref = this.b;
            for (l5 = 0, len = ref.length; l5 < len; l5++) {
              elt = ref[l5];
              fullbcount[elt] = (fullbcount[elt] || 0) + 1;
            }
          }
          fullbcount = this.fullbcount;
          avail = {};
          matches = 0;
          ref1 = this.a;
          for (m6 = 0, len1 = ref1.length; m6 < len1; m6++) {
            elt = ref1[m6];
            if (_has(avail, elt)) {
              numb = avail[elt];
            } else {
              numb = fullbcount[elt] || 0;
            }
            avail[elt] = numb - 1;
            if (numb > 0) {
              matches++;
            }
          }
          return _calculateRatio(matches, this.a.length + this.b.length);
        }
        realQuickRatio() {
          var la, lb;
          [la, lb] = [this.a.length, this.b.length];
          return _calculateRatio(min(la, lb), la + lb);
        }
      };
      getCloseMatches = function(word, possibilities, n5 = 3, cutoff = 0.6) {
        var l5, len, len1, m6, result, results, s6, score, x5;
        if (!(n5 > 0)) {
          throw new Error(`n must be > 0: (${n5})`);
        }
        if (!(0 <= cutoff && cutoff <= 1)) {
          throw new Error(`cutoff must be in [0.0, 1.0]: (${cutoff})`);
        }
        result = [];
        s6 = new SequenceMatcher();
        s6.setSeq2(word);
        for (l5 = 0, len = possibilities.length; l5 < len; l5++) {
          x5 = possibilities[l5];
          s6.setSeq1(x5);
          if (s6.realQuickRatio() >= cutoff && s6.quickRatio() >= cutoff && s6.ratio() >= cutoff) {
            result.push([s6.ratio(), x5]);
          }
        }
        result = Heap.nlargest(result, n5, _arrayCmp);
        results = [];
        for (m6 = 0, len1 = result.length; m6 < len1; m6++) {
          [score, x5] = result[m6];
          results.push(x5);
        }
        return results;
      };
      _countLeading = function(line, ch) {
        var i6, n5;
        [i6, n5] = [0, line.length];
        while (i6 < n5 && line[i6] === ch) {
          i6++;
        }
        return i6;
      };
      Differ = class Differ {
        /*
            Differ is a class for comparing sequences of lines of text, and
            producing human-readable differences or deltas.  Differ uses
            SequenceMatcher both to compare sequences of lines, and to compare
            sequences of characters within similar (near-matching) lines.
        
            Each line of a Differ delta begins with a two-letter code:
        
                '- '    line unique to sequence 1
                '+ '    line unique to sequence 2
                '  '    line common to both sequences
                '? '    line not present in either input sequence
        
            Lines beginning with '? ' attempt to guide the eye to intraline
            differences, and were not present in either input sequence.  These lines
            can be confusing if the sequences contain tab characters.
        
            Note that Differ makes no claim to produce a *minimal* diff.  To the
            contrary, minimal diffs are often counter-intuitive, because they synch
            up anywhere possible, sometimes accidental matches 100 pages apart.
            Restricting synch points to contiguous matches preserves some notion of
            locality, at the occasional cost of producing a longer diff.
        
            Example: Comparing two texts.
        
            >>> text1 = ['1. Beautiful is better than ugly.\n',
            ...   '2. Explicit is better than implicit.\n',
            ...   '3. Simple is better than complex.\n',
            ...   '4. Complex is better than complicated.\n']
            >>> text1.length
            4
            >>> text2 = ['1. Beautiful is better than ugly.\n',
            ...   '3.   Simple is better than complex.\n',
            ...   '4. Complicated is better than complex.\n',
            ...   '5. Flat is better than nested.\n']
        
            Next we instantiate a Differ object:
        
            >>> d = new Differ()
        
            Note that when instantiating a Differ object we may pass functions to
            filter out line and character 'junk'.
        
            Finally, we compare the two:
        
            >>> result = d.compare(text1, text2)
            [ '  1. Beautiful is better than ugly.\n',
              '- 2. Explicit is better than implicit.\n',
              '- 3. Simple is better than complex.\n',
              '+ 3.   Simple is better than complex.\n',
              '?   ++\n',
              '- 4. Complex is better than complicated.\n',
              '?          ^                     ---- ^\n',
              '+ 4. Complicated is better than complex.\n',
              '?         ++++ ^                      ^\n',
              '+ 5. Flat is better than nested.\n' ]
        
            Methods:
        
            constructor(linejunk=null, charjunk=null)
                Construct a text differencer, with optional filters.
            compare(a, b)
                Compare two sequences of lines; generate the resulting delta.
            */
        constructor(linejunk1, charjunk1) {
          this.linejunk = linejunk1;
          this.charjunk = charjunk1;
        }
        /*
            Construct a text differencer, with optional filters.
        
            The two optional keyword parameters are for filter functions:
        
            - `linejunk`: A function that should accept a single string argument,
              and return true iff the string is junk. The module-level function
              `IS_LINE_JUNK` may be used to filter out lines without visible
              characters, except for at most one splat ('#').  It is recommended
              to leave linejunk null. 
        
            - `charjunk`: A function that should accept a string of length 1. The
              module-level function `IS_CHARACTER_JUNK` may be used to filter out
              whitespace characters (a blank or tab; **note**: bad idea to include
              newline in this!).  Use of IS_CHARACTER_JUNK is recommended.
            */
        compare(a5, b5) {
          var ahi, alo, bhi, blo, cruncher, g5, l5, len, len1, line, lines, m6, ref, tag;
          cruncher = new SequenceMatcher(this.linejunk, a5, b5);
          lines = [];
          ref = cruncher.getOpcodes();
          for (l5 = 0, len = ref.length; l5 < len; l5++) {
            [tag, alo, ahi, blo, bhi] = ref[l5];
            switch (tag) {
              case "replace":
                g5 = this._fancyReplace(a5, alo, ahi, b5, blo, bhi);
                break;
              case "delete":
                g5 = this._dump("-", a5, alo, ahi);
                break;
              case "insert":
                g5 = this._dump("+", b5, blo, bhi);
                break;
              case "equal":
                g5 = this._dump(" ", a5, alo, ahi);
                break;
              default:
                throw new Error(`unknow tag (${tag})`);
            }
            for (m6 = 0, len1 = g5.length; m6 < len1; m6++) {
              line = g5[m6];
              lines.push(line);
            }
          }
          return lines;
        }
        _dump(tag, x5, lo, hi) {
          var i6, l5, ref, ref1, results;
          results = [];
          for (i6 = l5 = ref = lo, ref1 = hi; ref <= ref1 ? l5 < ref1 : l5 > ref1; i6 = ref <= ref1 ? ++l5 : --l5) {
            results.push(`${tag} ${x5[i6]}`);
          }
          return results;
        }
        _plainReplace(a5, alo, ahi, b5, blo, bhi) {
          var first, g5, l5, len, len1, line, lines, m6, ref, second;
          assert(alo < ahi && blo < bhi);
          if (bhi - blo < ahi - alo) {
            first = this._dump("+", b5, blo, bhi);
            second = this._dump("-", a5, alo, ahi);
          } else {
            first = this._dump("-", a5, alo, ahi);
            second = this._dump("+", b5, blo, bhi);
          }
          lines = [];
          ref = [first, second];
          for (l5 = 0, len = ref.length; l5 < len; l5++) {
            g5 = ref[l5];
            for (m6 = 0, len1 = g5.length; m6 < len1; m6++) {
              line = g5[m6];
              lines.push(line);
            }
          }
          return lines;
        }
        _fancyReplace(a5, alo, ahi, b5, blo, bhi) {
          var aelt, ai, ai1, ai2, atags, belt, bestRatio, besti, bestj, bj, bj1, bj2, btags, cruncher, cutoff, eqi, eqj, i6, j5, l5, la, lb, len, len1, len2, len3, len4, line, lines, m6, o5, p5, q5, r6, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, t6, tag;
          [bestRatio, cutoff] = [0.74, 0.75];
          cruncher = new SequenceMatcher(this.charjunk);
          [eqi, eqj] = [
            null,
            null
            // 1st indices of equal lines (if any)
          ];
          lines = [];
          for (j5 = l5 = ref = blo, ref1 = bhi; ref <= ref1 ? l5 < ref1 : l5 > ref1; j5 = ref <= ref1 ? ++l5 : --l5) {
            bj = b5[j5];
            cruncher.setSeq2(bj);
            for (i6 = m6 = ref2 = alo, ref3 = ahi; ref2 <= ref3 ? m6 < ref3 : m6 > ref3; i6 = ref2 <= ref3 ? ++m6 : --m6) {
              ai = a5[i6];
              if (ai === bj) {
                if (eqi === null) {
                  [eqi, eqj] = [i6, j5];
                }
                continue;
              }
              cruncher.setSeq1(ai);
              if (cruncher.realQuickRatio() > bestRatio && cruncher.quickRatio() > bestRatio && cruncher.ratio() > bestRatio) {
                [bestRatio, besti, bestj] = [cruncher.ratio(), i6, j5];
              }
            }
          }
          if (bestRatio < cutoff) {
            if (eqi === null) {
              ref4 = this._plainReplace(a5, alo, ahi, b5, blo, bhi);
              for (o5 = 0, len = ref4.length; o5 < len; o5++) {
                line = ref4[o5];
                lines.push(line);
              }
              return lines;
            }
            [besti, bestj, bestRatio] = [eqi, eqj, 1];
          } else {
            eqi = null;
          }
          ref5 = this._fancyHelper(a5, alo, besti, b5, blo, bestj);
          for (p5 = 0, len1 = ref5.length; p5 < len1; p5++) {
            line = ref5[p5];
            lines.push(line);
          }
          [aelt, belt] = [a5[besti], b5[bestj]];
          if (eqi === null) {
            atags = btags = "";
            cruncher.setSeqs(aelt, belt);
            ref6 = cruncher.getOpcodes();
            for (q5 = 0, len2 = ref6.length; q5 < len2; q5++) {
              [tag, ai1, ai2, bj1, bj2] = ref6[q5];
              [la, lb] = [ai2 - ai1, bj2 - bj1];
              switch (tag) {
                case "replace":
                  atags += Array(la + 1).join("^");
                  btags += Array(lb + 1).join("^");
                  break;
                case "delete":
                  atags += Array(la + 1).join("-");
                  break;
                case "insert":
                  btags += Array(lb + 1).join("+");
                  break;
                case "equal":
                  atags += Array(la + 1).join(" ");
                  btags += Array(lb + 1).join(" ");
                  break;
                default:
                  throw new Error(`unknow tag (${tag})`);
              }
            }
            ref7 = this._qformat(aelt, belt, atags, btags);
            for (r6 = 0, len3 = ref7.length; r6 < len3; r6++) {
              line = ref7[r6];
              lines.push(line);
            }
          } else {
            lines.push("  " + aelt);
          }
          ref8 = this._fancyHelper(a5, besti + 1, ahi, b5, bestj + 1, bhi);
          for (t6 = 0, len4 = ref8.length; t6 < len4; t6++) {
            line = ref8[t6];
            lines.push(line);
          }
          return lines;
        }
        _fancyHelper(a5, alo, ahi, b5, blo, bhi) {
          var g5;
          g5 = [];
          if (alo < ahi) {
            if (blo < bhi) {
              g5 = this._fancyReplace(a5, alo, ahi, b5, blo, bhi);
            } else {
              g5 = this._dump("-", a5, alo, ahi);
            }
          } else if (blo < bhi) {
            g5 = this._dump("+", b5, blo, bhi);
          }
          return g5;
        }
        _qformat(aline, bline, atags, btags) {
          var common, lines;
          lines = [];
          common = min(_countLeading(aline, "	"), _countLeading(bline, "	"));
          common = min(common, _countLeading(atags.slice(0, common), " "));
          common = min(common, _countLeading(btags.slice(0, common), " "));
          atags = atags.slice(common).replace(/\s+$/, "");
          btags = btags.slice(common).replace(/\s+$/, "");
          lines.push("- " + aline);
          if (atags.length) {
            lines.push(`? ${Array(common + 1).join("	")}${atags}
`);
          }
          lines.push("+ " + bline);
          if (btags.length) {
            lines.push(`? ${Array(common + 1).join("	")}${btags}
`);
          }
          return lines;
        }
      };
      IS_LINE_JUNK = function(line, pat = /^\s*#?\s*$/) {
        return pat.test(line);
      };
      IS_CHARACTER_JUNK = function(ch, ws = " 	") {
        return indexOf.call(ws, ch) >= 0;
      };
      _formatRangeUnified = function(start, stop) {
        var beginning, length;
        beginning = start + 1;
        length = stop - start;
        if (length === 1) {
          return `${beginning}`;
        }
        if (!length) {
          beginning--;
        }
        return `${beginning},${length}`;
      };
      unifiedDiff = function(a5, b5, { fromfile, tofile, fromfiledate, tofiledate, n: n5, lineterm } = {}) {
        var file1Range, file2Range, first, fromdate, group, i1, i22, j1, j22, l5, last, len, len1, len2, len3, len4, line, lines, m6, o5, p5, q5, ref, ref1, ref2, ref3, started, tag, todate;
        if (fromfile == null) {
          fromfile = "";
        }
        if (tofile == null) {
          tofile = "";
        }
        if (fromfiledate == null) {
          fromfiledate = "";
        }
        if (tofiledate == null) {
          tofiledate = "";
        }
        if (n5 == null) {
          n5 = 3;
        }
        if (lineterm == null) {
          lineterm = "\n";
        }
        lines = [];
        started = false;
        ref = new SequenceMatcher(null, a5, b5).getGroupedOpcodes();
        for (l5 = 0, len = ref.length; l5 < len; l5++) {
          group = ref[l5];
          if (!started) {
            started = true;
            fromdate = fromfiledate ? `	${fromfiledate}` : "";
            todate = tofiledate ? `	${tofiledate}` : "";
            lines.push(`--- ${fromfile}${fromdate}${lineterm}`);
            lines.push(`+++ ${tofile}${todate}${lineterm}`);
          }
          [first, last] = [group[0], group[group.length - 1]];
          file1Range = _formatRangeUnified(first[1], last[2]);
          file2Range = _formatRangeUnified(first[3], last[4]);
          lines.push(`@@ -${file1Range} +${file2Range} @@${lineterm}`);
          for (m6 = 0, len1 = group.length; m6 < len1; m6++) {
            [tag, i1, i22, j1, j22] = group[m6];
            if (tag === "equal") {
              ref1 = a5.slice(i1, i22);
              for (o5 = 0, len2 = ref1.length; o5 < len2; o5++) {
                line = ref1[o5];
                lines.push(" " + line);
              }
              continue;
            }
            if (tag === "replace" || tag === "delete") {
              ref2 = a5.slice(i1, i22);
              for (p5 = 0, len3 = ref2.length; p5 < len3; p5++) {
                line = ref2[p5];
                lines.push("-" + line);
              }
            }
            if (tag === "replace" || tag === "insert") {
              ref3 = b5.slice(j1, j22);
              for (q5 = 0, len4 = ref3.length; q5 < len4; q5++) {
                line = ref3[q5];
                lines.push("+" + line);
              }
            }
          }
        }
        return lines;
      };
      _formatRangeContext = function(start, stop) {
        var beginning, length;
        beginning = start + 1;
        length = stop - start;
        if (!length) {
          beginning--;
        }
        if (length <= 1) {
          return `${beginning}`;
        }
        return `${beginning},${beginning + length - 1}`;
      };
      contextDiff = function(a5, b5, { fromfile, tofile, fromfiledate, tofiledate, n: n5, lineterm } = {}) {
        var _3, file1Range, file2Range, first, fromdate, group, i1, i22, j1, j22, l5, last, len, len1, len2, len3, len4, line, lines, m6, o5, p5, prefix2, q5, ref, ref1, ref2, started, tag, todate;
        if (fromfile == null) {
          fromfile = "";
        }
        if (tofile == null) {
          tofile = "";
        }
        if (fromfiledate == null) {
          fromfiledate = "";
        }
        if (tofiledate == null) {
          tofiledate = "";
        }
        if (n5 == null) {
          n5 = 3;
        }
        if (lineterm == null) {
          lineterm = "\n";
        }
        prefix2 = {
          insert: "+ ",
          delete: "- ",
          replace: "! ",
          equal: "  "
        };
        started = false;
        lines = [];
        ref = new SequenceMatcher(null, a5, b5).getGroupedOpcodes();
        for (l5 = 0, len = ref.length; l5 < len; l5++) {
          group = ref[l5];
          if (!started) {
            started = true;
            fromdate = fromfiledate ? `	${fromfiledate}` : "";
            todate = tofiledate ? `	${tofiledate}` : "";
            lines.push(`*** ${fromfile}${fromdate}${lineterm}`);
            lines.push(`--- ${tofile}${todate}${lineterm}`);
            [first, last] = [group[0], group[group.length - 1]];
            lines.push("***************" + lineterm);
            file1Range = _formatRangeContext(first[1], last[2]);
            lines.push(`*** ${file1Range} ****${lineterm}`);
            if (_any(function() {
              var len12, m7, results;
              results = [];
              for (m7 = 0, len12 = group.length; m7 < len12; m7++) {
                [tag, _3, _3, _3, _3] = group[m7];
                results.push(tag === "replace" || tag === "delete");
              }
              return results;
            }())) {
              for (m6 = 0, len1 = group.length; m6 < len1; m6++) {
                [tag, i1, i22, _3, _3] = group[m6];
                if (tag !== "insert") {
                  ref1 = a5.slice(i1, i22);
                  for (o5 = 0, len2 = ref1.length; o5 < len2; o5++) {
                    line = ref1[o5];
                    lines.push(prefix2[tag] + line);
                  }
                }
              }
            }
            file2Range = _formatRangeContext(first[3], last[4]);
            lines.push(`--- ${file2Range} ----${lineterm}`);
            if (_any(function() {
              var len32, p6, results;
              results = [];
              for (p6 = 0, len32 = group.length; p6 < len32; p6++) {
                [tag, _3, _3, _3, _3] = group[p6];
                results.push(tag === "replace" || tag === "insert");
              }
              return results;
            }())) {
              for (p5 = 0, len3 = group.length; p5 < len3; p5++) {
                [tag, _3, _3, j1, j22] = group[p5];
                if (tag !== "delete") {
                  ref2 = b5.slice(j1, j22);
                  for (q5 = 0, len4 = ref2.length; q5 < len4; q5++) {
                    line = ref2[q5];
                    lines.push(prefix2[tag] + line);
                  }
                }
              }
            }
          }
        }
        return lines;
      };
      ndiff = function(a5, b5, linejunk, charjunk = IS_CHARACTER_JUNK) {
        return new Differ(linejunk, charjunk).compare(a5, b5);
      };
      restore = function(delta, which) {
        var l5, len, line, lines, prefixes2, ref, tag;
        tag = {
          1: "- ",
          2: "+ "
        }[which];
        if (!tag) {
          throw new Error(`unknow delta choice (must be 1 or 2): ${which}`);
        }
        prefixes2 = ["  ", tag];
        lines = [];
        for (l5 = 0, len = delta.length; l5 < len; l5++) {
          line = delta[l5];
          if (ref = line.slice(0, 2), indexOf.call(prefixes2, ref) >= 0) {
            lines.push(line.slice(2));
          }
        }
        return lines;
      };
      exports2._arrayCmp = _arrayCmp;
      exports2.SequenceMatcher = SequenceMatcher;
      exports2.getCloseMatches = getCloseMatches;
      exports2._countLeading = _countLeading;
      exports2.Differ = Differ;
      exports2.IS_LINE_JUNK = IS_LINE_JUNK;
      exports2.IS_CHARACTER_JUNK = IS_CHARACTER_JUNK;
      exports2._formatRangeUnified = _formatRangeUnified;
      exports2.unifiedDiff = unifiedDiff;
      exports2._formatRangeContext = _formatRangeContext;
      exports2.contextDiff = contextDiff;
      exports2.ndiff = ndiff;
      exports2.restore = restore;
    }).call(exports2);
  }
});

// ../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/index.js
var require_difflib2 = __commonJS({
  "../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/index.js"(exports2, module2) {
    "use strict";
    module2.exports = require_difflib();
  }
});

// ../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/util.js
var require_util = __commonJS({
  "../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/util.js"(exports2, module2) {
    "use strict";
    var extendedTypeOf = function(obj) {
      const result = typeof obj;
      if (obj == null) {
        return "null";
      } else if (result === "object" && obj.constructor === Array) {
        return "array";
      } else if (result === "object" && obj instanceof Date) {
        return "date";
      } else {
        return result;
      }
    };
    var roundObj = function(data, precision) {
      const type = typeof data;
      if (type === "array") {
        return data.map((x5) => roundObj(x5, precision));
      } else if (type === "object") {
        for (const key in data) {
          data[key] = roundObj(data[key], precision);
        }
        return data;
      } else if (type === "number" && Number.isFinite(data) && !Number.isInteger(data)) {
        return +data.toFixed(precision);
      } else {
        return data;
      }
    };
    module2.exports = { extendedTypeOf, roundObj };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/styles.js
var require_styles = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/styles.js"(exports2, module2) {
    "use strict";
    var styles3 = {};
    module2["exports"] = styles3;
    var codes = {
      reset: [0, 0],
      bold: [1, 22],
      dim: [2, 22],
      italic: [3, 23],
      underline: [4, 24],
      inverse: [7, 27],
      hidden: [8, 28],
      strikethrough: [9, 29],
      black: [30, 39],
      red: [31, 39],
      green: [32, 39],
      yellow: [33, 39],
      blue: [34, 39],
      magenta: [35, 39],
      cyan: [36, 39],
      white: [37, 39],
      gray: [90, 39],
      grey: [90, 39],
      brightRed: [91, 39],
      brightGreen: [92, 39],
      brightYellow: [93, 39],
      brightBlue: [94, 39],
      brightMagenta: [95, 39],
      brightCyan: [96, 39],
      brightWhite: [97, 39],
      bgBlack: [40, 49],
      bgRed: [41, 49],
      bgGreen: [42, 49],
      bgYellow: [43, 49],
      bgBlue: [44, 49],
      bgMagenta: [45, 49],
      bgCyan: [46, 49],
      bgWhite: [47, 49],
      bgGray: [100, 49],
      bgGrey: [100, 49],
      bgBrightRed: [101, 49],
      bgBrightGreen: [102, 49],
      bgBrightYellow: [103, 49],
      bgBrightBlue: [104, 49],
      bgBrightMagenta: [105, 49],
      bgBrightCyan: [106, 49],
      bgBrightWhite: [107, 49],
      // legacy styles for colors pre v1.0.0
      blackBG: [40, 49],
      redBG: [41, 49],
      greenBG: [42, 49],
      yellowBG: [43, 49],
      blueBG: [44, 49],
      magentaBG: [45, 49],
      cyanBG: [46, 49],
      whiteBG: [47, 49]
    };
    Object.keys(codes).forEach(function(key) {
      var val2 = codes[key];
      var style = styles3[key] = [];
      style.open = "\x1B[" + val2[0] + "m";
      style.close = "\x1B[" + val2[1] + "m";
    });
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/has-flag.js
var require_has_flag = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/has-flag.js"(exports2, module2) {
    "use strict";
    module2.exports = function(flag, argv) {
      argv = argv || process.argv;
      var terminatorPos = argv.indexOf("--");
      var prefix2 = /^-{1,2}/.test(flag) ? "" : "--";
      var pos = argv.indexOf(prefix2 + flag);
      return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/supports-colors.js
var require_supports_colors = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/supports-colors.js"(exports2, module2) {
    "use strict";
    var os3 = require("os");
    var hasFlag2 = require_has_flag();
    var env4 = process.env;
    var forceColor = void 0;
    if (hasFlag2("no-color") || hasFlag2("no-colors") || hasFlag2("color=false")) {
      forceColor = false;
    } else if (hasFlag2("color") || hasFlag2("colors") || hasFlag2("color=true") || hasFlag2("color=always")) {
      forceColor = true;
    }
    if ("FORCE_COLOR" in env4) {
      forceColor = env4.FORCE_COLOR.length === 0 || parseInt(env4.FORCE_COLOR, 10) !== 0;
    }
    function translateLevel2(level) {
      if (level === 0) {
        return false;
      }
      return {
        level,
        hasBasic: true,
        has256: level >= 2,
        has16m: level >= 3
      };
    }
    function supportsColor2(stream) {
      if (forceColor === false) {
        return 0;
      }
      if (hasFlag2("color=16m") || hasFlag2("color=full") || hasFlag2("color=truecolor")) {
        return 3;
      }
      if (hasFlag2("color=256")) {
        return 2;
      }
      if (stream && !stream.isTTY && forceColor !== true) {
        return 0;
      }
      var min = forceColor ? 1 : 0;
      if (process.platform === "win32") {
        var osRelease = os3.release().split(".");
        if (Number(process.versions.node.split(".")[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
          return Number(osRelease[2]) >= 14931 ? 3 : 2;
        }
        return 1;
      }
      if ("CI" in env4) {
        if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].some(function(sign) {
          return sign in env4;
        }) || env4.CI_NAME === "codeship") {
          return 1;
        }
        return min;
      }
      if ("TEAMCITY_VERSION" in env4) {
        return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env4.TEAMCITY_VERSION) ? 1 : 0;
      }
      if ("TERM_PROGRAM" in env4) {
        var version = parseInt((env4.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
        switch (env4.TERM_PROGRAM) {
          case "iTerm.app":
            return version >= 3 ? 3 : 2;
          case "Hyper":
            return 3;
          case "Apple_Terminal":
            return 2;
        }
      }
      if (/-256(color)?$/i.test(env4.TERM)) {
        return 2;
      }
      if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env4.TERM)) {
        return 1;
      }
      if ("COLORTERM" in env4) {
        return 1;
      }
      if (env4.TERM === "dumb") {
        return min;
      }
      return min;
    }
    function getSupportLevel(stream) {
      var level = supportsColor2(stream);
      return translateLevel2(level);
    }
    module2.exports = {
      supportsColor: getSupportLevel,
      stdout: getSupportLevel(process.stdout),
      stderr: getSupportLevel(process.stderr)
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/trap.js
var require_trap = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/trap.js"(exports2, module2) {
    "use strict";
    module2["exports"] = function runTheTrap(text, options) {
      var result = "";
      text = text || "Run the trap, drop the bass";
      text = text.split("");
      var trap = {
        a: ["@", "\u0104", "\u023A", "\u0245", "\u0394", "\u039B", "\u0414"],
        b: ["\xDF", "\u0181", "\u0243", "\u026E", "\u03B2", "\u0E3F"],
        c: ["\xA9", "\u023B", "\u03FE"],
        d: ["\xD0", "\u018A", "\u0500", "\u0501", "\u0502", "\u0503"],
        e: [
          "\xCB",
          "\u0115",
          "\u018E",
          "\u0258",
          "\u03A3",
          "\u03BE",
          "\u04BC",
          "\u0A6C"
        ],
        f: ["\u04FA"],
        g: ["\u0262"],
        h: ["\u0126", "\u0195", "\u04A2", "\u04BA", "\u04C7", "\u050A"],
        i: ["\u0F0F"],
        j: ["\u0134"],
        k: ["\u0138", "\u04A0", "\u04C3", "\u051E"],
        l: ["\u0139"],
        m: ["\u028D", "\u04CD", "\u04CE", "\u0520", "\u0521", "\u0D69"],
        n: ["\xD1", "\u014B", "\u019D", "\u0376", "\u03A0", "\u048A"],
        o: [
          "\xD8",
          "\xF5",
          "\xF8",
          "\u01FE",
          "\u0298",
          "\u047A",
          "\u05DD",
          "\u06DD",
          "\u0E4F"
        ],
        p: ["\u01F7", "\u048E"],
        q: ["\u09CD"],
        r: ["\xAE", "\u01A6", "\u0210", "\u024C", "\u0280", "\u042F"],
        s: ["\xA7", "\u03DE", "\u03DF", "\u03E8"],
        t: ["\u0141", "\u0166", "\u0373"],
        u: ["\u01B1", "\u054D"],
        v: ["\u05D8"],
        w: ["\u0428", "\u0460", "\u047C", "\u0D70"],
        x: ["\u04B2", "\u04FE", "\u04FC", "\u04FD"],
        y: ["\xA5", "\u04B0", "\u04CB"],
        z: ["\u01B5", "\u0240"]
      };
      text.forEach(function(c5) {
        c5 = c5.toLowerCase();
        var chars = trap[c5] || [" "];
        var rand = Math.floor(Math.random() * chars.length);
        if (typeof trap[c5] !== "undefined") {
          result += trap[c5][rand];
        } else {
          result += c5;
        }
      });
      return result;
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/zalgo.js
var require_zalgo = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/zalgo.js"(exports2, module2) {
    "use strict";
    module2["exports"] = function zalgo(text, options) {
      text = text || "   he is here   ";
      var soul = {
        "up": [
          "\u030D",
          "\u030E",
          "\u0304",
          "\u0305",
          "\u033F",
          "\u0311",
          "\u0306",
          "\u0310",
          "\u0352",
          "\u0357",
          "\u0351",
          "\u0307",
          "\u0308",
          "\u030A",
          "\u0342",
          "\u0313",
          "\u0308",
          "\u034A",
          "\u034B",
          "\u034C",
          "\u0303",
          "\u0302",
          "\u030C",
          "\u0350",
          "\u0300",
          "\u0301",
          "\u030B",
          "\u030F",
          "\u0312",
          "\u0313",
          "\u0314",
          "\u033D",
          "\u0309",
          "\u0363",
          "\u0364",
          "\u0365",
          "\u0366",
          "\u0367",
          "\u0368",
          "\u0369",
          "\u036A",
          "\u036B",
          "\u036C",
          "\u036D",
          "\u036E",
          "\u036F",
          "\u033E",
          "\u035B",
          "\u0346",
          "\u031A"
        ],
        "down": [
          "\u0316",
          "\u0317",
          "\u0318",
          "\u0319",
          "\u031C",
          "\u031D",
          "\u031E",
          "\u031F",
          "\u0320",
          "\u0324",
          "\u0325",
          "\u0326",
          "\u0329",
          "\u032A",
          "\u032B",
          "\u032C",
          "\u032D",
          "\u032E",
          "\u032F",
          "\u0330",
          "\u0331",
          "\u0332",
          "\u0333",
          "\u0339",
          "\u033A",
          "\u033B",
          "\u033C",
          "\u0345",
          "\u0347",
          "\u0348",
          "\u0349",
          "\u034D",
          "\u034E",
          "\u0353",
          "\u0354",
          "\u0355",
          "\u0356",
          "\u0359",
          "\u035A",
          "\u0323"
        ],
        "mid": [
          "\u0315",
          "\u031B",
          "\u0300",
          "\u0301",
          "\u0358",
          "\u0321",
          "\u0322",
          "\u0327",
          "\u0328",
          "\u0334",
          "\u0335",
          "\u0336",
          "\u035C",
          "\u035D",
          "\u035E",
          "\u035F",
          "\u0360",
          "\u0362",
          "\u0338",
          "\u0337",
          "\u0361",
          " \u0489"
        ]
      };
      var all = [].concat(soul.up, soul.down, soul.mid);
      function randomNumber(range) {
        var r6 = Math.floor(Math.random() * range);
        return r6;
      }
      function isChar(character) {
        var bool = false;
        all.filter(function(i6) {
          bool = i6 === character;
        });
        return bool;
      }
      function heComes(text2, options2) {
        var result = "";
        var counts;
        var l5;
        options2 = options2 || {};
        options2["up"] = typeof options2["up"] !== "undefined" ? options2["up"] : true;
        options2["mid"] = typeof options2["mid"] !== "undefined" ? options2["mid"] : true;
        options2["down"] = typeof options2["down"] !== "undefined" ? options2["down"] : true;
        options2["size"] = typeof options2["size"] !== "undefined" ? options2["size"] : "maxi";
        text2 = text2.split("");
        for (l5 in text2) {
          if (isChar(l5)) {
            continue;
          }
          result = result + text2[l5];
          counts = { "up": 0, "down": 0, "mid": 0 };
          switch (options2.size) {
            case "mini":
              counts.up = randomNumber(8);
              counts.mid = randomNumber(2);
              counts.down = randomNumber(8);
              break;
            case "maxi":
              counts.up = randomNumber(16) + 3;
              counts.mid = randomNumber(4) + 1;
              counts.down = randomNumber(64) + 3;
              break;
            default:
              counts.up = randomNumber(8) + 1;
              counts.mid = randomNumber(6) / 2;
              counts.down = randomNumber(8) + 1;
              break;
          }
          var arr = ["up", "mid", "down"];
          for (var d5 in arr) {
            var index6 = arr[d5];
            for (var i6 = 0; i6 <= counts[index6]; i6++) {
              if (options2[index6]) {
                result = result + soul[index6][randomNumber(soul[index6].length)];
              }
            }
          }
        }
        return result;
      }
      return heComes(text, options);
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/america.js
var require_america = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/america.js"(exports2, module2) {
    "use strict";
    module2["exports"] = function(colors) {
      return function(letter, i6, exploded) {
        if (letter === " ") return letter;
        switch (i6 % 3) {
          case 0:
            return colors.red(letter);
          case 1:
            return colors.white(letter);
          case 2:
            return colors.blue(letter);
        }
      };
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/zebra.js
var require_zebra = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/zebra.js"(exports2, module2) {
    "use strict";
    module2["exports"] = function(colors) {
      return function(letter, i6, exploded) {
        return i6 % 2 === 0 ? letter : colors.inverse(letter);
      };
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/rainbow.js
var require_rainbow = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/rainbow.js"(exports2, module2) {
    "use strict";
    module2["exports"] = function(colors) {
      var rainbowColors = ["red", "yellow", "green", "blue", "magenta"];
      return function(letter, i6, exploded) {
        if (letter === " ") {
          return letter;
        } else {
          return colors[rainbowColors[i6++ % rainbowColors.length]](letter);
        }
      };
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/random.js
var require_random = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/random.js"(exports2, module2) {
    "use strict";
    module2["exports"] = function(colors) {
      var available = [
        "underline",
        "inverse",
        "grey",
        "yellow",
        "red",
        "green",
        "blue",
        "white",
        "cyan",
        "magenta",
        "brightYellow",
        "brightRed",
        "brightGreen",
        "brightBlue",
        "brightWhite",
        "brightCyan",
        "brightMagenta"
      ];
      return function(letter, i6, exploded) {
        return letter === " " ? letter : colors[available[Math.round(Math.random() * (available.length - 2))]](letter);
      };
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/colors.js
var require_colors = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/colors.js"(exports2, module2) {
    "use strict";
    var colors = {};
    module2["exports"] = colors;
    colors.themes = {};
    var util2 = require("util");
    var ansiStyles2 = colors.styles = require_styles();
    var defineProps = Object.defineProperties;
    var newLineRegex = new RegExp(/[\r\n]+/g);
    colors.supportsColor = require_supports_colors().supportsColor;
    if (typeof colors.enabled === "undefined") {
      colors.enabled = colors.supportsColor() !== false;
    }
    colors.enable = function() {
      colors.enabled = true;
    };
    colors.disable = function() {
      colors.enabled = false;
    };
    colors.stripColors = colors.strip = function(str) {
      return ("" + str).replace(/\x1B\[\d+m/g, "");
    };
    var stylize = colors.stylize = function stylize2(str, style) {
      if (!colors.enabled) {
        return str + "";
      }
      var styleMap = ansiStyles2[style];
      if (!styleMap && style in colors) {
        return colors[style](str);
      }
      return styleMap.open + str + styleMap.close;
    };
    var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
    var escapeStringRegexp = function(str) {
      if (typeof str !== "string") {
        throw new TypeError("Expected a string");
      }
      return str.replace(matchOperatorsRe, "\\$&");
    };
    function build(_styles) {
      var builder = function builder2() {
        return applyStyle2.apply(builder2, arguments);
      };
      builder._styles = _styles;
      builder.__proto__ = proto2;
      return builder;
    }
    var styles3 = function() {
      var ret = {};
      ansiStyles2.grey = ansiStyles2.gray;
      Object.keys(ansiStyles2).forEach(function(key) {
        ansiStyles2[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles2[key].close), "g");
        ret[key] = {
          get: function() {
            return build(this._styles.concat(key));
          }
        };
      });
      return ret;
    }();
    var proto2 = defineProps(function colors2() {
    }, styles3);
    function applyStyle2() {
      var args = Array.prototype.slice.call(arguments);
      var str = args.map(function(arg) {
        if (arg != null && arg.constructor === String) {
          return arg;
        } else {
          return util2.inspect(arg);
        }
      }).join(" ");
      if (!colors.enabled || !str) {
        return str;
      }
      var newLinesPresent = str.indexOf("\n") != -1;
      var nestedStyles = this._styles;
      var i6 = nestedStyles.length;
      while (i6--) {
        var code = ansiStyles2[nestedStyles[i6]];
        str = code.open + str.replace(code.closeRe, code.open) + code.close;
        if (newLinesPresent) {
          str = str.replace(newLineRegex, function(match2) {
            return code.close + match2 + code.open;
          });
        }
      }
      return str;
    }
    colors.setTheme = function(theme) {
      if (typeof theme === "string") {
        console.log("colors.setTheme now only accepts an object, not a string.  If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file.  The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));");
        return;
      }
      for (var style in theme) {
        (function(style2) {
          colors[style2] = function(str) {
            if (typeof theme[style2] === "object") {
              var out = str;
              for (var i6 in theme[style2]) {
                out = colors[theme[style2][i6]](out);
              }
              return out;
            }
            return colors[theme[style2]](str);
          };
        })(style);
      }
    };
    function init2() {
      var ret = {};
      Object.keys(styles3).forEach(function(name) {
        ret[name] = {
          get: function() {
            return build([name]);
          }
        };
      });
      return ret;
    }
    var sequencer = function sequencer2(map3, str) {
      var exploded = str.split("");
      exploded = exploded.map(map3);
      return exploded.join("");
    };
    colors.trap = require_trap();
    colors.zalgo = require_zalgo();
    colors.maps = {};
    colors.maps.america = require_america()(colors);
    colors.maps.zebra = require_zebra()(colors);
    colors.maps.rainbow = require_rainbow()(colors);
    colors.maps.random = require_random()(colors);
    for (map2 in colors.maps) {
      (function(map3) {
        colors[map3] = function(str) {
          return sequencer(colors.maps[map3], str);
        };
      })(map2);
    }
    var map2;
    defineProps(colors, init2());
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/safe.js
var require_safe = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/safe.js"(exports2, module2) {
    "use strict";
    var colors = require_colors();
    module2["exports"] = colors;
  }
});

// ../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/colorize.js
var require_colorize = __commonJS({
  "../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/colorize.js"(exports2, module2) {
    "use strict";
    var color = require_safe();
    var { extendedTypeOf } = require_util();
    var Theme = {
      " "(s6) {
        return s6;
      },
      "+": color.green,
      "-": color.red
    };
    var subcolorizeToCallback = function(options, key, diff2, output, color2, indent) {
      let subvalue;
      const prefix2 = key ? `${key}: ` : "";
      const subindent = indent + "  ";
      const outputElisions = (n5) => {
        const maxElisions = options.maxElisions === void 0 ? Infinity : options.maxElisions;
        if (n5 < maxElisions) {
          for (let i6 = 0; i6 < n5; i6++) {
            output(" ", subindent + "...");
          }
        } else {
          output(" ", subindent + `... (${n5} entries)`);
        }
      };
      switch (extendedTypeOf(diff2)) {
        case "object":
          if ("__old" in diff2 && "__new" in diff2 && Object.keys(diff2).length === 2) {
            subcolorizeToCallback(options, key, diff2.__old, output, "-", indent);
            return subcolorizeToCallback(options, key, diff2.__new, output, "+", indent);
          } else {
            output(color2, `${indent}${prefix2}{`);
            for (const subkey of Object.keys(diff2)) {
              let m6;
              subvalue = diff2[subkey];
              if (m6 = subkey.match(/^(.*)__deleted$/)) {
                subcolorizeToCallback(options, m6[1], subvalue, output, "-", subindent);
              } else if (m6 = subkey.match(/^(.*)__added$/)) {
                subcolorizeToCallback(options, m6[1], subvalue, output, "+", subindent);
              } else {
                subcolorizeToCallback(options, subkey, subvalue, output, color2, subindent);
              }
            }
            return output(color2, `${indent}}`);
          }
        case "array": {
          output(color2, `${indent}${prefix2}[`);
          let looksLikeDiff = true;
          for (const item of diff2) {
            if (extendedTypeOf(item) !== "array" || !(item.length === 2 || item.length === 1 && item[0] === " ") || !(typeof item[0] === "string") || item[0].length !== 1 || ![" ", "-", "+", "~"].includes(item[0])) {
              looksLikeDiff = false;
            }
          }
          if (looksLikeDiff) {
            let op;
            let elisionCount = 0;
            for ([op, subvalue] of diff2) {
              if (op === " " && subvalue == null) {
                elisionCount++;
              } else {
                if (elisionCount > 0) {
                  outputElisions(elisionCount);
                }
                elisionCount = 0;
                if (![" ", "~", "+", "-"].includes(op)) {
                  throw new Error(`Unexpected op '${op}' in ${JSON.stringify(diff2, null, 2)}`);
                }
                if (op === "~") {
                  op = " ";
                }
                subcolorizeToCallback(options, "", subvalue, output, op, subindent);
              }
            }
            if (elisionCount > 0) {
              outputElisions(elisionCount);
            }
          } else {
            for (subvalue of diff2) {
              subcolorizeToCallback(options, "", subvalue, output, color2, subindent);
            }
          }
          return output(color2, `${indent}]`);
        }
        default:
          if (diff2 === 0 || diff2 === null || diff2 === false || diff2 === "" || diff2) {
            return output(color2, indent + prefix2 + JSON.stringify(diff2));
          }
      }
    };
    var colorizeToCallback = (diff2, options, output) => subcolorizeToCallback(options, "", diff2, output, " ", "");
    var colorizeToArray = function(diff2, options = {}) {
      const output = [];
      colorizeToCallback(diff2, options, (color2, line) => output.push(`${color2}${line}`));
      return output;
    };
    var colorize = function(diff2, options = {}) {
      const output = [];
      colorizeToCallback(diff2, options, function(color2, line) {
        if (options.color != null ? options.color : true) {
          return output.push(((options.theme != null ? options.theme[color2] : void 0) != null ? options.theme != null ? options.theme[color2] : void 0 : Theme[color2])(`${color2}${line}`) + "\n");
        } else {
          return output.push(`${color2}${line}
`);
        }
      });
      return output.join("");
    };
    module2.exports = { colorize, colorizeToArray, colorizeToCallback };
  }
});

// ../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/index.js
var require_lib = __commonJS({
  "../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/index.js"(exports2, module2) {
    "use strict";
    var { SequenceMatcher } = require_difflib2();
    var { extendedTypeOf, roundObj } = require_util();
    var { colorize, colorizeToCallback } = require_colorize();
    var JsonDiff = class {
      constructor(options) {
        options.outputKeys = options.outputKeys || [];
        options.excludeKeys = options.excludeKeys || [];
        this.options = options;
      }
      isScalar(obj) {
        return typeof obj !== "object" || obj === null;
      }
      objectDiff(obj1, obj2) {
        let result = {};
        let score = 0;
        let equal = true;
        for (const [key, value] of Object.entries(obj1)) {
          if (!this.options.outputNewOnly) {
            const postfix = "__deleted";
            if (!(key in obj2) && !this.options.excludeKeys.includes(key)) {
              result[`${key}${postfix}`] = value;
              score -= 30;
              equal = false;
            }
          }
        }
        for (const [key, value] of Object.entries(obj2)) {
          const postfix = !this.options.outputNewOnly ? "__added" : "";
          if (!(key in obj1) && !this.options.excludeKeys.includes(key)) {
            result[`${key}${postfix}`] = value;
            score -= 30;
            equal = false;
          }
        }
        for (const [key, value1] of Object.entries(obj1)) {
          if (key in obj2) {
            if (this.options.excludeKeys.includes(key)) {
              continue;
            }
            score += 20;
            const value2 = obj2[key];
            const change = this.diff(value1, value2);
            if (!change.equal) {
              result[key] = change.result;
              equal = false;
            } else if (this.options.full || this.options.outputKeys.includes(key)) {
              result[key] = value1;
            }
            score += Math.min(20, Math.max(-10, change.score / 5));
          }
        }
        if (equal) {
          score = 100 * Math.max(Object.keys(obj1).length, 0.5);
          if (!this.options.full) {
            result = void 0;
          }
        } else {
          score = Math.max(0, score);
        }
        return { score, result, equal };
      }
      findMatchingObject(item, index6, fuzzyOriginals) {
        let bestMatch = null;
        for (const [key, { item: candidate, index: matchIndex }] of Object.entries(fuzzyOriginals)) {
          if (key !== "__next") {
            const indexDistance = Math.abs(matchIndex - index6);
            if (extendedTypeOf(item) === extendedTypeOf(candidate)) {
              const { score } = this.diff(item, candidate);
              if (!bestMatch || score > bestMatch.score || score === bestMatch.score && indexDistance < bestMatch.indexDistance) {
                bestMatch = { score, key, indexDistance };
              }
            }
          }
        }
        return bestMatch;
      }
      scalarize(array2, originals, fuzzyOriginals) {
        const fuzzyMatches = [];
        if (fuzzyOriginals) {
          const keyScores = {};
          for (let index6 = 0; index6 < array2.length; index6++) {
            const item = array2[index6];
            if (this.isScalar(item)) {
              continue;
            }
            const bestMatch = this.findMatchingObject(item, index6, fuzzyOriginals);
            if (bestMatch && (!keyScores[bestMatch.key] || bestMatch.score > keyScores[bestMatch.key].score)) {
              keyScores[bestMatch.key] = { score: bestMatch.score, index: index6 };
            }
          }
          for (const [key, match2] of Object.entries(keyScores)) {
            fuzzyMatches[match2.index] = key;
          }
        }
        const result = [];
        for (let index6 = 0; index6 < array2.length; index6++) {
          const item = array2[index6];
          if (this.isScalar(item)) {
            result.push(item);
          } else {
            const key = fuzzyMatches[index6] || "__$!SCALAR" + originals.__next++;
            originals[key] = { item, index: index6 };
            result.push(key);
          }
        }
        return result;
      }
      isScalarized(item, originals) {
        return typeof item === "string" && item in originals;
      }
      descalarize(item, originals) {
        if (this.isScalarized(item, originals)) {
          return originals[item].item;
        } else {
          return item;
        }
      }
      arrayDiff(obj1, obj2) {
        const originals1 = { __next: 1 };
        const seq1 = this.scalarize(obj1, originals1);
        const originals2 = { __next: originals1.__next };
        const seq2 = this.scalarize(obj2, originals2, originals1);
        if (this.options.sort) {
          seq1.sort();
          seq2.sort();
        }
        const opcodes = new SequenceMatcher(null, seq1, seq2).getOpcodes();
        let result = [];
        let score = 0;
        let equal = true;
        for (const [op, i1, i22, j1, j22] of opcodes) {
          let i6, j5;
          let asc, end;
          let asc1, end1;
          let asc2, end2;
          if (!(op === "equal" || this.options.keysOnly && op === "replace")) {
            equal = false;
          }
          switch (op) {
            case "equal":
              for (i6 = i1, end = i22, asc = i1 <= end; asc ? i6 < end : i6 > end; asc ? i6++ : i6--) {
                const item = seq1[i6];
                if (this.isScalarized(item, originals1)) {
                  if (!this.isScalarized(item, originals2)) {
                    throw new Error(
                      `internal bug: isScalarized(item, originals1) != isScalarized(item, originals2) for item ${JSON.stringify(
                        item
                      )}`
                    );
                  }
                  const item1 = this.descalarize(item, originals1);
                  const item2 = this.descalarize(item, originals2);
                  const change = this.diff(item1, item2);
                  if (!change.equal) {
                    result.push(["~", change.result]);
                    equal = false;
                  } else {
                    if (this.options.full || this.options.keepUnchangedValues) {
                      result.push([" ", item1]);
                    } else {
                      result.push([" "]);
                    }
                  }
                } else {
                  if (this.options.full || this.options.keepUnchangedValues) {
                    result.push([" ", item]);
                  } else {
                    result.push([" "]);
                  }
                }
                score += 10;
              }
              break;
            case "delete":
              for (i6 = i1, end1 = i22, asc1 = i1 <= end1; asc1 ? i6 < end1 : i6 > end1; asc1 ? i6++ : i6--) {
                result.push(["-", this.descalarize(seq1[i6], originals1)]);
                score -= 5;
              }
              break;
            case "insert":
              for (j5 = j1, end2 = j22, asc2 = j1 <= end2; asc2 ? j5 < end2 : j5 > end2; asc2 ? j5++ : j5--) {
                result.push(["+", this.descalarize(seq2[j5], originals2)]);
                score -= 5;
              }
              break;
            case "replace":
              if (!this.options.keysOnly) {
                let asc3, end3;
                let asc4, end4;
                for (i6 = i1, end3 = i22, asc3 = i1 <= end3; asc3 ? i6 < end3 : i6 > end3; asc3 ? i6++ : i6--) {
                  result.push(["-", this.descalarize(seq1[i6], originals1)]);
                  score -= 5;
                }
                for (j5 = j1, end4 = j22, asc4 = j1 <= end4; asc4 ? j5 < end4 : j5 > end4; asc4 ? j5++ : j5--) {
                  result.push(["+", this.descalarize(seq2[j5], originals2)]);
                  score -= 5;
                }
              } else {
                let asc5, end5;
                for (i6 = i1, end5 = i22, asc5 = i1 <= end5; asc5 ? i6 < end5 : i6 > end5; asc5 ? i6++ : i6--) {
                  const change = this.diff(
                    this.descalarize(seq1[i6], originals1),
                    this.descalarize(seq2[i6 - i1 + j1], originals2)
                  );
                  if (!change.equal) {
                    result.push(["~", change.result]);
                    equal = false;
                  } else {
                    result.push([" "]);
                  }
                }
              }
              break;
          }
        }
        if (equal || opcodes.length === 0) {
          if (!this.options.full) {
            result = void 0;
          } else {
            result = obj1;
          }
          score = 100;
        } else {
          score = Math.max(0, score);
        }
        return { score, result, equal };
      }
      diff(obj1, obj2) {
        const type1 = extendedTypeOf(obj1);
        const type2 = extendedTypeOf(obj2);
        if (type1 === type2) {
          switch (type1) {
            case "object":
              return this.objectDiff(obj1, obj2);
            case "array":
              return this.arrayDiff(obj1, obj2);
          }
        }
        let score = 100;
        let result = obj1;
        let equal;
        if (!this.options.keysOnly) {
          if (type1 === "date" && type2 === "date") {
            equal = obj1.getTime() === obj2.getTime();
          } else {
            equal = obj1 === obj2;
          }
          if (!equal) {
            score = 0;
            if (this.options.outputNewOnly) {
              result = obj2;
            } else {
              result = { __old: obj1, __new: obj2 };
            }
          } else if (!this.options.full) {
            result = void 0;
          }
        } else {
          equal = true;
          result = void 0;
        }
        return { score, result, equal };
      }
    };
    function diff2(obj1, obj2, options = {}) {
      if (options.precision !== void 0) {
        obj1 = roundObj(obj1, options.precision);
        obj2 = roundObj(obj2, options.precision);
      }
      return new JsonDiff(options).diff(obj1, obj2).result;
    }
    function diffString(obj1, obj2, options = {}) {
      return colorize(diff2(obj1, obj2, options), options);
    }
    module2.exports = { diff: diff2, diffString, colorize, colorizeToCallback };
  }
});

// src/jsonDiffer.js
function diffSchemasOrTables(left, right) {
  left = JSON.parse(JSON.stringify(left));
  right = JSON.parse(JSON.stringify(right));
  const result = Object.entries((0, import_json_diff.diff)(left, right) ?? {});
  const added = result.filter((it) => it[0].endsWith("__added")).map((it) => it[1]);
  const deleted = result.filter((it) => it[0].endsWith("__deleted")).map((it) => it[1]);
  return { added, deleted };
}
function diffIndPolicies(left, right) {
  left = JSON.parse(JSON.stringify(left));
  right = JSON.parse(JSON.stringify(right));
  const result = Object.entries((0, import_json_diff.diff)(left, right) ?? {});
  const added = result.filter((it) => it[0].endsWith("__added")).map((it) => it[1]);
  const deleted = result.filter((it) => it[0].endsWith("__deleted")).map((it) => it[1]);
  return { added, deleted };
}
function diffColumns(left, right) {
  left = JSON.parse(JSON.stringify(left));
  right = JSON.parse(JSON.stringify(right));
  const result = (0, import_json_diff.diff)(left, right) ?? {};
  const alteredTables = Object.fromEntries(
    Object.entries(result).filter((it) => {
      return !(it[0].includes("__added") || it[0].includes("__deleted"));
    }).map((tableEntry) => {
      const deletedColumns = Object.entries(tableEntry[1].columns ?? {}).filter((it) => {
        return it[0].endsWith("__deleted");
      }).map((it) => {
        return it[1];
      });
      const addedColumns = Object.entries(tableEntry[1].columns ?? {}).filter((it) => {
        return it[0].endsWith("__added");
      }).map((it) => {
        return it[1];
      });
      tableEntry[1].columns = {
        added: addedColumns,
        deleted: deletedColumns
      };
      const table6 = left[tableEntry[0]];
      return [
        tableEntry[0],
        { name: table6.name, schema: table6.schema, ...tableEntry[1] }
      ];
    })
  );
  return alteredTables;
}
function diffPolicies(left, right) {
  left = JSON.parse(JSON.stringify(left));
  right = JSON.parse(JSON.stringify(right));
  const result = (0, import_json_diff.diff)(left, right) ?? {};
  const alteredTables = Object.fromEntries(
    Object.entries(result).filter((it) => {
      return !(it[0].includes("__added") || it[0].includes("__deleted"));
    }).map((tableEntry) => {
      const deletedPolicies = Object.entries(tableEntry[1].policies ?? {}).filter((it) => {
        return it[0].endsWith("__deleted");
      }).map((it) => {
        return it[1];
      });
      const addedPolicies = Object.entries(tableEntry[1].policies ?? {}).filter((it) => {
        return it[0].endsWith("__added");
      }).map((it) => {
        return it[1];
      });
      tableEntry[1].policies = {
        added: addedPolicies,
        deleted: deletedPolicies
      };
      const table6 = left[tableEntry[0]];
      return [
        tableEntry[0],
        { name: table6.name, schema: table6.schema, ...tableEntry[1] }
      ];
    })
  );
  return alteredTables;
}
function applyJsonDiff(json1, json2) {
  json1 = JSON.parse(JSON.stringify(json1));
  json2 = JSON.parse(JSON.stringify(json2));
  const rawDiff = (0, import_json_diff.diff)(json1, json2);
  const difference = JSON.parse(JSON.stringify(rawDiff || {}));
  difference.schemas = difference.schemas || {};
  difference.tables = difference.tables || {};
  difference.enums = difference.enums || {};
  difference.sequences = difference.sequences || {};
  difference.roles = difference.roles || {};
  difference.policies = difference.policies || {};
  difference.views = difference.views || {};
  const schemaKeys = Object.keys(difference.schemas);
  for (let key of schemaKeys) {
    if (key.endsWith("__added") || key.endsWith("__deleted")) {
      delete difference.schemas[key];
      continue;
    }
  }
  const tableKeys = Object.keys(difference.tables);
  for (let key of tableKeys) {
    if (key.endsWith("__added") || key.endsWith("__deleted")) {
      delete difference.tables[key];
      continue;
    }
    const table6 = json1.tables[key];
    difference.tables[key] = {
      name: table6.name,
      schema: table6.schema,
      ...difference.tables[key]
    };
  }
  for (let [tableKey2, tableValue] of Object.entries(difference.tables)) {
    const table6 = difference.tables[tableKey2];
    const columns = tableValue.columns || {};
    const columnKeys = Object.keys(columns);
    for (let key of columnKeys) {
      if (key.endsWith("__added") || key.endsWith("__deleted")) {
        delete table6.columns[key];
        continue;
      }
    }
    if (Object.keys(columns).length === 0) {
      delete table6["columns"];
    }
    if ("name" in table6 && "schema" in table6 && Object.keys(table6).length === 2) {
      delete difference.tables[tableKey2];
    }
  }
  const enumsEntries = Object.entries(difference.enums);
  const alteredEnums = enumsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => {
    const enumEntry = json1.enums[it[0]];
    const { name, schema: schema6, values } = enumEntry;
    const sequence = mapArraysDiff(values, it[1].values);
    const addedValues = sequence.filter((it2) => it2.type === "added").map((it2) => {
      return {
        before: it2.before,
        value: it2.value
      };
    });
    const deletedValues = sequence.filter((it2) => it2.type === "removed").map((it2) => it2.value);
    return { name, schema: schema6, addedValues, deletedValues };
  });
  const sequencesEntries = Object.entries(difference.sequences);
  const alteredSequences = sequencesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted")) && "values" in it[1]).map((it) => {
    return json2.sequences[it[0]];
  });
  const rolesEntries = Object.entries(difference.roles);
  const alteredRoles = rolesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => {
    return json2.roles[it[0]];
  });
  const policiesEntries = Object.entries(difference.policies);
  const alteredPolicies = policiesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => {
    return json2.policies[it[0]];
  });
  const viewsEntries = Object.entries(difference.views);
  const alteredViews = viewsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map(
    ([nameWithSchema, view5]) => {
      const deletedWithOption = view5.with__deleted;
      const addedWithOption = view5.with__added;
      const deletedWith = Object.fromEntries(
        Object.entries(view5.with || {}).filter((it) => it[0].endsWith("__deleted")).map(([key, value]) => {
          return [key.replace("__deleted", ""), value];
        })
      );
      const addedWith = Object.fromEntries(
        Object.entries(view5.with || {}).filter((it) => it[0].endsWith("__added")).map(([key, value]) => {
          return [key.replace("__added", ""), value];
        })
      );
      const alterWith = Object.fromEntries(
        Object.entries(view5.with || {}).filter(
          (it) => typeof it[1].__old !== "undefined" && typeof it[1].__new !== "undefined"
        ).map(
          (it) => {
            return [it[0], it[1].__new];
          }
        )
      );
      const alteredSchema = view5.schema;
      const alteredDefinition = view5.definition;
      const alteredExisting = view5.isExisting;
      const addedTablespace = view5.tablespace__added;
      const droppedTablespace = view5.tablespace__deleted;
      const alterTablespaceTo = view5.tablespace;
      let alteredTablespace;
      if (addedTablespace) alteredTablespace = { __new: addedTablespace, __old: "pg_default" };
      if (droppedTablespace) alteredTablespace = { __new: "pg_default", __old: droppedTablespace };
      if (alterTablespaceTo) alteredTablespace = alterTablespaceTo;
      const addedUsing = view5.using__added;
      const droppedUsing = view5.using__deleted;
      const alterUsingTo = view5.using;
      let alteredUsing;
      if (addedUsing) alteredUsing = { __new: addedUsing, __old: "heap" };
      if (droppedUsing) alteredUsing = { __new: "heap", __old: droppedUsing };
      if (alterUsingTo) alteredUsing = alterUsingTo;
      const alteredMeta = view5.meta;
      return Object.fromEntries(
        Object.entries({
          name: json2.views[nameWithSchema].name,
          schema: json2.views[nameWithSchema].schema,
          // pg
          deletedWithOption,
          addedWithOption,
          deletedWith: Object.keys(deletedWith).length ? deletedWith : void 0,
          addedWith: Object.keys(addedWith).length ? addedWith : void 0,
          alteredWith: Object.keys(alterWith).length ? alterWith : void 0,
          alteredSchema,
          alteredTablespace,
          alteredUsing,
          // mysql
          alteredMeta,
          // common
          alteredDefinition,
          alteredExisting
        }).filter(([_3, value]) => value !== void 0)
      );
    }
  );
  const alteredTablesWithColumns = Object.values(difference.tables).map(
    (table6) => {
      return findAlternationsInTable(table6);
    }
  );
  return {
    alteredTablesWithColumns,
    alteredEnums,
    alteredSequences,
    alteredRoles,
    alteredViews,
    alteredPolicies
  };
}
var import_json_diff, mapArraysDiff, findAlternationsInTable, alternationsInColumn;
var init_jsonDiffer = __esm({
  "src/jsonDiffer.js"() {
    "use strict";
    "use-strict";
    import_json_diff = __toESM(require_lib());
    mapArraysDiff = (source, diff2) => {
      const sequence = [];
      let sourceIndex = 0;
      for (let i6 = 0; i6 < diff2.length; i6++) {
        const it = diff2[i6];
        if (it.length === 1) {
          sequence.push({ type: "same", value: source[sourceIndex] });
          sourceIndex += 1;
        } else {
          if (it[0] === "-") {
            sequence.push({ type: "removed", value: it[1] });
          } else {
            sequence.push({ type: "added", value: it[1], before: "" });
          }
        }
      }
      const result = sequence.reverse().reduce(
        (acc, it) => {
          if (it.type === "same") {
            acc.prev = it.value;
          }
          if (it.type === "added" && acc.prev) {
            it.before = acc.prev;
          }
          acc.result.push(it);
          return acc;
        },
        { result: [] }
      );
      return result.result.reverse();
    };
    findAlternationsInTable = (table6) => {
      const columns = table6.columns ?? {};
      const altered = Object.keys(columns).filter((it) => !(it.includes("__deleted") || it.includes("__added"))).map((it) => {
        return { name: it, ...columns[it] };
      });
      const deletedIndexes = Object.fromEntries(
        Object.entries(table6.indexes__deleted || {}).concat(
          Object.entries(table6.indexes || {}).filter((it) => it[0].includes("__deleted"))
        ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
      );
      const addedIndexes = Object.fromEntries(
        Object.entries(table6.indexes__added || {}).concat(
          Object.entries(table6.indexes || {}).filter((it) => it[0].includes("__added"))
        ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
      );
      const alteredIndexes = Object.fromEntries(
        Object.entries(table6.indexes || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const deletedPolicies = Object.fromEntries(
        Object.entries(table6.policies__deleted || {}).concat(
          Object.entries(table6.policies || {}).filter((it) => it[0].includes("__deleted"))
        ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
      );
      const addedPolicies = Object.fromEntries(
        Object.entries(table6.policies__added || {}).concat(
          Object.entries(table6.policies || {}).filter((it) => it[0].includes("__added"))
        ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
      );
      const alteredPolicies = Object.fromEntries(
        Object.entries(table6.policies || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const deletedForeignKeys = Object.fromEntries(
        Object.entries(table6.foreignKeys__deleted || {}).concat(
          Object.entries(table6.foreignKeys || {}).filter((it) => it[0].includes("__deleted"))
        ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
      );
      const addedForeignKeys = Object.fromEntries(
        Object.entries(table6.foreignKeys__added || {}).concat(
          Object.entries(table6.foreignKeys || {}).filter((it) => it[0].includes("__added"))
        ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
      );
      const alteredForeignKeys = Object.fromEntries(
        Object.entries(table6.foreignKeys || {}).filter(
          (it) => !it[0].endsWith("__added") && !it[0].endsWith("__deleted")
        ).map((entry) => [entry[0], entry[1]])
      );
      const addedCompositePKs = Object.fromEntries(
        Object.entries(table6.compositePrimaryKeys || {}).filter((it) => {
          return it[0].endsWith("__added");
        })
      );
      const deletedCompositePKs = Object.fromEntries(
        Object.entries(table6.compositePrimaryKeys || {}).filter((it) => {
          return it[0].endsWith("__deleted");
        })
      );
      const alteredCompositePKs = Object.fromEntries(
        Object.entries(table6.compositePrimaryKeys || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const addedUniqueConstraints = Object.fromEntries(
        Object.entries(table6.uniqueConstraints || {}).filter((it) => {
          return it[0].endsWith("__added");
        })
      );
      const deletedUniqueConstraints = Object.fromEntries(
        Object.entries(table6.uniqueConstraints || {}).filter((it) => {
          return it[0].endsWith("__deleted");
        })
      );
      const alteredUniqueConstraints = Object.fromEntries(
        Object.entries(table6.uniqueConstraints || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const addedCheckConstraints = Object.fromEntries(
        Object.entries(table6.checkConstraints || {}).filter((it) => {
          return it[0].endsWith("__added");
        })
      );
      const deletedCheckConstraints = Object.fromEntries(
        Object.entries(table6.checkConstraints || {}).filter((it) => {
          return it[0].endsWith("__deleted");
        })
      );
      const alteredCheckConstraints = Object.fromEntries(
        Object.entries(table6.checkConstraints || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const mappedAltered = altered.map((it) => alternationsInColumn(it)).filter(Boolean);
      return {
        name: table6.name,
        schema: table6.schema || "",
        altered: mappedAltered,
        addedIndexes,
        deletedIndexes,
        alteredIndexes,
        addedForeignKeys,
        deletedForeignKeys,
        alteredForeignKeys,
        addedCompositePKs,
        deletedCompositePKs,
        alteredCompositePKs,
        addedUniqueConstraints,
        deletedUniqueConstraints,
        alteredUniqueConstraints,
        deletedPolicies,
        addedPolicies,
        alteredPolicies,
        addedCheckConstraints,
        deletedCheckConstraints,
        alteredCheckConstraints
      };
    };
    alternationsInColumn = (column6) => {
      const altered = [column6];
      const result = altered.filter((it) => {
        if ("type" in it && it.type.__old.replace(" (", "(") === it.type.__new.replace(" (", "(")) {
          return false;
        }
        return true;
      }).map((it) => {
        if (typeof it.name !== "string" && "__old" in it.name) {
          return {
            ...it,
            name: { type: "changed", old: it.name.__old, new: it.name.__new }
          };
        }
        return it;
      }).map((it) => {
        if ("type" in it) {
          return {
            ...it,
            type: { type: "changed", old: it.type.__old, new: it.type.__new }
          };
        }
        return it;
      }).map((it) => {
        if ("default" in it) {
          return {
            ...it,
            default: {
              type: "changed",
              old: it.default.__old,
              new: it.default.__new
            }
          };
        }
        if ("default__added" in it) {
          const { default__added, ...others } = it;
          return {
            ...others,
            default: { type: "added", value: it.default__added }
          };
        }
        if ("default__deleted" in it) {
          const { default__deleted, ...others } = it;
          return {
            ...others,
            default: { type: "deleted", value: it.default__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("generated" in it) {
          if ("as" in it.generated && "type" in it.generated) {
            return {
              ...it,
              generated: {
                type: "changed",
                old: { as: it.generated.as.__old, type: it.generated.type.__old },
                new: { as: it.generated.as.__new, type: it.generated.type.__new }
              }
            };
          } else if ("as" in it.generated) {
            return {
              ...it,
              generated: {
                type: "changed",
                old: { as: it.generated.as.__old },
                new: { as: it.generated.as.__new }
              }
            };
          } else {
            return {
              ...it,
              generated: {
                type: "changed",
                old: { as: it.generated.type.__old },
                new: { as: it.generated.type.__new }
              }
            };
          }
        }
        if ("generated__added" in it) {
          const { generated__added, ...others } = it;
          return {
            ...others,
            generated: { type: "added", value: it.generated__added }
          };
        }
        if ("generated__deleted" in it) {
          const { generated__deleted, ...others } = it;
          return {
            ...others,
            generated: { type: "deleted", value: it.generated__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("identity" in it) {
          return {
            ...it,
            identity: {
              type: "changed",
              old: it.identity.__old,
              new: it.identity.__new
            }
          };
        }
        if ("identity__added" in it) {
          const { identity__added, ...others } = it;
          return {
            ...others,
            identity: { type: "added", value: it.identity__added }
          };
        }
        if ("identity__deleted" in it) {
          const { identity__deleted, ...others } = it;
          return {
            ...others,
            identity: { type: "deleted", value: it.identity__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("notNull" in it) {
          return {
            ...it,
            notNull: {
              type: "changed",
              old: it.notNull.__old,
              new: it.notNull.__new
            }
          };
        }
        if ("notNull__added" in it) {
          const { notNull__added, ...others } = it;
          return {
            ...others,
            notNull: { type: "added", value: it.notNull__added }
          };
        }
        if ("notNull__deleted" in it) {
          const { notNull__deleted, ...others } = it;
          return {
            ...others,
            notNull: { type: "deleted", value: it.notNull__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("primaryKey" in it) {
          return {
            ...it,
            primaryKey: {
              type: "changed",
              old: it.primaryKey.__old,
              new: it.primaryKey.__new
            }
          };
        }
        if ("primaryKey__added" in it) {
          const { notNull__added, ...others } = it;
          return {
            ...others,
            primaryKey: { type: "added", value: it.primaryKey__added }
          };
        }
        if ("primaryKey__deleted" in it) {
          const { notNull__deleted, ...others } = it;
          return {
            ...others,
            primaryKey: { type: "deleted", value: it.primaryKey__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("typeSchema" in it) {
          return {
            ...it,
            typeSchema: {
              type: "changed",
              old: it.typeSchema.__old,
              new: it.typeSchema.__new
            }
          };
        }
        if ("typeSchema__added" in it) {
          const { typeSchema__added, ...others } = it;
          return {
            ...others,
            typeSchema: { type: "added", value: it.typeSchema__added }
          };
        }
        if ("typeSchema__deleted" in it) {
          const { typeSchema__deleted, ...others } = it;
          return {
            ...others,
            typeSchema: { type: "deleted", value: it.typeSchema__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("onUpdate" in it) {
          return {
            ...it,
            onUpdate: {
              type: "changed",
              old: it.onUpdate.__old,
              new: it.onUpdate.__new
            }
          };
        }
        if ("onUpdate__added" in it) {
          const { onUpdate__added, ...others } = it;
          return {
            ...others,
            onUpdate: { type: "added", value: it.onUpdate__added }
          };
        }
        if ("onUpdate__deleted" in it) {
          const { onUpdate__deleted, ...others } = it;
          return {
            ...others,
            onUpdate: { type: "deleted", value: it.onUpdate__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("autoincrement" in it) {
          return {
            ...it,
            autoincrement: {
              type: "changed",
              old: it.autoincrement.__old,
              new: it.autoincrement.__new
            }
          };
        }
        if ("autoincrement__added" in it) {
          const { autoincrement__added, ...others } = it;
          return {
            ...others,
            autoincrement: { type: "added", value: it.autoincrement__added }
          };
        }
        if ("autoincrement__deleted" in it) {
          const { autoincrement__deleted, ...others } = it;
          return {
            ...others,
            autoincrement: { type: "deleted", value: it.autoincrement__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("" in it) {
          return {
            ...it,
            autoincrement: {
              type: "changed",
              old: it.autoincrement.__old,
              new: it.autoincrement.__new
            }
          };
        }
        if ("autoincrement__added" in it) {
          const { autoincrement__added, ...others } = it;
          return {
            ...others,
            autoincrement: { type: "added", value: it.autoincrement__added }
          };
        }
        if ("autoincrement__deleted" in it) {
          const { autoincrement__deleted, ...others } = it;
          return {
            ...others,
            autoincrement: { type: "deleted", value: it.autoincrement__deleted }
          };
        }
        return it;
      }).filter(Boolean);
      return result[0];
    };
  }
});

// src/sqlgenerator.ts
function fromJson(statements, dialect6, action, json2) {
  const result = statements.flatMap((statement) => {
    const filtered = convertors.filter((it) => {
      return it.can(statement, dialect6);
    });
    const convertor = filtered.length === 1 ? filtered[0] : void 0;
    if (!convertor) {
      return "";
    }
    return convertor.convert(statement, json2, action);
  }).filter((it) => it !== "");
  return result;
}
var parseType, Convertor, PgCreateRoleConvertor, PgDropRoleConvertor, PgRenameRoleConvertor, PgAlterRoleConvertor, PgCreatePolicyConvertor, PgDropPolicyConvertor, PgRenamePolicyConvertor, PgAlterPolicyConvertor, PgCreateIndPolicyConvertor, PgDropIndPolicyConvertor, PgRenameIndPolicyConvertor, PgAlterIndPolicyConvertor, PgEnableRlsConvertor, PgDisableRlsConvertor, PgCreateTableConvertor, MySqlCreateTableConvertor, SingleStoreCreateTableConvertor, SQLiteCreateTableConvertor, PgCreateViewConvertor, MySqlCreateViewConvertor, SqliteCreateViewConvertor, PgDropViewConvertor, MySqlDropViewConvertor, SqliteDropViewConvertor, MySqlAlterViewConvertor, PgRenameViewConvertor, MySqlRenameViewConvertor, PgAlterViewSchemaConvertor, PgAlterViewAddWithOptionConvertor, PgAlterViewDropWithOptionConvertor, PgAlterViewAlterTablespaceConvertor, PgAlterViewAlterUsingConvertor, PgAlterTableAlterColumnSetGenerated, PgAlterTableAlterColumnDropGenerated, PgAlterTableAlterColumnAlterGenerated, PgAlterTableAddUniqueConstraintConvertor, PgAlterTableDropUniqueConstraintConvertor, PgAlterTableAddCheckConstraintConvertor, PgAlterTableDeleteCheckConstraintConvertor, MySQLAlterTableAddUniqueConstraintConvertor, MySQLAlterTableDropUniqueConstraintConvertor, MySqlAlterTableAddCheckConstraintConvertor, SingleStoreAlterTableAddUniqueConstraintConvertor, SingleStoreAlterTableDropUniqueConstraintConvertor, MySqlAlterTableDeleteCheckConstraintConvertor, CreatePgSequenceConvertor, DropPgSequenceConvertor, RenamePgSequenceConvertor, MovePgSequenceConvertor, AlterPgSequenceConvertor, CreateTypeEnumConvertor, DropTypeEnumConvertor, AlterTypeAddValueConvertor, AlterTypeSetSchemaConvertor, AlterRenameTypeConvertor, AlterTypeDropValueConvertor, PgDropTableConvertor, MySQLDropTableConvertor, SingleStoreDropTableConvertor, SQLiteDropTableConvertor, PgRenameTableConvertor, SqliteRenameTableConvertor, MySqlRenameTableConvertor, SingleStoreRenameTableConvertor, PgAlterTableRenameColumnConvertor, MySqlAlterTableRenameColumnConvertor, SingleStoreAlterTableRenameColumnConvertor, SQLiteAlterTableRenameColumnConvertor, PgAlterTableDropColumnConvertor, MySqlAlterTableDropColumnConvertor, SingleStoreAlterTableDropColumnConvertor, SQLiteAlterTableDropColumnConvertor, PgAlterTableAddColumnConvertor, MySqlAlterTableAddColumnConvertor, SingleStoreAlterTableAddColumnConvertor, SQLiteAlterTableAddColumnConvertor, PgAlterTableAlterColumnSetTypeConvertor, PgAlterTableAlterColumnSetDefaultConvertor, PgAlterTableAlterColumnDropDefaultConvertor, PgAlterTableAlterColumnDropGeneratedConvertor, PgAlterTableAlterColumnSetExpressionConvertor, PgAlterTableAlterColumnAlterrGeneratedConvertor, SqliteAlterTableAlterColumnDropGeneratedConvertor, SqliteAlterTableAlterColumnSetExpressionConvertor, SqliteAlterTableAlterColumnAlterGeneratedConvertor, MySqlAlterTableAlterColumnAlterrGeneratedConvertor, MySqlAlterTableAddPk, MySqlAlterTableDropPk, LibSQLModifyColumn, MySqlModifyColumn, SingleStoreAlterTableAlterColumnAlterrGeneratedConvertor, SingleStoreAlterTableAddPk, SingleStoreAlterTableDropPk, SingleStoreModifyColumn, PgAlterTableCreateCompositePrimaryKeyConvertor, PgAlterTableDeleteCompositePrimaryKeyConvertor, PgAlterTableAlterCompositePrimaryKeyConvertor, MySqlAlterTableCreateCompositePrimaryKeyConvertor, MySqlAlterTableDeleteCompositePrimaryKeyConvertor, MySqlAlterTableAlterCompositePrimaryKeyConvertor, PgAlterTableAlterColumnSetPrimaryKeyConvertor, PgAlterTableAlterColumnDropPrimaryKeyConvertor, PgAlterTableAlterColumnSetNotNullConvertor, PgAlterTableAlterColumnDropNotNullConvertor, PgCreateForeignKeyConvertor, LibSQLCreateForeignKeyConvertor, MySqlCreateForeignKeyConvertor, PgAlterForeignKeyConvertor, PgDeleteForeignKeyConvertor, MySqlDeleteForeignKeyConvertor, CreatePgIndexConvertor, CreateMySqlIndexConvertor, CreateSingleStoreIndexConvertor, CreateSqliteIndexConvertor, PgDropIndexConvertor, PgCreateSchemaConvertor, PgRenameSchemaConvertor, PgDropSchemaConvertor, PgAlterTableSetSchemaConvertor, PgAlterTableSetNewSchemaConvertor, PgAlterTableRemoveFromSchemaConvertor, SqliteDropIndexConvertor, MySqlDropIndexConvertor, SingleStoreDropIndexConvertor, SQLiteRecreateTableConvertor, LibSQLRecreateTableConvertor, SingleStoreRecreateTableConvertor, convertors;
var init_sqlgenerator = __esm({
  "src/sqlgenerator.ts"() {
    "use strict";
    init_migrate();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    init_utils();
    parseType = (schemaPrefix, type) => {
      const pgNativeTypes = [
        "uuid",
        "smallint",
        "integer",
        "bigint",
        "boolean",
        "text",
        "varchar",
        "serial",
        "bigserial",
        "decimal",
        "numeric",
        "real",
        "json",
        "jsonb",
        "time",
        "time with time zone",
        "time without time zone",
        "time",
        "timestamp",
        "timestamp with time zone",
        "timestamp without time zone",
        "date",
        "interval",
        "bigint",
        "bigserial",
        "double precision",
        "interval year",
        "interval month",
        "interval day",
        "interval hour",
        "interval minute",
        "interval second",
        "interval year to month",
        "interval day to hour",
        "interval day to minute",
        "interval day to second",
        "interval hour to minute",
        "interval hour to second",
        "interval minute to second",
        "char",
        "vector",
        "geometry",
        "halfvec",
        "sparsevec",
        "bit"
      ];
      const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g;
      const arrayDefinition = (type.match(arrayDefinitionRegex) ?? []).join("");
      const withoutArrayDefinition = type.replace(arrayDefinitionRegex, "");
      return pgNativeTypes.some((it) => type.startsWith(it)) ? `${withoutArrayDefinition}${arrayDefinition}` : `${schemaPrefix}"${withoutArrayDefinition}"${arrayDefinition}`;
    };
    Convertor = class {
    };
    PgCreateRoleConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_role" && dialect6 === "postgresql";
      }
      convert(statement) {
        return `CREATE ROLE "${statement.name}"${statement.values.createDb || statement.values.createRole || !statement.values.inherit ? ` WITH${statement.values.createDb ? " CREATEDB" : ""}${statement.values.createRole ? " CREATEROLE" : ""}${statement.values.inherit ? "" : " NOINHERIT"}` : ""};`;
      }
    };
    PgDropRoleConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_role" && dialect6 === "postgresql";
      }
      convert(statement) {
        return `DROP ROLE "${statement.name}";`;
      }
    };
    PgRenameRoleConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_role" && dialect6 === "postgresql";
      }
      convert(statement) {
        return `ALTER ROLE "${statement.nameFrom}" RENAME TO "${statement.nameTo}";`;
      }
    };
    PgAlterRoleConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_role" && dialect6 === "postgresql";
      }
      convert(statement) {
        return `ALTER ROLE "${statement.name}"${` WITH${statement.values.createDb ? " CREATEDB" : " NOCREATEDB"}${statement.values.createRole ? " CREATEROLE" : " NOCREATEROLE"}${statement.values.inherit ? " INHERIT" : " NOINHERIT"}`};`;
      }
    };
    PgCreatePolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const policy5 = statement.data;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        const usingPart = policy5.using ? ` USING (${policy5.using})` : "";
        const withCheckPart = policy5.withCheck ? ` WITH CHECK (${policy5.withCheck})` : "";
        const policyToPart = policy5.to?.map(
          (v6) => ["current_user", "current_role", "session_user", "public"].includes(v6) ? v6 : `"${v6}"`
        ).join(", ");
        return `CREATE POLICY "${policy5.name}" ON ${tableNameWithSchema} AS ${policy5.as?.toUpperCase()} FOR ${policy5.for?.toUpperCase()} TO ${policyToPart}${usingPart}${withCheckPart};`;
      }
    };
    PgDropPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const policy5 = statement.data;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `DROP POLICY "${policy5.name}" ON ${tableNameWithSchema} CASCADE;`;
      }
    };
    PgRenamePolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER POLICY "${statement.oldName}" ON ${tableNameWithSchema} RENAME TO "${statement.newName}";`;
      }
    };
    PgAlterPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_policy" && dialect6 === "postgresql";
      }
      convert(statement, _dialect, action) {
        const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(statement.newData) : PgSquasher.unsquashPolicy(statement.newData);
        const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(statement.oldData) : PgSquasher.unsquashPolicy(statement.oldData);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        const usingPart = newPolicy.using ? ` USING (${newPolicy.using})` : oldPolicy.using ? ` USING (${oldPolicy.using})` : "";
        const withCheckPart = newPolicy.withCheck ? ` WITH CHECK (${newPolicy.withCheck})` : oldPolicy.withCheck ? ` WITH CHECK  (${oldPolicy.withCheck})` : "";
        return `ALTER POLICY "${oldPolicy.name}" ON ${tableNameWithSchema} TO ${newPolicy.to}${usingPart}${withCheckPart};`;
      }
    };
    PgCreateIndPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_ind_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const policy5 = statement.data;
        const usingPart = policy5.using ? ` USING (${policy5.using})` : "";
        const withCheckPart = policy5.withCheck ? ` WITH CHECK (${policy5.withCheck})` : "";
        const policyToPart = policy5.to?.map(
          (v6) => ["current_user", "current_role", "session_user", "public"].includes(v6) ? v6 : `"${v6}"`
        ).join(", ");
        return `CREATE POLICY "${policy5.name}" ON ${policy5.on} AS ${policy5.as?.toUpperCase()} FOR ${policy5.for?.toUpperCase()} TO ${policyToPart}${usingPart}${withCheckPart};`;
      }
    };
    PgDropIndPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_ind_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const policy5 = statement.data;
        return `DROP POLICY "${policy5.name}" ON ${policy5.on} CASCADE;`;
      }
    };
    PgRenameIndPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_ind_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        return `ALTER POLICY "${statement.oldName}" ON ${statement.tableKey} RENAME TO "${statement.newName}";`;
      }
    };
    PgAlterIndPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_ind_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const newPolicy = statement.newData;
        const oldPolicy = statement.oldData;
        const usingPart = newPolicy.using ? ` USING (${newPolicy.using})` : oldPolicy.using ? ` USING (${oldPolicy.using})` : "";
        const withCheckPart = newPolicy.withCheck ? ` WITH CHECK (${newPolicy.withCheck})` : oldPolicy.withCheck ? ` WITH CHECK  (${oldPolicy.withCheck})` : "";
        return `ALTER POLICY "${oldPolicy.name}" ON ${oldPolicy.on} TO ${newPolicy.to}${usingPart}${withCheckPart};`;
      }
    };
    PgEnableRlsConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "enable_rls" && dialect6 === "postgresql";
      }
      convert(statement) {
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ENABLE ROW LEVEL SECURITY;`;
      }
    };
    PgDisableRlsConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "disable_rls" && dialect6 === "postgresql";
      }
      convert(statement) {
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} DISABLE ROW LEVEL SECURITY;`;
      }
    };
    PgCreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_table" && dialect6 === "postgresql";
      }
      convert(st) {
        const { tableName, schema: schema6, columns, compositePKs, uniqueConstraints, checkConstraints, policies, isRLSEnabled } = st;
        let statement = "";
        const name = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        statement += `CREATE TABLE ${name} (
`;
        for (let i6 = 0; i6 < columns.length; i6++) {
          const column6 = columns[i6];
          const primaryKeyStatement = column6.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column6.notNull && !column6.identity ? " NOT NULL" : "";
          const defaultStatement = column6.default !== void 0 ? ` DEFAULT ${column6.default}` : "";
          const uniqueConstraint6 = column6.isUnique ? ` CONSTRAINT "${column6.uniqueName}" UNIQUE${column6.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}` : "";
          const schemaPrefix = column6.typeSchema && column6.typeSchema !== "public" ? `"${column6.typeSchema}".` : "";
          const type = parseType(schemaPrefix, column6.type);
          const generated = column6.generated;
          const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated?.as}) STORED` : "";
          const unsquashedIdentity = column6.identity ? PgSquasher.unsquashIdentity(column6.identity) : void 0;
          const identityWithSchema = schema6 ? `"${schema6}"."${unsquashedIdentity?.name}"` : `"${unsquashedIdentity?.name}"`;
          const identity = unsquashedIdentity ? ` GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY (sequence name ${identityWithSchema}${unsquashedIdentity.increment ? ` INCREMENT BY ${unsquashedIdentity.increment}` : ""}${unsquashedIdentity.minValue ? ` MINVALUE ${unsquashedIdentity.minValue}` : ""}${unsquashedIdentity.maxValue ? ` MAXVALUE ${unsquashedIdentity.maxValue}` : ""}${unsquashedIdentity.startWith ? ` START WITH ${unsquashedIdentity.startWith}` : ""}${unsquashedIdentity.cache ? ` CACHE ${unsquashedIdentity.cache}` : ""}${unsquashedIdentity.cycle ? ` CYCLE` : ""})` : "";
          statement += `	"${column6.name}" ${type}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${uniqueConstraint6}${identity}`;
          statement += i6 === columns.length - 1 ? "" : ",\n";
        }
        if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
          statement += ",\n";
          const compositePK6 = PgSquasher.unsquashPK(compositePKs[0]);
          statement += `	CONSTRAINT "${st.compositePkName}" PRIMARY KEY("${compositePK6.columns.join(`","`)}")`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint6 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = PgSquasher.unsquashUnique(uniqueConstraint6);
            statement += `	CONSTRAINT "${unsquashedUnique.name}" UNIQUE${unsquashedUnique.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}("${unsquashedUnique.columns.join(`","`)}")`;
          }
        }
        if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
          for (const checkConstraint5 of checkConstraints) {
            statement += ",\n";
            const unsquashedCheck = PgSquasher.unsquashCheck(checkConstraint5);
            statement += `	CONSTRAINT "${unsquashedCheck.name}" CHECK (${unsquashedCheck.value})`;
          }
        }
        statement += `
);`;
        statement += `
`;
        const enableRls = new PgEnableRlsConvertor().convert({
          type: "enable_rls",
          tableName,
          schema: schema6
        });
        return [statement, ...policies && policies.length > 0 || isRLSEnabled ? [enableRls] : []];
      }
    };
    MySqlCreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_table" && dialect6 === "mysql";
      }
      convert(st) {
        const {
          tableName,
          columns,
          schema: schema6,
          checkConstraints,
          compositePKs,
          uniqueConstraints,
          internals
        } = st;
        let statement = "";
        statement += `CREATE TABLE \`${tableName}\` (
`;
        for (let i6 = 0; i6 < columns.length; i6++) {
          const column6 = columns[i6];
          const primaryKeyStatement = column6.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column6.notNull ? " NOT NULL" : "";
          const defaultStatement = column6.default !== void 0 ? ` DEFAULT ${column6.default}` : "";
          const onUpdateStatement = column6.onUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          const autoincrementStatement = column6.autoincrement ? " AUTO_INCREMENT" : "";
          const generatedStatement = column6.generated ? ` GENERATED ALWAYS AS (${column6.generated?.as}) ${column6.generated?.type.toUpperCase()}` : "";
          statement += `	\`${column6.name}\` ${column6.type}${autoincrementStatement}${primaryKeyStatement}${generatedStatement}${notNullStatement}${defaultStatement}${onUpdateStatement}`;
          statement += i6 === columns.length - 1 ? "" : ",\n";
        }
        if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
          statement += ",\n";
          const compositePK6 = MySqlSquasher.unsquashPK(compositePKs[0]);
          statement += `	CONSTRAINT \`${st.compositePkName}\` PRIMARY KEY(\`${compositePK6.columns.join(`\`,\``)}\`)`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint6 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = MySqlSquasher.unsquashUnique(uniqueConstraint6);
            const uniqueString = unsquashedUnique.columns.map((it) => {
              return internals?.indexes ? internals?.indexes[unsquashedUnique.name]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``;
            }).join(",");
            statement += `	CONSTRAINT \`${unsquashedUnique.name}\` UNIQUE(${uniqueString})`;
          }
        }
        if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
          for (const checkConstraint5 of checkConstraints) {
            statement += ",\n";
            const unsquashedCheck = MySqlSquasher.unsquashCheck(checkConstraint5);
            statement += `	CONSTRAINT \`${unsquashedCheck.name}\` CHECK(${unsquashedCheck.value})`;
          }
        }
        statement += `
);`;
        statement += `
`;
        return statement;
      }
    };
    SingleStoreCreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_table" && dialect6 === "singlestore";
      }
      convert(st) {
        const {
          tableName,
          columns,
          schema: schema6,
          compositePKs,
          uniqueConstraints,
          internals
        } = st;
        let statement = "";
        statement += `CREATE TABLE \`${tableName}\` (
`;
        for (let i6 = 0; i6 < columns.length; i6++) {
          const column6 = columns[i6];
          const primaryKeyStatement = column6.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column6.notNull ? " NOT NULL" : "";
          const defaultStatement = column6.default !== void 0 ? ` DEFAULT ${column6.default}` : "";
          const onUpdateStatement = column6.onUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          const autoincrementStatement = column6.autoincrement ? " AUTO_INCREMENT" : "";
          const generatedStatement = column6.generated ? ` GENERATED ALWAYS AS (${column6.generated?.as}) ${column6.generated?.type.toUpperCase()}` : "";
          statement += `	\`${column6.name}\` ${column6.type}${autoincrementStatement}${primaryKeyStatement}${notNullStatement}${defaultStatement}${onUpdateStatement}${generatedStatement}`;
          statement += i6 === columns.length - 1 ? "" : ",\n";
        }
        if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
          statement += ",\n";
          const compositePK6 = SingleStoreSquasher.unsquashPK(compositePKs[0]);
          statement += `	CONSTRAINT \`${compositePK6.name}\` PRIMARY KEY(\`${compositePK6.columns.join(`\`,\``)}\`)`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint6 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = SingleStoreSquasher.unsquashUnique(uniqueConstraint6);
            const uniqueString = unsquashedUnique.columns.map((it) => {
              return internals?.indexes ? internals?.indexes[unsquashedUnique.name]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``;
            }).join(",");
            statement += `	CONSTRAINT \`${unsquashedUnique.name}\` UNIQUE(${uniqueString})`;
          }
        }
        statement += `
);`;
        statement += `
`;
        return statement;
      }
    };
    SQLiteCreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "sqlite_create_table" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(st) {
        const {
          tableName,
          columns,
          referenceData,
          compositePKs,
          uniqueConstraints,
          checkConstraints
        } = st;
        let statement = "";
        statement += `CREATE TABLE \`${tableName}\` (
`;
        for (let i6 = 0; i6 < columns.length; i6++) {
          const column6 = columns[i6];
          const primaryKeyStatement = column6.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column6.notNull ? " NOT NULL" : "";
          const defaultStatement = column6.default !== void 0 ? ` DEFAULT ${column6.default}` : "";
          const autoincrementStatement = column6.autoincrement ? " AUTOINCREMENT" : "";
          const generatedStatement = column6.generated ? ` GENERATED ALWAYS AS ${column6.generated.as} ${column6.generated.type.toUpperCase()}` : "";
          statement += "	";
          statement += `\`${column6.name}\` ${column6.type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${generatedStatement}${notNullStatement}`;
          statement += i6 === columns.length - 1 ? "" : ",\n";
        }
        compositePKs.forEach((it) => {
          statement += ",\n	";
          statement += `PRIMARY KEY(${it.map((it2) => `\`${it2}\``).join(", ")})`;
        });
        for (let i6 = 0; i6 < referenceData.length; i6++) {
          const {
            name,
            tableFrom,
            tableTo,
            columnsFrom,
            columnsTo,
            onDelete,
            onUpdate
          } = referenceData[i6];
          const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
          const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
          const fromColumnsString = columnsFrom.map((it) => `\`${it}\``).join(",");
          const toColumnsString = columnsTo.map((it) => `\`${it}\``).join(",");
          statement += ",";
          statement += "\n	";
          statement += `FOREIGN KEY (${fromColumnsString}) REFERENCES \`${tableTo}\`(${toColumnsString})${onUpdateStatement}${onDeleteStatement}`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint6 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = SQLiteSquasher.unsquashUnique(uniqueConstraint6);
            statement += `	CONSTRAINT ${unsquashedUnique.name} UNIQUE(\`${unsquashedUnique.columns.join(`\`,\``)}\`)`;
          }
        }
        if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
          for (const check of checkConstraints) {
            statement += ",\n";
            const { value, name } = SQLiteSquasher.unsquashCheck(check);
            statement += `	CONSTRAINT "${name}" CHECK(${value})`;
          }
        }
        statement += `
`;
        statement += `);`;
        statement += `
`;
        return statement;
      }
    };
    PgCreateViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_view" && dialect6 === "postgresql";
      }
      convert(st) {
        const { definition, name: viewName, schema: schema6, with: withOption, materialized, withNoData, tablespace, using } = st;
        const name = schema6 ? `"${schema6}"."${viewName}"` : `"${viewName}"`;
        let statement = materialized ? `CREATE MATERIALIZED VIEW ${name}` : `CREATE VIEW ${name}`;
        if (using) statement += ` USING "${using}"`;
        const options = [];
        if (withOption) {
          statement += ` WITH (`;
          Object.entries(withOption).forEach(([key, value]) => {
            if (typeof value === "undefined") return;
            options.push(`${key.snake_case()} = ${value}`);
          });
          statement += options.join(", ");
          statement += `)`;
        }
        if (tablespace) statement += ` TABLESPACE ${tablespace}`;
        statement += ` AS (${definition})`;
        if (withNoData) statement += ` WITH NO DATA`;
        statement += `;`;
        return statement;
      }
    };
    MySqlCreateViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "mysql_create_view" && dialect6 === "mysql";
      }
      convert(st) {
        const { definition, name, algorithm, sqlSecurity, withCheckOption, replace } = st;
        let statement = `CREATE `;
        statement += replace ? `OR REPLACE ` : "";
        statement += algorithm ? `ALGORITHM = ${algorithm}
` : "";
        statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
` : "";
        statement += `VIEW \`${name}\` AS (${definition})`;
        statement += withCheckOption ? `
WITH ${withCheckOption} CHECK OPTION` : "";
        statement += ";";
        return statement;
      }
    };
    SqliteCreateViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "sqlite_create_view" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(st) {
        const { definition, name } = st;
        return `CREATE VIEW \`${name}\` AS ${definition};`;
      }
    };
    PgDropViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_view" && dialect6 === "postgresql";
      }
      convert(st) {
        const { name: viewName, schema: schema6, materialized } = st;
        const name = schema6 ? `"${schema6}"."${viewName}"` : `"${viewName}"`;
        return `DROP${materialized ? " MATERIALIZED" : ""} VIEW ${name};`;
      }
    };
    MySqlDropViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_view" && dialect6 === "mysql";
      }
      convert(st) {
        const { name } = st;
        return `DROP VIEW \`${name}\`;`;
      }
    };
    SqliteDropViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_view" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(st) {
        const { name } = st;
        return `DROP VIEW \`${name}\`;`;
      }
    };
    MySqlAlterViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_mysql_view" && dialect6 === "mysql";
      }
      convert(st) {
        const { name, algorithm, definition, sqlSecurity, withCheckOption } = st;
        let statement = `ALTER `;
        statement += algorithm ? `ALGORITHM = ${algorithm}
` : "";
        statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
` : "";
        statement += `VIEW \`${name}\` AS ${definition}`;
        statement += withCheckOption ? `
WITH ${withCheckOption} CHECK OPTION` : "";
        statement += ";";
        return statement;
      }
    };
    PgRenameViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_view" && dialect6 === "postgresql";
      }
      convert(st) {
        const { nameFrom: from, nameTo: to, schema: schema6, materialized } = st;
        const nameFrom = `"${schema6}"."${from}"`;
        return `ALTER${materialized ? " MATERIALIZED" : ""} VIEW ${nameFrom} RENAME TO "${to}";`;
      }
    };
    MySqlRenameViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_view" && dialect6 === "mysql";
      }
      convert(st) {
        const { nameFrom: from, nameTo: to } = st;
        return `RENAME TABLE \`${from}\` TO \`${to}\`;`;
      }
    };
    PgAlterViewSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_view_alter_schema" && dialect6 === "postgresql";
      }
      convert(st) {
        const { fromSchema, toSchema, name, materialized } = st;
        const statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${fromSchema}"."${name}" SET SCHEMA "${toSchema}";`;
        return statement;
      }
    };
    PgAlterViewAddWithOptionConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_view_add_with_option" && dialect6 === "postgresql";
      }
      convert(st) {
        const { schema: schema6, with: withOption, name, materialized } = st;
        let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema6}"."${name}" SET (`;
        const options = [];
        Object.entries(withOption).forEach(([key, value]) => {
          options.push(`${key.snake_case()} = ${value}`);
        });
        statement += options.join(", ");
        statement += `);`;
        return statement;
      }
    };
    PgAlterViewDropWithOptionConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_view_drop_with_option" && dialect6 === "postgresql";
      }
      convert(st) {
        const { schema: schema6, name, materialized, with: withOptions } = st;
        let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema6}"."${name}" RESET (`;
        const options = [];
        Object.entries(withOptions).forEach(([key, value]) => {
          options.push(`${key.snake_case()}`);
        });
        statement += options.join(", ");
        statement += ");";
        return statement;
      }
    };
    PgAlterViewAlterTablespaceConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_view_alter_tablespace" && dialect6 === "postgresql";
      }
      convert(st) {
        const { schema: schema6, name, toTablespace } = st;
        const statement = `ALTER MATERIALIZED VIEW "${schema6}"."${name}" SET TABLESPACE ${toTablespace};`;
        return statement;
      }
    };
    PgAlterViewAlterUsingConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_view_alter_using" && dialect6 === "postgresql";
      }
      convert(st) {
        const { schema: schema6, name, toUsing } = st;
        const statement = `ALTER MATERIALIZED VIEW "${schema6}"."${name}" SET ACCESS METHOD "${toUsing}";`;
        return statement;
      }
    };
    PgAlterTableAlterColumnSetGenerated = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_identity" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { identity, tableName, columnName, schema: schema6 } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        const unsquashedIdentity = PgSquasher.unsquashIdentity(identity);
        const identityWithSchema = schema6 ? `"${schema6}"."${unsquashedIdentity?.name}"` : `"${unsquashedIdentity?.name}"`;
        const identityStatement = unsquashedIdentity ? ` GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY (sequence name ${identityWithSchema}${unsquashedIdentity.increment ? ` INCREMENT BY ${unsquashedIdentity.increment}` : ""}${unsquashedIdentity.minValue ? ` MINVALUE ${unsquashedIdentity.minValue}` : ""}${unsquashedIdentity.maxValue ? ` MAXVALUE ${unsquashedIdentity.maxValue}` : ""}${unsquashedIdentity.startWith ? ` START WITH ${unsquashedIdentity.startWith}` : ""}${unsquashedIdentity.cache ? ` CACHE ${unsquashedIdentity.cache}` : ""}${unsquashedIdentity.cycle ? ` CYCLE` : ""})` : "";
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" ADD${identityStatement};`;
      }
    };
    PgAlterTableAlterColumnDropGenerated = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_identity" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema6 } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP IDENTITY;`;
      }
    };
    PgAlterTableAlterColumnAlterGenerated = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_change_identity" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { identity, oldIdentity, tableName, columnName, schema: schema6 } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        const unsquashedIdentity = PgSquasher.unsquashIdentity(identity);
        const unsquashedOldIdentity = PgSquasher.unsquashIdentity(oldIdentity);
        const statementsToReturn = [];
        if (unsquashedOldIdentity.type !== unsquashedIdentity.type) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"};`
          );
        }
        if (unsquashedOldIdentity.minValue !== unsquashedIdentity.minValue) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET MINVALUE ${unsquashedIdentity.minValue};`
          );
        }
        if (unsquashedOldIdentity.maxValue !== unsquashedIdentity.maxValue) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET MAXVALUE ${unsquashedIdentity.maxValue};`
          );
        }
        if (unsquashedOldIdentity.increment !== unsquashedIdentity.increment) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET INCREMENT BY ${unsquashedIdentity.increment};`
          );
        }
        if (unsquashedOldIdentity.startWith !== unsquashedIdentity.startWith) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET START WITH ${unsquashedIdentity.startWith};`
          );
        }
        if (unsquashedOldIdentity.cache !== unsquashedIdentity.cache) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET CACHE ${unsquashedIdentity.cache};`
          );
        }
        if (unsquashedOldIdentity.cycle !== unsquashedIdentity.cycle) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET ${unsquashedIdentity.cycle ? `CYCLE` : "NO CYCLE"};`
          );
        }
        return statementsToReturn;
      }
    };
    PgAlterTableAddUniqueConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_unique_constraint" && dialect6 === "postgresql";
      }
      convert(statement) {
        const unsquashed = PgSquasher.unsquashUnique(statement.data);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${unsquashed.name}" UNIQUE${unsquashed.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}("${unsquashed.columns.join('","')}");`;
      }
    };
    PgAlterTableDropUniqueConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_unique_constraint" && dialect6 === "postgresql";
      }
      convert(statement) {
        const unsquashed = PgSquasher.unsquashUnique(statement.data);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${unsquashed.name}";`;
      }
    };
    PgAlterTableAddCheckConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_check_constraint" && dialect6 === "postgresql";
      }
      convert(statement) {
        const unsquashed = PgSquasher.unsquashCheck(statement.data);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${unsquashed.name}" CHECK (${unsquashed.value});`;
      }
    };
    PgAlterTableDeleteCheckConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_check_constraint" && dialect6 === "postgresql";
      }
      convert(statement) {
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${statement.constraintName}";`;
      }
    };
    MySQLAlterTableAddUniqueConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_unique_constraint" && dialect6 === "mysql";
      }
      convert(statement) {
        const unsquashed = MySqlSquasher.unsquashUnique(statement.data);
        return `ALTER TABLE \`${statement.tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` UNIQUE(\`${unsquashed.columns.join("`,`")}\`);`;
      }
    };
    MySQLAlterTableDropUniqueConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_unique_constraint" && dialect6 === "mysql";
      }
      convert(statement) {
        const unsquashed = MySqlSquasher.unsquashUnique(statement.data);
        return `ALTER TABLE \`${statement.tableName}\` DROP INDEX \`${unsquashed.name}\`;`;
      }
    };
    MySqlAlterTableAddCheckConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_check_constraint" && dialect6 === "mysql";
      }
      convert(statement) {
        const unsquashed = MySqlSquasher.unsquashCheck(statement.data);
        const { tableName } = statement;
        return `ALTER TABLE \`${tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` CHECK (${unsquashed.value});`;
      }
    };
    SingleStoreAlterTableAddUniqueConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_unique_constraint" && dialect6 === "singlestore";
      }
      convert(statement) {
        const unsquashed = SingleStoreSquasher.unsquashUnique(statement.data);
        return `ALTER TABLE \`${statement.tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` UNIQUE(\`${unsquashed.columns.join("`,`")}\`);`;
      }
    };
    SingleStoreAlterTableDropUniqueConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_unique_constraint" && dialect6 === "singlestore";
      }
      convert(statement) {
        const unsquashed = SingleStoreSquasher.unsquashUnique(statement.data);
        return `ALTER TABLE \`${statement.tableName}\` DROP INDEX \`${unsquashed.name}\`;`;
      }
    };
    MySqlAlterTableDeleteCheckConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_check_constraint" && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableName } = statement;
        return `ALTER TABLE \`${tableName}\` DROP CONSTRAINT \`${statement.constraintName}\`;`;
      }
    };
    CreatePgSequenceConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_sequence" && dialect6 === "postgresql";
      }
      convert(st) {
        const { name, values, schema: schema6 } = st;
        const sequenceWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
        return `CREATE SEQUENCE ${sequenceWithSchema}${values.increment ? ` INCREMENT BY ${values.increment}` : ""}${values.minValue ? ` MINVALUE ${values.minValue}` : ""}${values.maxValue ? ` MAXVALUE ${values.maxValue}` : ""}${values.startWith ? ` START WITH ${values.startWith}` : ""}${values.cache ? ` CACHE ${values.cache}` : ""}${values.cycle ? ` CYCLE` : ""};`;
      }
    };
    DropPgSequenceConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_sequence" && dialect6 === "postgresql";
      }
      convert(st) {
        const { name, schema: schema6 } = st;
        const sequenceWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
        return `DROP SEQUENCE ${sequenceWithSchema};`;
      }
    };
    RenamePgSequenceConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_sequence" && dialect6 === "postgresql";
      }
      convert(st) {
        const { nameFrom, nameTo, schema: schema6 } = st;
        const sequenceWithSchemaFrom = schema6 ? `"${schema6}"."${nameFrom}"` : `"${nameFrom}"`;
        const sequenceWithSchemaTo = schema6 ? `"${schema6}"."${nameTo}"` : `"${nameTo}"`;
        return `ALTER SEQUENCE ${sequenceWithSchemaFrom} RENAME TO "${nameTo}";`;
      }
    };
    MovePgSequenceConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "move_sequence" && dialect6 === "postgresql";
      }
      convert(st) {
        const { schemaFrom, schemaTo, name } = st;
        const sequenceWithSchema = schemaFrom ? `"${schemaFrom}"."${name}"` : `"${name}"`;
        const seqSchemaTo = schemaTo ? `"${schemaTo}"` : `public`;
        return `ALTER SEQUENCE ${sequenceWithSchema} SET SCHEMA ${seqSchemaTo};`;
      }
    };
    AlterPgSequenceConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_sequence" && dialect6 === "postgresql";
      }
      convert(st) {
        const { name, schema: schema6, values } = st;
        const { increment, minValue, maxValue, startWith, cache: cache5, cycle } = values;
        const sequenceWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
        return `ALTER SEQUENCE ${sequenceWithSchema}${increment ? ` INCREMENT BY ${increment}` : ""}${minValue ? ` MINVALUE ${minValue}` : ""}${maxValue ? ` MAXVALUE ${maxValue}` : ""}${startWith ? ` START WITH ${startWith}` : ""}${cache5 ? ` CACHE ${cache5}` : ""}${cycle ? ` CYCLE` : ""};`;
      }
    };
    CreateTypeEnumConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "create_type_enum";
      }
      convert(st) {
        const { name, values, schema: schema6 } = st;
        const enumNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
        let valuesStatement = "(";
        valuesStatement += values.map((it) => `'${escapeSingleQuotes(it)}'`).join(", ");
        valuesStatement += ")";
        let statement = `CREATE TYPE ${enumNameWithSchema} AS ENUM${valuesStatement};`;
        return statement;
      }
    };
    DropTypeEnumConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "drop_type_enum";
      }
      convert(st) {
        const { name, schema: schema6 } = st;
        const enumNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
        let statement = `DROP TYPE ${enumNameWithSchema};`;
        return statement;
      }
    };
    AlterTypeAddValueConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "alter_type_add_value";
      }
      convert(st) {
        const { name, schema: schema6, value, before } = st;
        const enumNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
        return `ALTER TYPE ${enumNameWithSchema} ADD VALUE '${value}'${before.length ? ` BEFORE '${before}'` : ""};`;
      }
    };
    AlterTypeSetSchemaConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "move_type_enum";
      }
      convert(st) {
        const { name, schemaFrom, schemaTo } = st;
        const enumNameWithSchema = schemaFrom ? `"${schemaFrom}"."${name}"` : `"${name}"`;
        return `ALTER TYPE ${enumNameWithSchema} SET SCHEMA "${schemaTo}";`;
      }
    };
    AlterRenameTypeConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "rename_type_enum";
      }
      convert(st) {
        const { nameTo, nameFrom, schema: schema6 } = st;
        const enumNameWithSchema = schema6 ? `"${schema6}"."${nameFrom}"` : `"${nameFrom}"`;
        return `ALTER TYPE ${enumNameWithSchema} RENAME TO "${nameTo}";`;
      }
    };
    AlterTypeDropValueConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "alter_type_drop_value";
      }
      convert(st) {
        const { columnsWithEnum, name, newValues, enumSchema: enumSchema4 } = st;
        const statements = [];
        for (const withEnum of columnsWithEnum) {
          const tableNameWithSchema = withEnum.tableSchema ? `"${withEnum.tableSchema}"."${withEnum.table}"` : `"${withEnum.table}"`;
          statements.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DATA TYPE text;`
          );
          if (withEnum.default) {
            statements.push(
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DEFAULT ${withEnum.default}::text;`
            );
          }
        }
        statements.push(new DropTypeEnumConvertor().convert({ name, schema: enumSchema4, type: "drop_type_enum" }));
        statements.push(new CreateTypeEnumConvertor().convert({
          name,
          schema: enumSchema4,
          values: newValues,
          type: "create_type_enum"
        }));
        for (const withEnum of columnsWithEnum) {
          const tableNameWithSchema = withEnum.tableSchema ? `"${withEnum.tableSchema}"."${withEnum.table}"` : `"${withEnum.table}"`;
          const parsedType = parseType(`"${enumSchema4}".`, withEnum.columnType);
          if (withEnum.default) {
            statements.push(
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DEFAULT ${withEnum.default}::${parsedType};`
            );
          }
          statements.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DATA TYPE ${parsedType} USING "${withEnum.column}"::${parsedType};`
          );
        }
        return statements;
      }
    };
    PgDropTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_table" && dialect6 === "postgresql";
      }
      convert(statement, _d2, action) {
        const { tableName, schema: schema6, policies } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        const dropPolicyConvertor = new PgDropPolicyConvertor();
        const droppedPolicies = policies?.map((p5) => {
          return dropPolicyConvertor.convert({
            type: "drop_policy",
            tableName,
            data: action === "push" ? PgSquasher.unsquashPolicyPush(p5) : PgSquasher.unsquashPolicy(p5),
            schema: schema6
          });
        }) ?? [];
        return [
          ...droppedPolicies,
          `DROP TABLE ${tableNameWithSchema} CASCADE;`
        ];
      }
    };
    MySQLDropTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_table" && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableName } = statement;
        return `DROP TABLE \`${tableName}\`;`;
      }
    };
    SingleStoreDropTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_table" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableName } = statement;
        return `DROP TABLE \`${tableName}\`;`;
      }
    };
    SQLiteDropTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_table" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { tableName } = statement;
        return `DROP TABLE \`${tableName}\`;`;
      }
    };
    PgRenameTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_table" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableNameFrom, tableNameTo, toSchema, fromSchema } = statement;
        const from = fromSchema ? `"${fromSchema}"."${tableNameFrom}"` : `"${tableNameFrom}"`;
        const to = `"${tableNameTo}"`;
        return `ALTER TABLE ${from} RENAME TO ${to};`;
      }
    };
    SqliteRenameTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_table" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { tableNameFrom, tableNameTo } = statement;
        return `ALTER TABLE \`${tableNameFrom}\` RENAME TO \`${tableNameTo}\`;`;
      }
    };
    MySqlRenameTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_table" && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableNameFrom, tableNameTo } = statement;
        return `RENAME TABLE \`${tableNameFrom}\` TO \`${tableNameTo}\`;`;
      }
    };
    SingleStoreRenameTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_table" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableNameFrom, tableNameTo } = statement;
        return `ALTER TABLE \`${tableNameFrom}\` RENAME TO \`${tableNameTo}\`;`;
      }
    };
    PgAlterTableRenameColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_rename_column" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, oldColumnName, newColumnName, schema: schema6 } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} RENAME COLUMN "${oldColumnName}" TO "${newColumnName}";`;
      }
    };
    MySqlAlterTableRenameColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_rename_column" && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableName, oldColumnName, newColumnName } = statement;
        return `ALTER TABLE \`${tableName}\` RENAME COLUMN \`${oldColumnName}\` TO \`${newColumnName}\`;`;
      }
    };
    SingleStoreAlterTableRenameColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_rename_column" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableName, oldColumnName, newColumnName } = statement;
        return `ALTER TABLE \`${tableName}\` CHANGE \`${oldColumnName}\` \`${newColumnName}\`;`;
      }
    };
    SQLiteAlterTableRenameColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_rename_column" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { tableName, oldColumnName, newColumnName } = statement;
        return `ALTER TABLE \`${tableName}\` RENAME COLUMN "${oldColumnName}" TO "${newColumnName}";`;
      }
    };
    PgAlterTableDropColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_drop_column" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema6 } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP COLUMN "${columnName}";`;
      }
    };
    MySqlAlterTableDropColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_drop_column" && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`;
      }
    };
    SingleStoreAlterTableDropColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_drop_column" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`;
      }
    };
    SQLiteAlterTableDropColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_drop_column" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`;
      }
    };
    PgAlterTableAddColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_add_column" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, column: column6, schema: schema6 } = statement;
        const { name, type, notNull, generated, primaryKey, identity } = column6;
        const primaryKeyStatement = primaryKey ? " PRIMARY KEY" : "";
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        const defaultStatement = `${column6.default !== void 0 ? ` DEFAULT ${column6.default}` : ""}`;
        const schemaPrefix = column6.typeSchema && column6.typeSchema !== "public" ? `"${column6.typeSchema}".` : "";
        const fixedType = parseType(schemaPrefix, column6.type);
        const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
        const unsquashedIdentity = identity ? PgSquasher.unsquashIdentity(identity) : void 0;
        const identityWithSchema = schema6 ? `"${schema6}"."${unsquashedIdentity?.name}"` : `"${unsquashedIdentity?.name}"`;
        const identityStatement = unsquashedIdentity ? ` GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY (sequence name ${identityWithSchema}${unsquashedIdentity.increment ? ` INCREMENT BY ${unsquashedIdentity.increment}` : ""}${unsquashedIdentity.minValue ? ` MINVALUE ${unsquashedIdentity.minValue}` : ""}${unsquashedIdentity.maxValue ? ` MAXVALUE ${unsquashedIdentity.maxValue}` : ""}${unsquashedIdentity.startWith ? ` START WITH ${unsquashedIdentity.startWith}` : ""}${unsquashedIdentity.cache ? ` CACHE ${unsquashedIdentity.cache}` : ""}${unsquashedIdentity.cycle ? ` CYCLE` : ""})` : "";
        const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated?.as}) STORED` : "";
        return `ALTER TABLE ${tableNameWithSchema} ADD COLUMN "${name}" ${fixedType}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${identityStatement};`;
      }
    };
    MySqlAlterTableAddColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_add_column" && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableName, column: column6 } = statement;
        const {
          name,
          type,
          notNull,
          primaryKey,
          autoincrement,
          onUpdate,
          generated
        } = column6;
        const defaultStatement = `${column6.default !== void 0 ? ` DEFAULT ${column6.default}` : ""}`;
        const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
        const primaryKeyStatement = `${primaryKey ? " PRIMARY KEY" : ""}`;
        const autoincrementStatement = `${autoincrement ? " AUTO_INCREMENT" : ""}`;
        const onUpdateStatement = `${onUpdate ? " ON UPDATE CURRENT_TIMESTAMP" : ""}`;
        const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated?.as}) ${generated?.type.toUpperCase()}` : "";
        return `ALTER TABLE \`${tableName}\` ADD \`${name}\` ${type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${generatedStatement}${notNullStatement}${onUpdateStatement};`;
      }
    };
    SingleStoreAlterTableAddColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_add_column" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableName, column: column6 } = statement;
        const {
          name,
          type,
          notNull,
          primaryKey,
          autoincrement,
          onUpdate,
          generated
        } = column6;
        const defaultStatement = `${column6.default !== void 0 ? ` DEFAULT ${column6.default}` : ""}`;
        const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
        const primaryKeyStatement = `${primaryKey ? " PRIMARY KEY" : ""}`;
        const autoincrementStatement = `${autoincrement ? " AUTO_INCREMENT" : ""}`;
        const onUpdateStatement = `${onUpdate ? " ON UPDATE CURRENT_TIMESTAMP" : ""}`;
        const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated?.as}) ${generated?.type.toUpperCase()}` : "";
        return `ALTER TABLE \`${tableName}\` ADD \`${name}\` ${type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${notNullStatement}${onUpdateStatement}${generatedStatement};`;
      }
    };
    SQLiteAlterTableAddColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "sqlite_alter_table_add_column" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { tableName, column: column6, referenceData } = statement;
        const { name, type, notNull, primaryKey, generated } = column6;
        const defaultStatement = `${column6.default !== void 0 ? ` DEFAULT ${column6.default}` : ""}`;
        const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
        const primaryKeyStatement = `${primaryKey ? " PRIMARY KEY" : ""}`;
        const referenceAsObject = referenceData ? SQLiteSquasher.unsquashFK(referenceData) : void 0;
        const referenceStatement = `${referenceAsObject ? ` REFERENCES ${referenceAsObject.tableTo}(${referenceAsObject.columnsTo})` : ""}`;
        const generatedStatement = generated ? ` GENERATED ALWAYS AS ${generated.as} ${generated.type.toUpperCase()}` : "";
        return `ALTER TABLE \`${tableName}\` ADD \`${name}\` ${type}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${referenceStatement};`;
      }
    };
    PgAlterTableAlterColumnSetTypeConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "pg_alter_table_alter_column_set_type" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, newDataType, schema: schema6, oldDataType, columnDefault, typeSchema } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        const statements = [];
        const type = parseType(`"${typeSchema}".`, newDataType.name);
        if (!oldDataType.isEnum && !newDataType.isEnum) {
          statements.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type};`
          );
          if (columnDefault) {
            statements.push(
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};`
            );
          }
        }
        if (oldDataType.isEnum && !newDataType.isEnum) {
          statements.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type};`
          );
          if (columnDefault) {
            statements.push(
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};`
            );
          }
        }
        if (!oldDataType.isEnum && newDataType.isEnum) {
          if (columnDefault) {
            statements.push(
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault}::${type};`
            );
          }
          statements.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type} USING "${columnName}"::${type};`
          );
        }
        if (oldDataType.isEnum && newDataType.isEnum) {
          const alterType = `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type} USING "${columnName}"::text::${type};`;
          if (newDataType.name !== oldDataType.name && columnDefault) {
            statements.push(
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP DEFAULT;`,
              alterType,
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};`
            );
          } else {
            statements.push(alterType);
          }
        }
        return statements;
      }
    };
    PgAlterTableAlterColumnSetDefaultConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_default" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema6 } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${statement.newDefaultValue};`;
      }
    };
    PgAlterTableAlterColumnDropDefaultConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_default" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema6 } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP DEFAULT;`;
      }
    };
    PgAlterTableAlterColumnDropGeneratedConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_generated" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema6 } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP EXPRESSION;`;
      }
    };
    PgAlterTableAlterColumnSetExpressionConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_generated" && dialect6 === "postgresql";
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema6,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        const addColumnStatement = new PgAlterTableAddColumnConvertor().convert({
          schema: schema6,
          tableName,
          column: {
            name: columnName,
            type: statement.newDataType,
            notNull,
            default: columnDefault,
            onUpdate: columnOnUpdate,
            autoincrement: columnAutoIncrement,
            primaryKey: columnPk,
            generated: columnGenerated
          },
          type: "alter_table_add_column"
        });
        return [
          `ALTER TABLE ${tableNameWithSchema} drop column "${columnName}";`,
          addColumnStatement
        ];
      }
    };
    PgAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "postgresql";
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema6,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        const addColumnStatement = new PgAlterTableAddColumnConvertor().convert({
          schema: schema6,
          tableName,
          column: {
            name: columnName,
            type: statement.newDataType,
            notNull,
            default: columnDefault,
            onUpdate: columnOnUpdate,
            autoincrement: columnAutoIncrement,
            primaryKey: columnPk,
            generated: columnGenerated
          },
          type: "alter_table_add_column"
        });
        return [
          `ALTER TABLE ${tableNameWithSchema} drop column "${columnName}";`,
          addColumnStatement
        ];
      }
    };
    SqliteAlterTableAlterColumnDropGeneratedConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_generated" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema6,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated,
          columnNotNull
        } = statement;
        const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert(
          {
            tableName,
            column: {
              name: columnName,
              type: statement.newDataType,
              notNull: columnNotNull,
              default: columnDefault,
              onUpdate: columnOnUpdate,
              autoincrement: columnAutoIncrement,
              primaryKey: columnPk,
              generated: columnGenerated
            },
            type: "sqlite_alter_table_add_column"
          }
        );
        const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({
          tableName,
          columnName,
          schema: schema6,
          type: "alter_table_drop_column"
        });
        return [dropColumnStatement, addColumnStatement];
      }
    };
    SqliteAlterTableAlterColumnSetExpressionConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_generated" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema6,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert(
          {
            tableName,
            column: {
              name: columnName,
              type: statement.newDataType,
              notNull,
              default: columnDefault,
              onUpdate: columnOnUpdate,
              autoincrement: columnAutoIncrement,
              primaryKey: columnPk,
              generated: columnGenerated
            },
            type: "sqlite_alter_table_add_column"
          }
        );
        const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({
          tableName,
          columnName,
          schema: schema6,
          type: "alter_table_drop_column"
        });
        return [dropColumnStatement, addColumnStatement];
      }
    };
    SqliteAlterTableAlterColumnAlterGeneratedConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_alter_generated" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema6,
          columnNotNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert(
          {
            tableName,
            column: {
              name: columnName,
              type: statement.newDataType,
              notNull: columnNotNull,
              default: columnDefault,
              onUpdate: columnOnUpdate,
              autoincrement: columnAutoIncrement,
              primaryKey: columnPk,
              generated: columnGenerated
            },
            type: "sqlite_alter_table_add_column"
          }
        );
        const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({
          tableName,
          columnName,
          schema: schema6,
          type: "alter_table_drop_column"
        });
        return [dropColumnStatement, addColumnStatement];
      }
    };
    MySqlAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "mysql";
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema6,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const tableNameWithSchema = schema6 ? `\`${schema6}\`.\`${tableName}\`` : `\`${tableName}\``;
        const addColumnStatement = new MySqlAlterTableAddColumnConvertor().convert({
          schema: schema6,
          tableName,
          column: {
            name: columnName,
            type: statement.newDataType,
            notNull,
            default: columnDefault,
            onUpdate: columnOnUpdate,
            autoincrement: columnAutoIncrement,
            primaryKey: columnPk,
            generated: columnGenerated
          },
          type: "alter_table_add_column"
        });
        return [
          `ALTER TABLE ${tableNameWithSchema} drop column \`${columnName}\`;`,
          addColumnStatement
        ];
      }
    };
    MySqlAlterTableAddPk = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_pk" && dialect6 === "mysql";
      }
      convert(statement) {
        return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY (\`${statement.columnName}\`);`;
      }
    };
    MySqlAlterTableDropPk = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_pk" && dialect6 === "mysql";
      }
      convert(statement) {
        return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY`;
      }
    };
    LibSQLModifyColumn = class extends Convertor {
      can(statement, dialect6) {
        return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") && dialect6 === "turso";
      }
      convert(statement, json2) {
        const { tableName, columnName } = statement;
        let columnType = ``;
        let columnDefault = "";
        let columnNotNull = "";
        const sqlStatements = [];
        const indexes = [];
        for (const table6 of Object.values(json2.tables)) {
          for (const index6 of Object.values(table6.indexes)) {
            const unsquashed = SQLiteSquasher.unsquashIdx(index6);
            sqlStatements.push(`DROP INDEX "${unsquashed.name}";`);
            indexes.push({ ...unsquashed, tableName: table6.name });
          }
        }
        switch (statement.type) {
          case "alter_table_alter_column_set_type":
            columnType = ` ${statement.newDataType}`;
            columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
            columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
            break;
          case "alter_table_alter_column_drop_notnull":
            columnType = ` ${statement.newDataType}`;
            columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
            columnNotNull = "";
            break;
          case "alter_table_alter_column_set_notnull":
            columnType = ` ${statement.newDataType}`;
            columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
            columnNotNull = ` NOT NULL`;
            break;
          case "alter_table_alter_column_set_default":
            columnType = ` ${statement.newDataType}`;
            columnDefault = ` DEFAULT ${statement.newDefaultValue}`;
            columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
            break;
          case "alter_table_alter_column_drop_default":
            columnType = ` ${statement.newDataType}`;
            columnDefault = "";
            columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
            break;
        }
        columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault;
        sqlStatements.push(
          `ALTER TABLE \`${tableName}\` ALTER COLUMN "${columnName}" TO "${columnName}"${columnType}${columnNotNull}${columnDefault};`
        );
        for (const index6 of indexes) {
          const indexPart = index6.isUnique ? "UNIQUE INDEX" : "INDEX";
          const whereStatement = index6.where ? ` WHERE ${index6.where}` : "";
          const uniqueString = index6.columns.map((it) => `\`${it}\``).join(",");
          const tableName2 = index6.tableName;
          sqlStatements.push(
            `CREATE ${indexPart} \`${index6.name}\` ON \`${tableName2}\` (${uniqueString})${whereStatement};`
          );
        }
        return sqlStatements;
      }
    };
    MySqlModifyColumn = class extends Convertor {
      can(statement, dialect6) {
        return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_on_update" || statement.type === "alter_table_alter_column_set_on_update" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_generated" || statement.type === "alter_table_alter_column_drop_generated") && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        let columnType = ``;
        let columnDefault = "";
        let columnNotNull = "";
        let columnOnUpdate = "";
        let columnAutoincrement = "";
        let primaryKey = statement.columnPk ? " PRIMARY KEY" : "";
        let columnGenerated = "";
        if (statement.type === "alter_table_alter_column_drop_notnull") {
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_notnull") {
          columnNotNull = ` NOT NULL`;
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_drop_on_update") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnOnUpdate = "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_on_update") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = ` ON UPDATE CURRENT_TIMESTAMP`;
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_autoincrement") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = " AUTO_INCREMENT";
        } else if (statement.type === "alter_table_alter_column_drop_autoincrement") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = "";
        } else if (statement.type === "alter_table_alter_column_set_default") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = ` DEFAULT ${statement.newDefaultValue}`;
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_drop_default") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_generated") {
          columnType = ` ${statement.newDataType}`;
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
          if (statement.columnGenerated?.type === "virtual") {
            return [
              new MySqlAlterTableDropColumnConvertor().convert({
                type: "alter_table_drop_column",
                tableName: statement.tableName,
                columnName: statement.columnName,
                schema: statement.schema
              }),
              new MySqlAlterTableAddColumnConvertor().convert({
                tableName,
                column: {
                  name: columnName,
                  type: statement.newDataType,
                  notNull: statement.columnNotNull,
                  default: statement.columnDefault,
                  onUpdate: statement.columnOnUpdate,
                  autoincrement: statement.columnAutoIncrement,
                  primaryKey: statement.columnPk,
                  generated: statement.columnGenerated
                },
                schema: statement.schema,
                type: "alter_table_add_column"
              })
            ];
          } else {
            columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${statement.columnGenerated?.as}) ${statement.columnGenerated?.type.toUpperCase()}` : "";
          }
        } else if (statement.type === "alter_table_alter_column_drop_generated") {
          columnType = ` ${statement.newDataType}`;
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
          if (statement.oldColumn?.generated?.type === "virtual") {
            return [
              new MySqlAlterTableDropColumnConvertor().convert({
                type: "alter_table_drop_column",
                tableName: statement.tableName,
                columnName: statement.columnName,
                schema: statement.schema
              }),
              new MySqlAlterTableAddColumnConvertor().convert({
                tableName,
                column: {
                  name: columnName,
                  type: statement.newDataType,
                  notNull: statement.columnNotNull,
                  default: statement.columnDefault,
                  onUpdate: statement.columnOnUpdate,
                  autoincrement: statement.columnAutoIncrement,
                  primaryKey: statement.columnPk,
                  generated: statement.columnGenerated
                },
                schema: statement.schema,
                type: "alter_table_add_column"
              })
            ];
          }
        } else {
          columnType = ` ${statement.newDataType}`;
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
          columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${statement.columnGenerated?.as}) ${statement.columnGenerated?.type.toUpperCase()}` : "";
        }
        columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault;
        return `ALTER TABLE \`${tableName}\` MODIFY COLUMN \`${columnName}\`${columnType}${columnAutoincrement}${columnGenerated}${columnNotNull}${columnDefault}${columnOnUpdate};`;
      }
    };
    SingleStoreAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "singlestore";
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema6,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const tableNameWithSchema = schema6 ? `\`${schema6}\`.\`${tableName}\`` : `\`${tableName}\``;
        const addColumnStatement = new SingleStoreAlterTableAddColumnConvertor().convert({
          schema: schema6,
          tableName,
          column: {
            name: columnName,
            type: statement.newDataType,
            notNull,
            default: columnDefault,
            onUpdate: columnOnUpdate,
            autoincrement: columnAutoIncrement,
            primaryKey: columnPk,
            generated: columnGenerated
          },
          type: "alter_table_add_column"
        });
        return [
          `ALTER TABLE ${tableNameWithSchema} drop column \`${columnName}\`;`,
          addColumnStatement
        ];
      }
    };
    SingleStoreAlterTableAddPk = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_pk" && dialect6 === "singlestore";
      }
      convert(statement) {
        return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY (\`${statement.columnName}\`);`;
      }
    };
    SingleStoreAlterTableDropPk = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_pk" && dialect6 === "singlestore";
      }
      convert(statement) {
        return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY`;
      }
    };
    SingleStoreModifyColumn = class extends Convertor {
      can(statement, dialect6) {
        return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_on_update" || statement.type === "alter_table_alter_column_set_on_update" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_generated" || statement.type === "alter_table_alter_column_drop_generated") && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        let columnType = ``;
        let columnDefault = "";
        let columnNotNull = "";
        let columnOnUpdate = "";
        let columnAutoincrement = "";
        let primaryKey = statement.columnPk ? " PRIMARY KEY" : "";
        let columnGenerated = "";
        if (statement.type === "alter_table_alter_column_drop_notnull") {
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_notnull") {
          columnNotNull = ` NOT NULL`;
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_drop_on_update") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnOnUpdate = "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_on_update") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = ` ON UPDATE CURRENT_TIMESTAMP`;
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_autoincrement") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = " AUTO_INCREMENT";
        } else if (statement.type === "alter_table_alter_column_drop_autoincrement") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = "";
        } else if (statement.type === "alter_table_alter_column_set_default") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = ` DEFAULT ${statement.newDefaultValue}`;
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_drop_default") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_generated") {
          columnType = ` ${statement.newDataType}`;
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
          if (statement.columnGenerated?.type === "virtual") {
            return [
              new SingleStoreAlterTableDropColumnConvertor().convert({
                type: "alter_table_drop_column",
                tableName: statement.tableName,
                columnName: statement.columnName,
                schema: statement.schema
              }),
              new SingleStoreAlterTableAddColumnConvertor().convert({
                tableName,
                column: {
                  name: columnName,
                  type: statement.newDataType,
                  notNull: statement.columnNotNull,
                  default: statement.columnDefault,
                  onUpdate: statement.columnOnUpdate,
                  autoincrement: statement.columnAutoIncrement,
                  primaryKey: statement.columnPk,
                  generated: statement.columnGenerated
                },
                schema: statement.schema,
                type: "alter_table_add_column"
              })
            ];
          } else {
            columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${statement.columnGenerated?.as}) ${statement.columnGenerated?.type.toUpperCase()}` : "";
          }
        } else if (statement.type === "alter_table_alter_column_drop_generated") {
          columnType = ` ${statement.newDataType}`;
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
          if (statement.oldColumn?.generated?.type === "virtual") {
            return [
              new SingleStoreAlterTableDropColumnConvertor().convert({
                type: "alter_table_drop_column",
                tableName: statement.tableName,
                columnName: statement.columnName,
                schema: statement.schema
              }),
              new SingleStoreAlterTableAddColumnConvertor().convert({
                tableName,
                column: {
                  name: columnName,
                  type: statement.newDataType,
                  notNull: statement.columnNotNull,
                  default: statement.columnDefault,
                  onUpdate: statement.columnOnUpdate,
                  autoincrement: statement.columnAutoIncrement,
                  primaryKey: statement.columnPk,
                  generated: statement.columnGenerated
                },
                schema: statement.schema,
                type: "alter_table_add_column"
              })
            ];
          }
        } else {
          columnType = ` ${statement.newDataType}`;
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
          columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${statement.columnGenerated?.as}) ${statement.columnGenerated?.type.toUpperCase()}` : "";
        }
        columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault;
        return `ALTER TABLE \`${tableName}\` MODIFY COLUMN \`${columnName}\`${columnType}${columnAutoincrement}${columnNotNull}${columnDefault}${columnOnUpdate}${columnGenerated};`;
      }
    };
    PgAlterTableCreateCompositePrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_composite_pk" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { name, columns } = PgSquasher.unsquashPK(statement.data);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${statement.constraintName}" PRIMARY KEY("${columns.join('","')}");`;
      }
    };
    PgAlterTableDeleteCompositePrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_composite_pk" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { name, columns } = PgSquasher.unsquashPK(statement.data);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${statement.constraintName}";`;
      }
    };
    PgAlterTableAlterCompositePrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_composite_pk" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { name, columns } = PgSquasher.unsquashPK(statement.old);
        const { name: newName, columns: newColumns } = PgSquasher.unsquashPK(
          statement.new
        );
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${statement.oldConstraintName}";
${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${statement.newConstraintName}" PRIMARY KEY("${newColumns.join('","')}");`;
      }
    };
    MySqlAlterTableCreateCompositePrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_composite_pk" && dialect6 === "mysql";
      }
      convert(statement) {
        const { name, columns } = MySqlSquasher.unsquashPK(statement.data);
        return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY(\`${columns.join("`,`")}\`);`;
      }
    };
    MySqlAlterTableDeleteCompositePrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_composite_pk" && dialect6 === "mysql";
      }
      convert(statement) {
        const { name, columns } = MySqlSquasher.unsquashPK(statement.data);
        return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY;`;
      }
    };
    MySqlAlterTableAlterCompositePrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_composite_pk" && dialect6 === "mysql";
      }
      convert(statement) {
        const { name, columns } = MySqlSquasher.unsquashPK(statement.old);
        const { name: newName, columns: newColumns } = MySqlSquasher.unsquashPK(
          statement.new
        );
        return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY, ADD PRIMARY KEY(\`${newColumns.join("`,`")}\`);`;
      }
    };
    PgAlterTableAlterColumnSetPrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_pk" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ADD PRIMARY KEY ("${columnName}");`;
      }
    };
    PgAlterTableAlterColumnDropPrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_pk" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema6 } = statement;
        return `/* 
    Unfortunately in current drizzle-kit version we can't automatically get name for primary key.
    We are working on making it available!

    Meanwhile you can:
        1. Check pk name in your database, by running
            SELECT constraint_name FROM information_schema.table_constraints
            WHERE table_schema = '${typeof schema6 === "undefined" || schema6 === "" ? "public" : schema6}'
                AND table_name = '${tableName}'
                AND constraint_type = 'PRIMARY KEY';
        2. Uncomment code below and paste pk name manually
        
    Hope to release this update as soon as possible
*/

-- ALTER TABLE "${tableName}" DROP CONSTRAINT "<constraint_name>";`;
      }
    };
    PgAlterTableAlterColumnSetNotNullConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_notnull" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET NOT NULL;`;
      }
    };
    PgAlterTableAlterColumnDropNotNullConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_notnull" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP NOT NULL;`;
      }
    };
    PgCreateForeignKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_reference" && dialect6 === "postgresql";
      }
      convert(statement) {
        const {
          name,
          tableFrom,
          tableTo,
          columnsFrom,
          columnsTo,
          onDelete,
          onUpdate,
          schemaTo
        } = PgSquasher.unsquashFK(statement.data);
        const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
        const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
        const fromColumnsString = columnsFrom.map((it) => `"${it}"`).join(",");
        const toColumnsString = columnsTo.map((it) => `"${it}"`).join(",");
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${tableFrom}"` : `"${tableFrom}"`;
        const tableToNameWithSchema = schemaTo ? `"${schemaTo}"."${tableTo}"` : `"${tableTo}"`;
        const alterStatement = `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${name}" FOREIGN KEY (${fromColumnsString}) REFERENCES ${tableToNameWithSchema}(${toColumnsString})${onDeleteStatement}${onUpdateStatement};`;
        return alterStatement;
      }
    };
    LibSQLCreateForeignKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_reference" && dialect6 === "turso";
      }
      convert(statement, json2, action) {
        const { columnsFrom, columnsTo, tableFrom, onDelete, onUpdate, tableTo } = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data);
        const { columnDefault, columnNotNull, columnType } = statement;
        const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
        const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
        const columnsDefaultValue = columnDefault ? ` DEFAULT ${columnDefault}` : "";
        const columnNotNullValue = columnNotNull ? ` NOT NULL` : "";
        const columnTypeValue = columnType ? ` ${columnType}` : "";
        const columnFrom = columnsFrom[0];
        const columnTo = columnsTo[0];
        return `ALTER TABLE \`${tableFrom}\` ALTER COLUMN "${columnFrom}" TO "${columnFrom}"${columnTypeValue}${columnNotNullValue}${columnsDefaultValue} REFERENCES ${tableTo}(${columnTo})${onDeleteStatement}${onUpdateStatement};`;
      }
    };
    MySqlCreateForeignKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_reference" && dialect6 === "mysql";
      }
      convert(statement) {
        const {
          name,
          tableFrom,
          tableTo,
          columnsFrom,
          columnsTo,
          onDelete,
          onUpdate
        } = MySqlSquasher.unsquashFK(statement.data);
        const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
        const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
        const fromColumnsString = columnsFrom.map((it) => `\`${it}\``).join(",");
        const toColumnsString = columnsTo.map((it) => `\`${it}\``).join(",");
        return `ALTER TABLE \`${tableFrom}\` ADD CONSTRAINT \`${name}\` FOREIGN KEY (${fromColumnsString}) REFERENCES \`${tableTo}\`(${toColumnsString})${onDeleteStatement}${onUpdateStatement};`;
      }
    };
    PgAlterForeignKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_reference" && dialect6 === "postgresql";
      }
      convert(statement) {
        const newFk = PgSquasher.unsquashFK(statement.data);
        const oldFk = PgSquasher.unsquashFK(statement.oldFkey);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${oldFk.tableFrom}"` : `"${oldFk.tableFrom}"`;
        let sql = `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${oldFk.name}";
`;
        const onDeleteStatement = newFk.onDelete ? ` ON DELETE ${newFk.onDelete}` : "";
        const onUpdateStatement = newFk.onUpdate ? ` ON UPDATE ${newFk.onUpdate}` : "";
        const fromColumnsString = newFk.columnsFrom.map((it) => `"${it}"`).join(",");
        const toColumnsString = newFk.columnsTo.map((it) => `"${it}"`).join(",");
        const tableFromNameWithSchema = oldFk.schemaTo ? `"${oldFk.schemaTo}"."${oldFk.tableFrom}"` : `"${oldFk.tableFrom}"`;
        const tableToNameWithSchema = newFk.schemaTo ? `"${newFk.schemaTo}"."${newFk.tableFrom}"` : `"${newFk.tableFrom}"`;
        const alterStatement = `ALTER TABLE ${tableFromNameWithSchema} ADD CONSTRAINT "${newFk.name}" FOREIGN KEY (${fromColumnsString}) REFERENCES ${tableToNameWithSchema}(${toColumnsString})${onDeleteStatement}${onUpdateStatement};`;
        sql += alterStatement;
        return sql;
      }
    };
    PgDeleteForeignKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_reference" && dialect6 === "postgresql";
      }
      convert(statement) {
        const tableFrom = statement.tableName;
        const { name } = PgSquasher.unsquashFK(statement.data);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${tableFrom}"` : `"${tableFrom}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${name}";
`;
      }
    };
    MySqlDeleteForeignKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_reference" && dialect6 === "mysql";
      }
      convert(statement) {
        const tableFrom = statement.tableName;
        const { name } = MySqlSquasher.unsquashFK(statement.data);
        return `ALTER TABLE \`${tableFrom}\` DROP FOREIGN KEY \`${name}\`;
`;
      }
    };
    CreatePgIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_index_pg" && dialect6 === "postgresql";
      }
      convert(statement) {
        const {
          name,
          columns,
          isUnique,
          concurrently,
          with: withMap,
          method,
          where
        } = statement.data;
        const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
        const value = columns.map(
          (it) => `${it.isExpression ? it.expression : `"${it.expression}"`}${it.opclass ? ` ${it.opclass}` : it.asc ? "" : " DESC"}${it.asc && it.nulls && it.nulls === "last" || it.opclass ? "" : ` NULLS ${it.nulls.toUpperCase()}`}`
        ).join(",");
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        function reverseLogic(mappedWith) {
          let reversedString = "";
          for (const key in mappedWith) {
            if (mappedWith.hasOwnProperty(key)) {
              reversedString += `${key}=${mappedWith[key]},`;
            }
          }
          reversedString = reversedString.slice(0, -1);
          return reversedString;
        }
        return `CREATE ${indexPart}${concurrently ? " CONCURRENTLY" : ""} "${name}" ON ${tableNameWithSchema} USING ${method} (${value})${Object.keys(withMap).length !== 0 ? ` WITH (${reverseLogic(withMap)})` : ""}${where ? ` WHERE ${where}` : ""};`;
      }
    };
    CreateMySqlIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_index" && dialect6 === "mysql";
      }
      convert(statement) {
        const { name, columns, isUnique } = MySqlSquasher.unsquashIdx(
          statement.data
        );
        const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
        const uniqueString = columns.map((it) => {
          return statement.internal?.indexes ? statement.internal?.indexes[name]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``;
        }).join(",");
        return `CREATE ${indexPart} \`${name}\` ON \`${statement.tableName}\` (${uniqueString});`;
      }
    };
    CreateSingleStoreIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_index" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { name, columns, isUnique } = SingleStoreSquasher.unsquashIdx(
          statement.data
        );
        const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
        const uniqueString = columns.map((it) => {
          return statement.internal?.indexes ? statement.internal?.indexes[name]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``;
        }).join(",");
        return `CREATE ${indexPart} \`${name}\` ON \`${statement.tableName}\` (${uniqueString});`;
      }
    };
    CreateSqliteIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_index" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { name, columns, isUnique, where } = SQLiteSquasher.unsquashIdx(
          statement.data
        );
        const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
        const whereStatement = where ? ` WHERE ${where}` : "";
        const uniqueString = columns.map((it) => {
          return statement.internal?.indexes ? statement.internal?.indexes[name]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``;
        }).join(",");
        return `CREATE ${indexPart} \`${name}\` ON \`${statement.tableName}\` (${uniqueString})${whereStatement};`;
      }
    };
    PgDropIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_index" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { schema: schema6 } = statement;
        const { name } = PgSquasher.unsquashIdx(statement.data);
        const indexNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
        return `DROP INDEX ${indexNameWithSchema};`;
      }
    };
    PgCreateSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_schema" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { name } = statement;
        return `CREATE SCHEMA "${name}";
`;
      }
    };
    PgRenameSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_schema" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { from, to } = statement;
        return `ALTER SCHEMA "${from}" RENAME TO "${to}";
`;
      }
    };
    PgDropSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_schema" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { name } = statement;
        return `DROP SCHEMA "${name}";
`;
      }
    };
    PgAlterTableSetSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_set_schema" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, schemaFrom, schemaTo } = statement;
        return `ALTER TABLE "${schemaFrom}"."${tableName}" SET SCHEMA "${schemaTo}";
`;
      }
    };
    PgAlterTableSetNewSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_set_new_schema" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, to, from } = statement;
        const tableNameWithSchema = from ? `"${from}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} SET SCHEMA "${to}";
`;
      }
    };
    PgAlterTableRemoveFromSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_remove_from_schema" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, schema: schema6 } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} SET SCHEMA public;
`;
      }
    };
    SqliteDropIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_index" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { name } = PgSquasher.unsquashIdx(statement.data);
        return `DROP INDEX \`${name}\`;`;
      }
    };
    MySqlDropIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_index" && dialect6 === "mysql";
      }
      convert(statement) {
        const { name } = MySqlSquasher.unsquashIdx(statement.data);
        return `DROP INDEX \`${name}\` ON \`${statement.tableName}\`;`;
      }
    };
    SingleStoreDropIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_index" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { name } = SingleStoreSquasher.unsquashIdx(statement.data);
        return `DROP INDEX \`${name}\` ON \`${statement.tableName}\`;`;
      }
    };
    SQLiteRecreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "recreate_table" && dialect6 === "sqlite";
      }
      convert(statement) {
        const { tableName, columns, compositePKs, referenceData, checkConstraints } = statement;
        const columnNames = columns.map((it) => `"${it.name}"`).join(", ");
        const newTableName = `__new_${tableName}`;
        const sqlStatements = [];
        sqlStatements.push(`PRAGMA foreign_keys=OFF;`);
        const mappedCheckConstraints = checkConstraints.map(
          (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `'${newTableName}'.`)
        );
        sqlStatements.push(
          new SQLiteCreateTableConvertor().convert({
            type: "sqlite_create_table",
            tableName: newTableName,
            columns,
            referenceData,
            compositePKs,
            checkConstraints: mappedCheckConstraints
          })
        );
        sqlStatements.push(
          `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;`
        );
        sqlStatements.push(
          new SQLiteDropTableConvertor().convert({
            type: "drop_table",
            tableName,
            schema: ""
          })
        );
        sqlStatements.push(
          new SqliteRenameTableConvertor().convert({
            fromSchema: "",
            tableNameFrom: newTableName,
            tableNameTo: tableName,
            toSchema: "",
            type: "rename_table"
          })
        );
        sqlStatements.push(`PRAGMA foreign_keys=ON;`);
        return sqlStatements;
      }
    };
    LibSQLRecreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "recreate_table" && dialect6 === "turso";
      }
      convert(statement) {
        const { tableName, columns, compositePKs, referenceData, checkConstraints } = statement;
        const columnNames = columns.map((it) => `"${it.name}"`).join(", ");
        const newTableName = `__new_${tableName}`;
        const sqlStatements = [];
        const mappedCheckConstraints = checkConstraints.map(
          (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`)
        );
        sqlStatements.push(`PRAGMA foreign_keys=OFF;`);
        sqlStatements.push(
          new SQLiteCreateTableConvertor().convert({
            type: "sqlite_create_table",
            tableName: newTableName,
            columns,
            referenceData,
            compositePKs,
            checkConstraints: mappedCheckConstraints
          })
        );
        sqlStatements.push(
          `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;`
        );
        sqlStatements.push(
          new SQLiteDropTableConvertor().convert({
            type: "drop_table",
            tableName,
            schema: ""
          })
        );
        sqlStatements.push(
          new SqliteRenameTableConvertor().convert({
            fromSchema: "",
            tableNameFrom: newTableName,
            tableNameTo: tableName,
            toSchema: "",
            type: "rename_table"
          })
        );
        sqlStatements.push(`PRAGMA foreign_keys=ON;`);
        return sqlStatements;
      }
    };
    SingleStoreRecreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "singlestore_recreate_table" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableName, columns, compositePKs, uniqueConstraints } = statement;
        const columnNames = columns.map((it) => `\`${it.name}\``).join(", ");
        const newTableName = `__new_${tableName}`;
        const sqlStatements = [];
        sqlStatements.push(
          new SingleStoreCreateTableConvertor().convert({
            type: "create_table",
            tableName: newTableName,
            columns,
            compositePKs,
            uniqueConstraints,
            schema: ""
          })
        );
        sqlStatements.push(
          `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;`
        );
        sqlStatements.push(
          new SingleStoreDropTableConvertor().convert({
            type: "drop_table",
            tableName,
            schema: ""
          })
        );
        sqlStatements.push(
          new SingleStoreRenameTableConvertor().convert({
            fromSchema: "",
            tableNameFrom: newTableName,
            tableNameTo: tableName,
            toSchema: "",
            type: "rename_table"
          })
        );
        return sqlStatements;
      }
    };
    convertors = [];
    convertors.push(new PgCreateTableConvertor());
    convertors.push(new MySqlCreateTableConvertor());
    convertors.push(new SingleStoreCreateTableConvertor());
    convertors.push(new SingleStoreRecreateTableConvertor());
    convertors.push(new SQLiteCreateTableConvertor());
    convertors.push(new SQLiteRecreateTableConvertor());
    convertors.push(new LibSQLRecreateTableConvertor());
    convertors.push(new PgCreateViewConvertor());
    convertors.push(new PgDropViewConvertor());
    convertors.push(new PgRenameViewConvertor());
    convertors.push(new PgAlterViewSchemaConvertor());
    convertors.push(new PgAlterViewAddWithOptionConvertor());
    convertors.push(new PgAlterViewDropWithOptionConvertor());
    convertors.push(new PgAlterViewAlterTablespaceConvertor());
    convertors.push(new PgAlterViewAlterUsingConvertor());
    convertors.push(new MySqlCreateViewConvertor());
    convertors.push(new MySqlDropViewConvertor());
    convertors.push(new MySqlRenameViewConvertor());
    convertors.push(new MySqlAlterViewConvertor());
    convertors.push(new SqliteCreateViewConvertor());
    convertors.push(new SqliteDropViewConvertor());
    convertors.push(new CreateTypeEnumConvertor());
    convertors.push(new DropTypeEnumConvertor());
    convertors.push(new AlterTypeAddValueConvertor());
    convertors.push(new AlterTypeSetSchemaConvertor());
    convertors.push(new AlterRenameTypeConvertor());
    convertors.push(new AlterTypeDropValueConvertor());
    convertors.push(new CreatePgSequenceConvertor());
    convertors.push(new DropPgSequenceConvertor());
    convertors.push(new RenamePgSequenceConvertor());
    convertors.push(new MovePgSequenceConvertor());
    convertors.push(new AlterPgSequenceConvertor());
    convertors.push(new PgDropTableConvertor());
    convertors.push(new MySQLDropTableConvertor());
    convertors.push(new SingleStoreDropTableConvertor());
    convertors.push(new SQLiteDropTableConvertor());
    convertors.push(new PgRenameTableConvertor());
    convertors.push(new MySqlRenameTableConvertor());
    convertors.push(new SingleStoreRenameTableConvertor());
    convertors.push(new SqliteRenameTableConvertor());
    convertors.push(new PgAlterTableRenameColumnConvertor());
    convertors.push(new MySqlAlterTableRenameColumnConvertor());
    convertors.push(new SingleStoreAlterTableRenameColumnConvertor());
    convertors.push(new SQLiteAlterTableRenameColumnConvertor());
    convertors.push(new PgAlterTableDropColumnConvertor());
    convertors.push(new MySqlAlterTableDropColumnConvertor());
    convertors.push(new SingleStoreAlterTableDropColumnConvertor());
    convertors.push(new SQLiteAlterTableDropColumnConvertor());
    convertors.push(new PgAlterTableAddColumnConvertor());
    convertors.push(new MySqlAlterTableAddColumnConvertor());
    convertors.push(new SingleStoreAlterTableAddColumnConvertor());
    convertors.push(new SQLiteAlterTableAddColumnConvertor());
    convertors.push(new PgAlterTableAlterColumnSetTypeConvertor());
    convertors.push(new PgAlterTableAddUniqueConstraintConvertor());
    convertors.push(new PgAlterTableDropUniqueConstraintConvertor());
    convertors.push(new PgAlterTableAddCheckConstraintConvertor());
    convertors.push(new PgAlterTableDeleteCheckConstraintConvertor());
    convertors.push(new MySqlAlterTableAddCheckConstraintConvertor());
    convertors.push(new MySqlAlterTableDeleteCheckConstraintConvertor());
    convertors.push(new MySQLAlterTableAddUniqueConstraintConvertor());
    convertors.push(new MySQLAlterTableDropUniqueConstraintConvertor());
    convertors.push(new SingleStoreAlterTableAddUniqueConstraintConvertor());
    convertors.push(new SingleStoreAlterTableDropUniqueConstraintConvertor());
    convertors.push(new CreatePgIndexConvertor());
    convertors.push(new CreateMySqlIndexConvertor());
    convertors.push(new CreateSingleStoreIndexConvertor());
    convertors.push(new CreateSqliteIndexConvertor());
    convertors.push(new PgDropIndexConvertor());
    convertors.push(new SqliteDropIndexConvertor());
    convertors.push(new MySqlDropIndexConvertor());
    convertors.push(new SingleStoreDropIndexConvertor());
    convertors.push(new PgAlterTableAlterColumnSetPrimaryKeyConvertor());
    convertors.push(new PgAlterTableAlterColumnDropPrimaryKeyConvertor());
    convertors.push(new PgAlterTableAlterColumnSetNotNullConvertor());
    convertors.push(new PgAlterTableAlterColumnDropNotNullConvertor());
    convertors.push(new PgAlterTableAlterColumnSetDefaultConvertor());
    convertors.push(new PgAlterTableAlterColumnDropDefaultConvertor());
    convertors.push(new PgAlterPolicyConvertor());
    convertors.push(new PgCreatePolicyConvertor());
    convertors.push(new PgDropPolicyConvertor());
    convertors.push(new PgRenamePolicyConvertor());
    convertors.push(new PgAlterIndPolicyConvertor());
    convertors.push(new PgCreateIndPolicyConvertor());
    convertors.push(new PgDropIndPolicyConvertor());
    convertors.push(new PgRenameIndPolicyConvertor());
    convertors.push(new PgEnableRlsConvertor());
    convertors.push(new PgDisableRlsConvertor());
    convertors.push(new PgDropRoleConvertor());
    convertors.push(new PgAlterRoleConvertor());
    convertors.push(new PgCreateRoleConvertor());
    convertors.push(new PgRenameRoleConvertor());
    convertors.push(new PgAlterTableAlterColumnSetExpressionConvertor());
    convertors.push(new PgAlterTableAlterColumnDropGeneratedConvertor());
    convertors.push(new PgAlterTableAlterColumnAlterrGeneratedConvertor());
    convertors.push(new MySqlAlterTableAlterColumnAlterrGeneratedConvertor());
    convertors.push(new SingleStoreAlterTableAlterColumnAlterrGeneratedConvertor());
    convertors.push(new SqliteAlterTableAlterColumnDropGeneratedConvertor());
    convertors.push(new SqliteAlterTableAlterColumnAlterGeneratedConvertor());
    convertors.push(new SqliteAlterTableAlterColumnSetExpressionConvertor());
    convertors.push(new MySqlModifyColumn());
    convertors.push(new LibSQLModifyColumn());
    convertors.push(new SingleStoreModifyColumn());
    convertors.push(new PgCreateForeignKeyConvertor());
    convertors.push(new MySqlCreateForeignKeyConvertor());
    convertors.push(new PgAlterForeignKeyConvertor());
    convertors.push(new PgDeleteForeignKeyConvertor());
    convertors.push(new MySqlDeleteForeignKeyConvertor());
    convertors.push(new PgCreateSchemaConvertor());
    convertors.push(new PgRenameSchemaConvertor());
    convertors.push(new PgDropSchemaConvertor());
    convertors.push(new PgAlterTableSetSchemaConvertor());
    convertors.push(new PgAlterTableSetNewSchemaConvertor());
    convertors.push(new PgAlterTableRemoveFromSchemaConvertor());
    convertors.push(new LibSQLCreateForeignKeyConvertor());
    convertors.push(new PgAlterTableAlterColumnDropGenerated());
    convertors.push(new PgAlterTableAlterColumnSetGenerated());
    convertors.push(new PgAlterTableAlterColumnAlterGenerated());
    convertors.push(new PgAlterTableCreateCompositePrimaryKeyConvertor());
    convertors.push(new PgAlterTableDeleteCompositePrimaryKeyConvertor());
    convertors.push(new PgAlterTableAlterCompositePrimaryKeyConvertor());
    convertors.push(new MySqlAlterTableDeleteCompositePrimaryKeyConvertor());
    convertors.push(new MySqlAlterTableDropPk());
    convertors.push(new MySqlAlterTableCreateCompositePrimaryKeyConvertor());
    convertors.push(new MySqlAlterTableAddPk());
    convertors.push(new MySqlAlterTableAlterCompositePrimaryKeyConvertor());
    convertors.push(new SingleStoreAlterTableDropPk());
    convertors.push(new SingleStoreAlterTableAddPk());
    https: `
create table users (
	id int,
    name character varying(128)
);

create type venum as enum('one', 'two', 'three');
alter table users add column typed venum;

insert into users(id, name, typed) values (1, 'name1', 'one');
insert into users(id, name, typed) values (2, 'name2', 'two');
insert into users(id, name, typed) values (3, 'name3', 'three');

alter type venum rename to __venum;
create type venum as enum ('one', 'two', 'three', 'four', 'five');

ALTER TABLE users ALTER COLUMN typed TYPE venum USING typed::text::venum;

insert into users(id, name, typed) values (4, 'name4', 'four');
insert into users(id, name, typed) values (5, 'name5', 'five');

drop type __venum;
`;
  }
});

// src/cli/commands/sqlitePushUtils.ts
var _moveDataStatements, getOldTableName, getNewTableName, logSuggestionsAndReturn;
var init_sqlitePushUtils = __esm({
  "src/cli/commands/sqlitePushUtils.ts"() {
    "use strict";
    init_source();
    init_sqliteSchema();
    init_sqlgenerator();
    init_utils();
    _moveDataStatements = (tableName, json, dataLoss = false) => {
      const statements = [];
      const newTableName = `__new_${tableName}`;
      const tableColumns = Object.values(json.tables[tableName].columns);
      const referenceData = Object.values(json.tables[tableName].foreignKeys);
      const compositePKs = Object.values(
        json.tables[tableName].compositePrimaryKeys
      ).map((it) => SQLiteSquasher.unsquashPK(it));
      const checkConstraints = Object.values(json.tables[tableName].checkConstraints);
      const mappedCheckConstraints = checkConstraints.map(
        (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`)
      );
      const fks = referenceData.map((it) => SQLiteSquasher.unsquashPushFK(it));
      statements.push(
        new SQLiteCreateTableConvertor().convert({
          type: "sqlite_create_table",
          tableName: newTableName,
          columns: tableColumns,
          referenceData: fks,
          compositePKs,
          checkConstraints: mappedCheckConstraints
        })
      );
      if (!dataLoss) {
        const columns = Object.keys(json.tables[tableName].columns).map(
          (c5) => `"${c5}"`
        );
        statements.push(
          `INSERT INTO \`${newTableName}\`(${columns.join(
            ", "
          )}) SELECT ${columns.join(", ")} FROM \`${tableName}\`;`
        );
      }
      statements.push(
        new SQLiteDropTableConvertor().convert({
          type: "drop_table",
          tableName,
          schema: ""
        })
      );
      statements.push(
        new SqliteRenameTableConvertor().convert({
          fromSchema: "",
          tableNameFrom: newTableName,
          tableNameTo: tableName,
          toSchema: "",
          type: "rename_table"
        })
      );
      for (const idx of Object.values(json.tables[tableName].indexes)) {
        statements.push(
          new CreateSqliteIndexConvertor().convert({
            type: "create_index",
            tableName,
            schema: "",
            data: idx
          })
        );
      }
      return statements;
    };
    getOldTableName = (tableName, meta) => {
      for (const key of Object.keys(meta.tables)) {
        const value = meta.tables[key];
        if (`"${tableName}"` === value) {
          return key.substring(1, key.length - 1);
        }
      }
      return tableName;
    };
    getNewTableName = (tableName, meta) => {
      if (typeof meta.tables[`"${tableName}"`] !== "undefined") {
        return meta.tables[`"${tableName}"`].substring(
          1,
          meta.tables[`"${tableName}"`].length - 1
        );
      }
      return tableName;
    };
    logSuggestionsAndReturn = async (connection, statements, json1, json2, meta) => {
      let shouldAskForApprove = false;
      const statementsToExecute = [];
      const infoToPrint = [];
      const tablesToRemove = [];
      const columnsToRemove = [];
      const schemasToRemove = [];
      const tablesToTruncate = [];
      for (const statement of statements) {
        if (statement.type === "drop_table") {
          const res = await connection.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.tableName
              )} table with ${count} items`
            );
            tablesToRemove.push(statement.tableName);
            shouldAskForApprove = true;
          }
          const fromJsonStatement = fromJson([statement], "sqlite", "push");
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        } else if (statement.type === "alter_table_drop_column") {
          const tableName = statement.tableName;
          const columnName = statement.columnName;
          const res = await connection.query(
            `select count(\`${tableName}\`.\`${columnName}\`) as count from \`${tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                columnName
              )} column in ${tableName} table with ${count} items`
            );
            columnsToRemove.push(`${tableName}_${statement.columnName}`);
            shouldAskForApprove = true;
          }
          const fromJsonStatement = fromJson([statement], "sqlite", "push");
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        } else if (statement.type === "sqlite_alter_table_add_column" && (statement.column.notNull && !statement.column.default)) {
          const tableName = statement.tableName;
          const columnName = statement.column.name;
          const res = await connection.query(
            `select count(*) as count from \`${tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to add not-null ${source_default.underline(
                columnName
              )} column without default value, which contains ${count} items`
            );
            tablesToTruncate.push(tableName);
            statementsToExecute.push(`delete from ${tableName};`);
            shouldAskForApprove = true;
          }
          const fromJsonStatement = fromJson([statement], "sqlite", "push");
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        } else if (statement.type === "recreate_table") {
          const tableName = statement.tableName;
          const oldTableName = getOldTableName(tableName, meta);
          let dataLoss = false;
          const prevColumnNames = Object.keys(json1.tables[oldTableName].columns);
          const currentColumnNames = Object.keys(json2.tables[tableName].columns);
          const { removedColumns, addedColumns } = findAddedAndRemoved(
            prevColumnNames,
            currentColumnNames
          );
          if (removedColumns.length) {
            for (const removedColumn of removedColumns) {
              const res = await connection.query(
                `select count(\`${tableName}\`.\`${removedColumn}\`) as count from \`${tableName}\``
              );
              const count = Number(res[0].count);
              if (count > 0) {
                infoToPrint.push(
                  `\xB7 You're about to delete ${source_default.underline(
                    removedColumn
                  )} column in ${tableName} table with ${count} items`
                );
                columnsToRemove.push(removedColumn);
                shouldAskForApprove = true;
              }
            }
          }
          if (addedColumns.length) {
            for (const addedColumn of addedColumns) {
              const [res] = await connection.query(
                `select count(*) as count from \`${tableName}\``
              );
              const columnConf = json2.tables[tableName].columns[addedColumn];
              const count = Number(res.count);
              if (count > 0 && columnConf.notNull && !columnConf.default) {
                dataLoss = true;
                infoToPrint.push(
                  `\xB7 You're about to add not-null ${source_default.underline(
                    addedColumn
                  )} column without default value to table, which contains ${count} items`
                );
                shouldAskForApprove = true;
                tablesToTruncate.push(tableName);
                statementsToExecute.push(`DELETE FROM \`${tableName}\`;`);
              }
            }
          }
          const tablesReferencingCurrent = [];
          for (const table6 of Object.values(json2.tables)) {
            const tablesRefs = Object.values(json2.tables[table6.name].foreignKeys).filter((t6) => SQLiteSquasher.unsquashPushFK(t6).tableTo === tableName).map((it) => SQLiteSquasher.unsquashPushFK(it).tableFrom);
            tablesReferencingCurrent.push(...tablesRefs);
          }
          if (!tablesReferencingCurrent.length) {
            statementsToExecute.push(..._moveDataStatements(tableName, json2, dataLoss));
            continue;
          }
          const [{ foreign_keys: pragmaState }] = await connection.query(`PRAGMA foreign_keys;`);
          if (pragmaState) {
            statementsToExecute.push(`PRAGMA foreign_keys=OFF;`);
          }
          statementsToExecute.push(..._moveDataStatements(tableName, json2, dataLoss));
          if (pragmaState) {
            statementsToExecute.push(`PRAGMA foreign_keys=ON;`);
          }
        } else {
          const fromJsonStatement = fromJson([statement], "sqlite", "push");
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        }
      }
      return {
        statementsToExecute,
        shouldAskForApprove,
        infoToPrint,
        columnsToRemove: [...new Set(columnsToRemove)],
        schemasToRemove: [...new Set(schemasToRemove)],
        tablesToTruncate: [...new Set(tablesToTruncate)],
        tablesToRemove: [...new Set(tablesToRemove)]
      };
    };
  }
});

// src/jsonStatements.ts
var preparePgCreateTableJson, prepareMySqlCreateTableJson, prepareSingleStoreCreateTableJson, prepareSQLiteCreateTable, prepareDropTableJson, prepareRenameTableJson, prepareCreateEnumJson, prepareAddValuesToEnumJson, prepareDropEnumValues, prepareDropEnumJson, prepareMoveEnumJson, prepareRenameEnumJson, prepareCreateSequenceJson, prepareAlterSequenceJson, prepareDropSequenceJson, prepareMoveSequenceJson, prepareRenameSequenceJson, prepareCreateRoleJson, prepareAlterRoleJson, prepareDropRoleJson, prepareRenameRoleJson, prepareCreateSchemasJson, prepareRenameSchemasJson, prepareDeleteSchemasJson, prepareRenameColumns, _prepareDropColumns, _prepareAddColumns, _prepareSqliteAddColumns, prepareAlterColumnsMysql, preparePgAlterColumns, prepareSqliteAlterColumns, prepareRenamePolicyJsons, prepareRenameIndPolicyJsons, prepareCreatePolicyJsons, prepareCreateIndPolicyJsons, prepareDropPolicyJsons, prepareDropIndPolicyJsons, prepareAlterPolicyJson, prepareAlterIndPolicyJson, preparePgCreateIndexesJson, prepareCreateIndexesJson, prepareCreateReferencesJson, prepareLibSQLCreateReferencesJson, prepareDropReferencesJson, prepareLibSQLDropReferencesJson, prepareAlterReferencesJson, prepareDropIndexesJson, prepareAddCompositePrimaryKeySqlite, prepareDeleteCompositePrimaryKeySqlite, prepareAlterCompositePrimaryKeySqlite, prepareAddCompositePrimaryKeyPg, prepareDeleteCompositePrimaryKeyPg, prepareAlterCompositePrimaryKeyPg, prepareAddUniqueConstraintPg, prepareDeleteUniqueConstraintPg, prepareAddCheckConstraint, prepareDeleteCheckConstraint, prepareAddCompositePrimaryKeyMySql, prepareDeleteCompositePrimaryKeyMySql, prepareAlterCompositePrimaryKeyMySql, preparePgCreateViewJson, prepareMySqlCreateViewJson, prepareSqliteCreateViewJson, prepareDropViewJson, prepareRenameViewJson, preparePgAlterViewAlterSchemaJson, preparePgAlterViewAddWithOptionJson, preparePgAlterViewDropWithOptionJson, preparePgAlterViewAlterTablespaceJson, preparePgAlterViewAlterUsingJson, prepareMySqlAlterView;
var init_jsonStatements = __esm({
  "src/jsonStatements.ts"() {
    "use strict";
    init_source();
    init_sqlitePushUtils();
    init_views();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    preparePgCreateTableJson = (table6, json2) => {
      const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints, policies, isRLSEnabled } = table6;
      const tableKey2 = `${schema6 || "public"}.${name}`;
      const compositePkName = Object.values(compositePrimaryKeys).length > 0 ? json2.tables[tableKey2].compositePrimaryKeys[`${PgSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name}`].name : "";
      return {
        type: "create_table",
        tableName: name,
        schema: schema6,
        columns: Object.values(columns),
        compositePKs: Object.values(compositePrimaryKeys),
        compositePkName,
        uniqueConstraints: Object.values(uniqueConstraints),
        policies: Object.values(policies),
        checkConstraints: Object.values(checkConstraints),
        isRLSEnabled: isRLSEnabled ?? false
      };
    };
    prepareMySqlCreateTableJson = (table6, json2, internals) => {
      const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints } = table6;
      return {
        type: "create_table",
        tableName: name,
        schema: schema6,
        columns: Object.values(columns),
        compositePKs: Object.values(compositePrimaryKeys),
        compositePkName: Object.values(compositePrimaryKeys).length > 0 ? json2.tables[name].compositePrimaryKeys[MySqlSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name].name : "",
        uniqueConstraints: Object.values(uniqueConstraints),
        internals,
        checkConstraints: Object.values(checkConstraints)
      };
    };
    prepareSingleStoreCreateTableJson = (table6, json2, internals) => {
      const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints } = table6;
      return {
        type: "create_table",
        tableName: name,
        schema: schema6,
        columns: Object.values(columns),
        compositePKs: Object.values(compositePrimaryKeys),
        compositePkName: Object.values(compositePrimaryKeys).length > 0 ? json2.tables[name].compositePrimaryKeys[SingleStoreSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name].name : "",
        uniqueConstraints: Object.values(uniqueConstraints),
        internals
      };
    };
    prepareSQLiteCreateTable = (table6, action) => {
      const { name, columns, uniqueConstraints, checkConstraints } = table6;
      const references2 = Object.values(table6.foreignKeys);
      const composites = Object.values(table6.compositePrimaryKeys).map(
        (it) => SQLiteSquasher.unsquashPK(it)
      );
      const fks = references2.map(
        (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it)
      );
      return {
        type: "sqlite_create_table",
        tableName: name,
        columns: Object.values(columns),
        referenceData: fks,
        compositePKs: composites,
        uniqueConstraints: Object.values(uniqueConstraints),
        checkConstraints: Object.values(checkConstraints)
      };
    };
    prepareDropTableJson = (table6) => {
      return {
        type: "drop_table",
        tableName: table6.name,
        schema: table6.schema,
        policies: table6.policies ? Object.values(table6.policies) : []
      };
    };
    prepareRenameTableJson = (tableFrom, tableTo) => {
      return {
        type: "rename_table",
        fromSchema: tableTo.schema,
        toSchema: tableTo.schema,
        tableNameFrom: tableFrom.name,
        tableNameTo: tableTo.name
      };
    };
    prepareCreateEnumJson = (name, schema6, values) => {
      return {
        type: "create_type_enum",
        name,
        schema: schema6,
        values
      };
    };
    prepareAddValuesToEnumJson = (name, schema6, values) => {
      return values.map((it) => {
        return {
          type: "alter_type_add_value",
          name,
          schema: schema6,
          value: it.value,
          before: it.before
        };
      });
    };
    prepareDropEnumValues = (name, schema6, removedValues, json2) => {
      if (!removedValues.length) return [];
      const affectedColumns = [];
      for (const tableKey2 in json2.tables) {
        const table6 = json2.tables[tableKey2];
        for (const columnKey in table6.columns) {
          const column6 = table6.columns[columnKey];
          const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g;
          const parsedColumnType = column6.type.replace(arrayDefinitionRegex, "");
          if (parsedColumnType === name && column6.typeSchema === schema6) {
            affectedColumns.push({
              tableSchema: table6.schema,
              table: table6.name,
              column: column6.name,
              columnType: column6.type,
              default: column6.default
            });
          }
        }
      }
      return [{
        type: "alter_type_drop_value",
        name,
        enumSchema: schema6,
        deletedValues: removedValues,
        newValues: json2.enums[`${schema6}.${name}`].values,
        columnsWithEnum: affectedColumns
      }];
    };
    prepareDropEnumJson = (name, schema6) => {
      return {
        type: "drop_type_enum",
        name,
        schema: schema6
      };
    };
    prepareMoveEnumJson = (name, schemaFrom, schemaTo) => {
      return {
        type: "move_type_enum",
        name,
        schemaFrom,
        schemaTo
      };
    };
    prepareRenameEnumJson = (nameFrom, nameTo, schema6) => {
      return {
        type: "rename_type_enum",
        nameFrom,
        nameTo,
        schema: schema6
      };
    };
    prepareCreateSequenceJson = (seq) => {
      const values = PgSquasher.unsquashSequence(seq.values);
      return {
        type: "create_sequence",
        name: seq.name,
        schema: seq.schema,
        values
      };
    };
    prepareAlterSequenceJson = (seq) => {
      const values = PgSquasher.unsquashSequence(seq.values);
      return [
        {
          type: "alter_sequence",
          schema: seq.schema,
          name: seq.name,
          values
        }
      ];
    };
    prepareDropSequenceJson = (name, schema6) => {
      return {
        type: "drop_sequence",
        name,
        schema: schema6
      };
    };
    prepareMoveSequenceJson = (name, schemaFrom, schemaTo) => {
      return {
        type: "move_sequence",
        name,
        schemaFrom,
        schemaTo
      };
    };
    prepareRenameSequenceJson = (nameFrom, nameTo, schema6) => {
      return {
        type: "rename_sequence",
        nameFrom,
        nameTo,
        schema: schema6
      };
    };
    prepareCreateRoleJson = (role) => {
      return {
        type: "create_role",
        name: role.name,
        values: {
          createDb: role.createDb,
          createRole: role.createRole,
          inherit: role.inherit
        }
      };
    };
    prepareAlterRoleJson = (role) => {
      return {
        type: "alter_role",
        name: role.name,
        values: {
          createDb: role.createDb,
          createRole: role.createRole,
          inherit: role.inherit
        }
      };
    };
    prepareDropRoleJson = (name) => {
      return {
        type: "drop_role",
        name
      };
    };
    prepareRenameRoleJson = (nameFrom, nameTo) => {
      return {
        type: "rename_role",
        nameFrom,
        nameTo
      };
    };
    prepareCreateSchemasJson = (values) => {
      return values.map((it) => {
        return {
          type: "create_schema",
          name: it
        };
      });
    };
    prepareRenameSchemasJson = (values) => {
      return values.map((it) => {
        return {
          type: "rename_schema",
          from: it.from,
          to: it.to
        };
      });
    };
    prepareDeleteSchemasJson = (values) => {
      return values.map((it) => {
        return {
          type: "drop_schema",
          name: it
        };
      });
    };
    prepareRenameColumns = (tableName, schema6, pairs) => {
      return pairs.map((it) => {
        return {
          type: "alter_table_rename_column",
          tableName,
          oldColumnName: it.from.name,
          newColumnName: it.to.name,
          schema: schema6
        };
      });
    };
    _prepareDropColumns = (taleName, schema6, columns) => {
      return columns.map((it) => {
        return {
          type: "alter_table_drop_column",
          tableName: taleName,
          columnName: it.name,
          schema: schema6
        };
      });
    };
    _prepareAddColumns = (tableName, schema6, columns) => {
      return columns.map((it) => {
        return {
          type: "alter_table_add_column",
          tableName,
          column: it,
          schema: schema6
        };
      });
    };
    _prepareSqliteAddColumns = (tableName, columns, referenceData) => {
      const unsquashed = referenceData.map((addedFkValue) => SQLiteSquasher.unsquashFK(addedFkValue));
      return columns.map((it) => {
        const columnsWithReference = unsquashed.find((t6) => t6.columnsFrom.includes(it.name));
        if (it.generated?.type === "stored") {
          warning(
            `As SQLite docs mention: "It is not possible to ALTER TABLE ADD COLUMN a STORED column. One can add a VIRTUAL column, however", source: "https://www.sqlite.org/gencol.html"`
          );
          return void 0;
        }
        return {
          type: "sqlite_alter_table_add_column",
          tableName,
          column: it,
          referenceData: columnsWithReference ? SQLiteSquasher.squashFK(columnsWithReference) : void 0
        };
      }).filter(Boolean);
    };
    prepareAlterColumnsMysql = (tableName, schema6, columns, json1, json2, action) => {
      let statements = [];
      let dropPkStatements = [];
      let setPkStatements = [];
      for (const column6 of columns) {
        const columnName = typeof column6.name !== "string" ? column6.name.new : column6.name;
        const table6 = json2.tables[tableName];
        const snapshotColumn = table6.columns[columnName];
        const columnType = snapshotColumn.type;
        const columnDefault = snapshotColumn.default;
        const columnOnUpdate = "onUpdate" in snapshotColumn ? snapshotColumn.onUpdate : void 0;
        const columnNotNull = table6.columns[columnName].notNull;
        const columnAutoIncrement = "autoincrement" in snapshotColumn ? snapshotColumn.autoincrement ?? false : false;
        const columnPk = table6.columns[columnName].primaryKey;
        if (column6.autoincrement?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_autoincrement",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.autoincrement?.type === "changed") {
          const type = column6.autoincrement.new ? "alter_table_alter_column_set_autoincrement" : "alter_table_alter_column_drop_autoincrement";
          statements.push({
            type,
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.autoincrement?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_autoincrement",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
      }
      for (const column6 of columns) {
        const columnName = typeof column6.name !== "string" ? column6.name.new : column6.name;
        const columnType = json2.tables[tableName].columns[columnName].type;
        const columnDefault = json2.tables[tableName].columns[columnName].default;
        const columnGenerated = json2.tables[tableName].columns[columnName].generated;
        const columnOnUpdate = json2.tables[tableName].columns[columnName].onUpdate;
        const columnNotNull = json2.tables[tableName].columns[columnName].notNull;
        const columnAutoIncrement = json2.tables[tableName].columns[columnName].autoincrement;
        const columnPk = json2.tables[tableName].columns[columnName].primaryKey;
        const compositePk = json2.tables[tableName].compositePrimaryKeys[`${tableName}_${columnName}`];
        if (typeof column6.name !== "string") {
          statements.push({
            type: "alter_table_rename_column",
            tableName,
            oldColumnName: column6.name.old,
            newColumnName: column6.name.new,
            schema: schema6
          });
        }
        if (column6.type?.type === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_type",
            tableName,
            columnName,
            newDataType: column6.type.new,
            oldDataType: column6.type.old,
            schema: schema6,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (column6.primaryKey?.type === "deleted" || column6.primaryKey?.type === "changed" && !column6.primaryKey.new && typeof compositePk === "undefined") {
          dropPkStatements.push({
            ////
            type: "alter_table_alter_column_drop_pk",
            tableName,
            columnName,
            schema: schema6
          });
        }
        if (column6.default?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column6.default.value,
            schema: schema6,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (column6.default?.type === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column6.default.new,
            oldDefaultValue: column6.default.old,
            schema: schema6,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (column6.default?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_default",
            tableName,
            columnName,
            schema: schema6,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (column6.notNull?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_notnull",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.notNull?.type === "changed") {
          const type = column6.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull";
          statements.push({
            type,
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.notNull?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_notnull",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.generated?.type === "added") {
          if (columnGenerated?.type === "virtual") {
            warning(
              `You are trying to add virtual generated constraint to ${source_default.blue(
                columnName
              )} column. As MySQL docs mention: "Nongenerated columns can be altered to stored but not virtual generated columns". We will drop an existing column and add it with a virtual generated statement. This means that the data previously stored in this column will be wiped, and new data will be generated on each read for this column
`
            );
          }
          statements.push({
            type: "alter_table_alter_column_set_generated",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (column6.generated?.type === "changed" && action !== "push") {
          statements.push({
            type: "alter_table_alter_column_alter_generated",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (column6.generated?.type === "deleted") {
          if (columnGenerated?.type === "virtual") {
            warning(
              `You are trying to remove virtual generated constraint from ${source_default.blue(
                columnName
              )} column. As MySQL docs mention: "Stored but not virtual generated columns can be altered to nongenerated columns. The stored generated values become the values of the nongenerated column". We will drop an existing column and add it without a virtual generated statement. This means that this column will have no data after migration
`
            );
          }
          statements.push({
            type: "alter_table_alter_column_drop_generated",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated,
            oldColumn: json1.tables[tableName].columns[columnName]
          });
        }
        if (column6.primaryKey?.type === "added" || column6.primaryKey?.type === "changed" && column6.primaryKey.new) {
          const wasAutoincrement = statements.filter(
            (it) => it.type === "alter_table_alter_column_set_autoincrement"
          );
          if (wasAutoincrement.length === 0) {
            setPkStatements.push({
              type: "alter_table_alter_column_set_pk",
              tableName,
              schema: schema6,
              columnName
            });
          }
        }
        if (column6.onUpdate?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_on_update",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.onUpdate?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_on_update",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
      }
      return [...dropPkStatements, ...setPkStatements, ...statements];
    };
    preparePgAlterColumns = (_tableName, schema6, columns, json2, json1, action) => {
      const tableKey2 = `${schema6 || "public"}.${_tableName}`;
      let statements = [];
      let dropPkStatements = [];
      let setPkStatements = [];
      for (const column6 of columns) {
        const columnName = typeof column6.name !== "string" ? column6.name.new : column6.name;
        const tableName = json2.tables[tableKey2].name;
        const columnType = json2.tables[tableKey2].columns[columnName].type;
        const columnDefault = json2.tables[tableKey2].columns[columnName].default;
        const columnGenerated = json2.tables[tableKey2].columns[columnName].generated;
        const columnOnUpdate = json2.tables[tableKey2].columns[columnName].onUpdate;
        const columnNotNull = json2.tables[tableKey2].columns[columnName].notNull;
        const columnAutoIncrement = json2.tables[tableKey2].columns[columnName].autoincrement;
        const columnPk = json2.tables[tableKey2].columns[columnName].primaryKey;
        const typeSchema = json2.tables[tableKey2].columns[columnName].typeSchema;
        const json1ColumnTypeSchema = json1.tables[tableKey2].columns[columnName].typeSchema;
        const compositePk = json2.tables[tableKey2].compositePrimaryKeys[`${tableName}_${columnName}`];
        if (typeof column6.name !== "string") {
          statements.push({
            type: "alter_table_rename_column",
            tableName,
            oldColumnName: column6.name.old,
            newColumnName: column6.name.new,
            schema: schema6
          });
        }
        if (column6.type?.type === "changed") {
          const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g;
          const parsedNewColumnType = column6.type.new.replace(arrayDefinitionRegex, "");
          const parsedOldColumnType = column6.type.old.replace(arrayDefinitionRegex, "");
          const isNewTypeIsEnum = json2.enums[`${typeSchema}.${parsedNewColumnType}`];
          const isOldTypeIsEnum = json1.enums[`${json1ColumnTypeSchema}.${parsedOldColumnType}`];
          statements.push({
            type: "pg_alter_table_alter_column_set_type",
            tableName,
            columnName,
            typeSchema,
            newDataType: {
              name: column6.type.new,
              isEnum: isNewTypeIsEnum ? true : false
            },
            oldDataType: {
              name: column6.type.old,
              isEnum: isOldTypeIsEnum ? true : false
            },
            schema: schema6,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.primaryKey?.type === "deleted" || column6.primaryKey?.type === "changed" && !column6.primaryKey.new && typeof compositePk === "undefined") {
          dropPkStatements.push({
            ////
            type: "alter_table_alter_column_drop_pk",
            tableName,
            columnName,
            schema: schema6
          });
        }
        if (column6.default?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column6.default.value,
            schema: schema6,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (column6.default?.type === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column6.default.new,
            oldDefaultValue: column6.default.old,
            schema: schema6,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (column6.default?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_default",
            tableName,
            columnName,
            schema: schema6,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (column6.notNull?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_notnull",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.notNull?.type === "changed") {
          const type = column6.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull";
          statements.push({
            type,
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.notNull?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_notnull",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.identity?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_identity",
            tableName,
            columnName,
            schema: schema6,
            identity: column6.identity.value
          });
        }
        if (column6.identity?.type === "changed") {
          statements.push({
            type: "alter_table_alter_column_change_identity",
            tableName,
            columnName,
            schema: schema6,
            identity: column6.identity.new,
            oldIdentity: column6.identity.old
          });
        }
        if (column6.identity?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_identity",
            tableName,
            columnName,
            schema: schema6
          });
        }
        if (column6.generated?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_generated",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (column6.generated?.type === "changed" && action !== "push") {
          statements.push({
            type: "alter_table_alter_column_alter_generated",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (column6.generated?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_generated",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (column6.primaryKey?.type === "added" || column6.primaryKey?.type === "changed" && column6.primaryKey.new) {
          const wasAutoincrement = statements.filter(
            (it) => it.type === "alter_table_alter_column_set_autoincrement"
          );
          if (wasAutoincrement.length === 0) {
            setPkStatements.push({
              type: "alter_table_alter_column_set_pk",
              tableName,
              schema: schema6,
              columnName
            });
          }
        }
        if (column6.onUpdate?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_on_update",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.onUpdate?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_on_update",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
      }
      return [...dropPkStatements, ...setPkStatements, ...statements];
    };
    prepareSqliteAlterColumns = (tableName, schema6, columns, json2) => {
      let statements = [];
      let dropPkStatements = [];
      let setPkStatements = [];
      for (const column6 of columns) {
        const columnName = typeof column6.name !== "string" ? column6.name.new : column6.name;
        const columnType = json2.tables[tableName].columns[columnName].type;
        const columnDefault = json2.tables[tableName].columns[columnName].default;
        const columnOnUpdate = json2.tables[tableName].columns[columnName].onUpdate;
        const columnNotNull = json2.tables[tableName].columns[columnName].notNull;
        const columnAutoIncrement = json2.tables[tableName].columns[columnName].autoincrement;
        const columnPk = json2.tables[tableName].columns[columnName].primaryKey;
        const columnGenerated = json2.tables[tableName].columns[columnName].generated;
        const compositePk = json2.tables[tableName].compositePrimaryKeys[`${tableName}_${columnName}`];
        if (column6.autoincrement?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_autoincrement",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.autoincrement?.type === "changed") {
          const type = column6.autoincrement.new ? "alter_table_alter_column_set_autoincrement" : "alter_table_alter_column_drop_autoincrement";
          statements.push({
            type,
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.autoincrement?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_autoincrement",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (typeof column6.name !== "string") {
          statements.push({
            type: "alter_table_rename_column",
            tableName,
            oldColumnName: column6.name.old,
            newColumnName: column6.name.new,
            schema: schema6
          });
        }
        if (column6.type?.type === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_type",
            tableName,
            columnName,
            newDataType: column6.type.new,
            oldDataType: column6.type.old,
            schema: schema6,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.primaryKey?.type === "deleted" || column6.primaryKey?.type === "changed" && !column6.primaryKey.new && typeof compositePk === "undefined") {
          dropPkStatements.push({
            ////
            type: "alter_table_alter_column_drop_pk",
            tableName,
            columnName,
            schema: schema6
          });
        }
        if (column6.default?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column6.default.value,
            schema: schema6,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (column6.default?.type === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column6.default.new,
            oldDefaultValue: column6.default.old,
            schema: schema6,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (column6.default?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_default",
            tableName,
            columnName,
            schema: schema6,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (column6.notNull?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_notnull",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.notNull?.type === "changed") {
          const type = column6.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull";
          statements.push({
            type,
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.notNull?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_notnull",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.generated?.type === "added") {
          if (columnGenerated?.type === "virtual") {
            statements.push({
              type: "alter_table_alter_column_set_generated",
              tableName,
              columnName,
              schema: schema6,
              newDataType: columnType,
              columnDefault,
              columnOnUpdate,
              columnNotNull,
              columnAutoIncrement,
              columnPk,
              columnGenerated
            });
          } else {
            warning(
              `As SQLite docs mention: "It is not possible to ALTER TABLE ADD COLUMN a STORED column. One can add a VIRTUAL column, however", source: "https://www.sqlite.org/gencol.html"`
            );
          }
        }
        if (column6.generated?.type === "changed") {
          if (columnGenerated?.type === "virtual") {
            statements.push({
              type: "alter_table_alter_column_alter_generated",
              tableName,
              columnName,
              schema: schema6,
              newDataType: columnType,
              columnDefault,
              columnOnUpdate,
              columnNotNull,
              columnAutoIncrement,
              columnPk,
              columnGenerated
            });
          } else {
            warning(
              `As SQLite docs mention: "It is not possible to ALTER TABLE ADD COLUMN a STORED column. One can add a VIRTUAL column, however", source: "https://www.sqlite.org/gencol.html"`
            );
          }
        }
        if (column6.generated?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_generated",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (column6.primaryKey?.type === "added" || column6.primaryKey?.type === "changed" && column6.primaryKey.new) {
          const wasAutoincrement = statements.filter(
            (it) => it.type === "alter_table_alter_column_set_autoincrement"
          );
          if (wasAutoincrement.length === 0) {
            setPkStatements.push({
              type: "alter_table_alter_column_set_pk",
              tableName,
              schema: schema6,
              columnName
            });
          }
        }
        if (column6.onUpdate?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_on_update",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.onUpdate?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_on_update",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
      }
      return [...dropPkStatements, ...setPkStatements, ...statements];
    };
    prepareRenamePolicyJsons = (tableName, schema6, renames) => {
      return renames.map((it) => {
        return {
          type: "rename_policy",
          tableName,
          oldName: it.from.name,
          newName: it.to.name,
          schema: schema6
        };
      });
    };
    prepareRenameIndPolicyJsons = (renames) => {
      return renames.map((it) => {
        return {
          type: "rename_ind_policy",
          tableKey: it.from.on,
          oldName: it.from.name,
          newName: it.to.name
        };
      });
    };
    prepareCreatePolicyJsons = (tableName, schema6, policies) => {
      return policies.map((it) => {
        return {
          type: "create_policy",
          tableName,
          data: it,
          schema: schema6
        };
      });
    };
    prepareCreateIndPolicyJsons = (policies) => {
      return policies.map((it) => {
        return {
          type: "create_ind_policy",
          tableName: it.on,
          data: it
        };
      });
    };
    prepareDropPolicyJsons = (tableName, schema6, policies) => {
      return policies.map((it) => {
        return {
          type: "drop_policy",
          tableName,
          data: it,
          schema: schema6
        };
      });
    };
    prepareDropIndPolicyJsons = (policies) => {
      return policies.map((it) => {
        return {
          type: "drop_ind_policy",
          tableName: it.on,
          data: it
        };
      });
    };
    prepareAlterPolicyJson = (tableName, schema6, oldPolicy, newPolicy) => {
      return {
        type: "alter_policy",
        tableName,
        oldData: oldPolicy,
        newData: newPolicy,
        schema: schema6
      };
    };
    prepareAlterIndPolicyJson = (oldPolicy, newPolicy) => {
      return {
        type: "alter_ind_policy",
        oldData: oldPolicy,
        newData: newPolicy
      };
    };
    preparePgCreateIndexesJson = (tableName, schema6, indexes, fullSchema, action) => {
      if (action === "push") {
        return Object.values(indexes).map((indexData) => {
          const unsquashedIndex = PgSquasher.unsquashIdxPush(indexData);
          const data = fullSchema.tables[`${schema6 === "" ? "public" : schema6}.${tableName}`].indexes[unsquashedIndex.name];
          return {
            type: "create_index_pg",
            tableName,
            data,
            schema: schema6
          };
        });
      }
      return Object.values(indexes).map((indexData) => {
        return {
          type: "create_index_pg",
          tableName,
          data: PgSquasher.unsquashIdx(indexData),
          schema: schema6
        };
      });
    };
    prepareCreateIndexesJson = (tableName, schema6, indexes, internal) => {
      return Object.values(indexes).map((indexData) => {
        return {
          type: "create_index",
          tableName,
          data: indexData,
          schema: schema6,
          internal
        };
      });
    };
    prepareCreateReferencesJson = (tableName, schema6, foreignKeys) => {
      return Object.values(foreignKeys).map((fkData) => {
        return {
          type: "create_reference",
          tableName,
          data: fkData,
          schema: schema6
        };
      });
    };
    prepareLibSQLCreateReferencesJson = (tableName, schema6, foreignKeys, json2, action) => {
      return Object.values(foreignKeys).map((fkData) => {
        const { columnsFrom, tableFrom, columnsTo } = action === "push" ? SQLiteSquasher.unsquashPushFK(fkData) : SQLiteSquasher.unsquashFK(fkData);
        let isMulticolumn = false;
        if (columnsFrom.length > 1 || columnsTo.length > 1) {
          isMulticolumn = true;
          return {
            type: "create_reference",
            tableName,
            data: fkData,
            schema: schema6,
            isMulticolumn
          };
        }
        const columnFrom = columnsFrom[0];
        const {
          notNull: columnNotNull,
          default: columnDefault,
          type: columnType
        } = json2.tables[tableFrom].columns[columnFrom];
        return {
          type: "create_reference",
          tableName,
          data: fkData,
          schema: schema6,
          columnNotNull,
          columnDefault,
          columnType
        };
      });
    };
    prepareDropReferencesJson = (tableName, schema6, foreignKeys) => {
      return Object.values(foreignKeys).map((fkData) => {
        return {
          type: "delete_reference",
          tableName,
          data: fkData,
          schema: schema6
        };
      });
    };
    prepareLibSQLDropReferencesJson = (tableName, schema6, foreignKeys, json2, meta, action) => {
      const statements = Object.values(foreignKeys).map((fkData) => {
        const { columnsFrom, tableFrom, columnsTo, name, tableTo, onDelete, onUpdate } = action === "push" ? SQLiteSquasher.unsquashPushFK(fkData) : SQLiteSquasher.unsquashFK(fkData);
        const keys = Object.keys(json2.tables[tableName].columns);
        const filtered = columnsFrom.filter((it) => keys.includes(it));
        const fullDrop = filtered.length === 0;
        if (fullDrop) return;
        let isMulticolumn = false;
        if (columnsFrom.length > 1 || columnsTo.length > 1) {
          isMulticolumn = true;
          return {
            type: "delete_reference",
            tableName,
            data: fkData,
            schema: schema6,
            isMulticolumn
          };
        }
        const columnFrom = columnsFrom[0];
        const newTableName = getNewTableName(tableFrom, meta);
        const {
          notNull: columnNotNull,
          default: columnDefault,
          type: columnType
        } = json2.tables[newTableName].columns[columnFrom];
        const fkToSquash = {
          columnsFrom,
          columnsTo,
          name,
          tableFrom: newTableName,
          tableTo,
          onDelete,
          onUpdate
        };
        const foreignKey = action === "push" ? SQLiteSquasher.squashPushFK(fkToSquash) : SQLiteSquasher.squashFK(fkToSquash);
        return {
          type: "delete_reference",
          tableName,
          data: foreignKey,
          schema: schema6,
          columnNotNull,
          columnDefault,
          columnType
        };
      });
      return statements.filter((it) => it);
    };
    prepareAlterReferencesJson = (tableName, schema6, foreignKeys) => {
      const stmts = [];
      Object.values(foreignKeys).map((val2) => {
        stmts.push({
          type: "delete_reference",
          tableName,
          schema: schema6,
          data: val2.__old
        });
        stmts.push({
          type: "create_reference",
          tableName,
          schema: schema6,
          data: val2.__new
        });
      });
      return stmts;
    };
    prepareDropIndexesJson = (tableName, schema6, indexes) => {
      return Object.values(indexes).map((indexData) => {
        return {
          type: "drop_index",
          tableName,
          data: indexData,
          schema: schema6
        };
      });
    };
    prepareAddCompositePrimaryKeySqlite = (tableName, pks) => {
      return Object.values(pks).map((it) => {
        return {
          type: "create_composite_pk",
          tableName,
          data: it
        };
      });
    };
    prepareDeleteCompositePrimaryKeySqlite = (tableName, pks) => {
      return Object.values(pks).map((it) => {
        return {
          type: "delete_composite_pk",
          tableName,
          data: it
        };
      });
    };
    prepareAlterCompositePrimaryKeySqlite = (tableName, pks) => {
      return Object.values(pks).map((it) => {
        return {
          type: "alter_composite_pk",
          tableName,
          old: it.__old,
          new: it.__new
        };
      });
    };
    prepareAddCompositePrimaryKeyPg = (tableName, schema6, pks, json2) => {
      return Object.values(pks).map((it) => {
        const unsquashed = PgSquasher.unsquashPK(it);
        return {
          type: "create_composite_pk",
          tableName,
          data: it,
          schema: schema6,
          constraintName: PgSquasher.unsquashPK(it).name
        };
      });
    };
    prepareDeleteCompositePrimaryKeyPg = (tableName, schema6, pks, json1) => {
      return Object.values(pks).map((it) => {
        return {
          type: "delete_composite_pk",
          tableName,
          data: it,
          schema: schema6,
          constraintName: PgSquasher.unsquashPK(it).name
        };
      });
    };
    prepareAlterCompositePrimaryKeyPg = (tableName, schema6, pks, json1, json2) => {
      return Object.values(pks).map((it) => {
        return {
          type: "alter_composite_pk",
          tableName,
          old: it.__old,
          new: it.__new,
          schema: schema6,
          oldConstraintName: PgSquasher.unsquashPK(it.__old).name,
          newConstraintName: PgSquasher.unsquashPK(it.__new).name
        };
      });
    };
    prepareAddUniqueConstraintPg = (tableName, schema6, unqs) => {
      return Object.values(unqs).map((it) => {
        return {
          type: "create_unique_constraint",
          tableName,
          data: it,
          schema: schema6
        };
      });
    };
    prepareDeleteUniqueConstraintPg = (tableName, schema6, unqs) => {
      return Object.values(unqs).map((it) => {
        return {
          type: "delete_unique_constraint",
          tableName,
          data: it,
          schema: schema6
        };
      });
    };
    prepareAddCheckConstraint = (tableName, schema6, check) => {
      return Object.values(check).map((it) => {
        return {
          type: "create_check_constraint",
          tableName,
          data: it,
          schema: schema6
        };
      });
    };
    prepareDeleteCheckConstraint = (tableName, schema6, check) => {
      return Object.values(check).map((it) => {
        return {
          type: "delete_check_constraint",
          tableName,
          constraintName: PgSquasher.unsquashCheck(it).name,
          schema: schema6
        };
      });
    };
    prepareAddCompositePrimaryKeyMySql = (tableName, pks, json1, json2) => {
      const res = [];
      for (const it of Object.values(pks)) {
        const unsquashed = MySqlSquasher.unsquashPK(it);
        if (unsquashed.columns.length === 1 && json1.tables[tableName]?.columns[unsquashed.columns[0]]?.primaryKey) {
          continue;
        }
        res.push({
          type: "create_composite_pk",
          tableName,
          data: it,
          constraintName: unsquashed.name
        });
      }
      return res;
    };
    prepareDeleteCompositePrimaryKeyMySql = (tableName, pks, json1) => {
      return Object.values(pks).map((it) => {
        const unsquashed = MySqlSquasher.unsquashPK(it);
        return {
          type: "delete_composite_pk",
          tableName,
          data: it
        };
      });
    };
    prepareAlterCompositePrimaryKeyMySql = (tableName, pks, json1, json2) => {
      return Object.values(pks).map((it) => {
        return {
          type: "alter_composite_pk",
          tableName,
          old: it.__old,
          new: it.__new,
          oldConstraintName: json1.tables[tableName].compositePrimaryKeys[MySqlSquasher.unsquashPK(it.__old).name].name,
          newConstraintName: json2.tables[tableName].compositePrimaryKeys[MySqlSquasher.unsquashPK(it.__new).name].name
        };
      });
    };
    preparePgCreateViewJson = (name, schema6, definition, materialized, withNoData = false, withOption, using, tablespace) => {
      return {
        type: "create_view",
        name,
        schema: schema6,
        definition,
        with: withOption,
        materialized,
        withNoData,
        using,
        tablespace
      };
    };
    prepareMySqlCreateViewJson = (name, definition, meta, replace = false) => {
      const { algorithm, sqlSecurity, withCheckOption } = MySqlSquasher.unsquashView(meta);
      return {
        type: "mysql_create_view",
        name,
        definition,
        algorithm,
        sqlSecurity,
        withCheckOption,
        replace
      };
    };
    prepareSqliteCreateViewJson = (name, definition) => {
      return {
        type: "sqlite_create_view",
        name,
        definition
      };
    };
    prepareDropViewJson = (name, schema6, materialized) => {
      const resObject = { name, type: "drop_view" };
      if (schema6) resObject["schema"] = schema6;
      if (materialized) resObject["materialized"] = materialized;
      return resObject;
    };
    prepareRenameViewJson = (to, from, schema6, materialized) => {
      const resObject = {
        type: "rename_view",
        nameTo: to,
        nameFrom: from
      };
      if (schema6) resObject["schema"] = schema6;
      if (materialized) resObject["materialized"] = materialized;
      return resObject;
    };
    preparePgAlterViewAlterSchemaJson = (to, from, name, materialized) => {
      const returnObject = {
        type: "alter_view_alter_schema",
        fromSchema: from,
        toSchema: to,
        name
      };
      if (materialized) returnObject["materialized"] = materialized;
      return returnObject;
    };
    preparePgAlterViewAddWithOptionJson = (name, schema6, materialized, withOption) => {
      return {
        type: "alter_view_add_with_option",
        name,
        schema: schema6,
        materialized,
        with: withOption
      };
    };
    preparePgAlterViewDropWithOptionJson = (name, schema6, materialized, withOption) => {
      return {
        type: "alter_view_drop_with_option",
        name,
        schema: schema6,
        materialized,
        with: withOption
      };
    };
    preparePgAlterViewAlterTablespaceJson = (name, schema6, materialized, to) => {
      return {
        type: "alter_view_alter_tablespace",
        name,
        schema: schema6,
        materialized,
        toTablespace: to
      };
    };
    preparePgAlterViewAlterUsingJson = (name, schema6, materialized, to) => {
      return {
        type: "alter_view_alter_using",
        name,
        schema: schema6,
        materialized,
        toUsing: to
      };
    };
    prepareMySqlAlterView = (view5) => {
      return { type: "alter_mysql_view", ...view5 };
    };
  }
});

// src/statementCombiner.ts
var prepareLibSQLRecreateTable, prepareSQLiteRecreateTable, libSQLCombineStatements, sqliteCombineStatements, prepareSingleStoreRecreateTable, singleStoreCombineStatements;
var init_statementCombiner = __esm({
  "src/statementCombiner.ts"() {
    "use strict";
    init_jsonStatements();
    init_sqliteSchema();
    prepareLibSQLRecreateTable = (table6, action) => {
      const { name, columns, uniqueConstraints, indexes, checkConstraints } = table6;
      const composites = Object.values(table6.compositePrimaryKeys).map(
        (it) => SQLiteSquasher.unsquashPK(it)
      );
      const references2 = Object.values(table6.foreignKeys);
      const fks = references2.map(
        (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it)
      );
      const statements = [
        {
          type: "recreate_table",
          tableName: name,
          columns: Object.values(columns),
          compositePKs: composites,
          referenceData: fks,
          uniqueConstraints: Object.values(uniqueConstraints),
          checkConstraints: Object.values(checkConstraints)
        }
      ];
      if (Object.keys(indexes).length) {
        statements.push(...prepareCreateIndexesJson(name, "", indexes));
      }
      return statements;
    };
    prepareSQLiteRecreateTable = (table6, action) => {
      const { name, columns, uniqueConstraints, indexes, checkConstraints } = table6;
      const composites = Object.values(table6.compositePrimaryKeys).map(
        (it) => SQLiteSquasher.unsquashPK(it)
      );
      const references2 = Object.values(table6.foreignKeys);
      const fks = references2.map(
        (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it)
      );
      const statements = [
        {
          type: "recreate_table",
          tableName: name,
          columns: Object.values(columns),
          compositePKs: composites,
          referenceData: fks,
          uniqueConstraints: Object.values(uniqueConstraints),
          checkConstraints: Object.values(checkConstraints)
        }
      ];
      if (Object.keys(indexes).length) {
        statements.push(...prepareCreateIndexesJson(name, "", indexes));
      }
      return statements;
    };
    libSQLCombineStatements = (statements, json2, action) => {
      const newStatements = {};
      for (const statement of statements) {
        if (statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default") {
          const { tableName: tableName2, columnName, columnPk } = statement;
          const columnIsPartOfForeignKey = Object.values(
            json2.tables[tableName2].foreignKeys
          ).some((it) => {
            const unsquashFk = action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it);
            return unsquashFk.columnsFrom.includes(columnName);
          });
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2 && (columnIsPartOfForeignKey || columnPk)) {
            newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
            continue;
          }
          if (statementsForTable2 && (columnIsPartOfForeignKey || columnPk)) {
            if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
              const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
              const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
              if (wasRename) {
                newStatements[tableName2].push(...preparedStatements);
              } else {
                newStatements[tableName2] = preparedStatements;
              }
            }
            continue;
          }
          if (statementsForTable2 && !(columnIsPartOfForeignKey || columnPk)) {
            if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
              newStatements[tableName2].push(statement);
            }
            continue;
          }
          newStatements[tableName2] = [statement];
          continue;
        }
        if (statement.type === "create_reference") {
          const tableName2 = statement.tableName;
          const data = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data);
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = statement.isMulticolumn ? prepareLibSQLRecreateTable(json2.tables[tableName2], action) : [statement];
            continue;
          }
          if (!statement.isMulticolumn && statementsForTable2.some(
            (st) => st.type === "sqlite_alter_table_add_column" && st.column.name === data.columnsFrom[0]
          )) {
            continue;
          }
          if (statement.isMulticolumn) {
            if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
              const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
              const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
              if (wasRename) {
                newStatements[tableName2].push(...preparedStatements);
              } else {
                newStatements[tableName2] = preparedStatements;
              }
              continue;
            }
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            newStatements[tableName2].push(statement);
          }
          continue;
        }
        if (statement.type === "delete_reference") {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        if (statement.type === "sqlite_alter_table_add_column" && statement.column.primaryKey) {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName;
        const statementsForTable = newStatements[tableName];
        if (!statementsForTable) {
          newStatements[tableName] = [statement];
          continue;
        }
        if (!statementsForTable.some(({ type }) => type === "recreate_table")) {
          newStatements[tableName].push(statement);
        }
      }
      const combinedStatements = Object.values(newStatements).flat();
      const renamedTables = combinedStatements.filter((it) => it.type === "rename_table");
      const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column");
      const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column");
      return [...renamedTables, ...renamedColumns, ...rest];
    };
    sqliteCombineStatements = (statements, json2, action) => {
      const newStatements = {};
      for (const statement of statements) {
        if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "delete_reference" || statement.type === "alter_reference" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk" || statement.type === "create_unique_constraint" || statement.type === "delete_unique_constraint" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        if (statement.type === "sqlite_alter_table_add_column" && statement.column.primaryKey) {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        if (statement.type === "create_reference") {
          const tableName2 = statement.tableName;
          const data = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data);
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
            continue;
          }
          if (data.columnsFrom.length === 1 && statementsForTable2.some(
            (st) => st.type === "sqlite_alter_table_add_column" && st.column.name === data.columnsFrom[0]
          )) {
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName;
        const statementsForTable = newStatements[tableName];
        if (!statementsForTable) {
          newStatements[tableName] = [statement];
          continue;
        }
        if (!statementsForTable.some(({ type }) => type === "recreate_table")) {
          newStatements[tableName].push(statement);
        }
      }
      const combinedStatements = Object.values(newStatements).flat();
      const renamedTables = combinedStatements.filter((it) => it.type === "rename_table");
      const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column");
      const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column");
      return [...renamedTables, ...renamedColumns, ...rest];
    };
    prepareSingleStoreRecreateTable = (table6) => {
      const { name, columns, uniqueConstraints, indexes, compositePrimaryKeys } = table6;
      const composites = Object.values(compositePrimaryKeys);
      const statements = [
        {
          type: "singlestore_recreate_table",
          tableName: name,
          columns: Object.values(columns),
          compositePKs: composites,
          uniqueConstraints: Object.values(uniqueConstraints)
        }
      ];
      if (Object.keys(indexes).length) {
        statements.push(...prepareCreateIndexesJson(name, "", indexes));
      }
      return statements;
    };
    singleStoreCombineStatements = (statements, json2) => {
      const newStatements = {};
      for (const statement of statements) {
        if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk") {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(
              ({ type }) => type === "rename_table" || type === "alter_table_rename_column"
            );
            const preparedStatements = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        if ((statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_default") && statement.columnNotNull) {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        if (statement.type === "alter_table_add_column" && statement.column.primaryKey) {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName;
        const statementsForTable = newStatements[tableName];
        if (!statementsForTable) {
          newStatements[tableName] = [statement];
          continue;
        }
        if (!statementsForTable.some(({ type }) => type === "singlestore_recreate_table")) {
          newStatements[tableName].push(statement);
        }
      }
      const combinedStatements = Object.values(newStatements).flat();
      const renamedTables = combinedStatements.filter((it) => it.type === "rename_table");
      const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column");
      const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column");
      return [...renamedTables, ...renamedColumns, ...rest];
    };
  }
});

// src/snapshotsDiffer.ts
var snapshotsDiffer_exports = {};
__export(snapshotsDiffer_exports, {
  alteredPgViewSchema: () => alteredPgViewSchema,
  alteredTableScheme: () => alteredTableScheme,
  applyLibSQLSnapshotsDiff: () => applyLibSQLSnapshotsDiff,
  applyMysqlSnapshotsDiff: () => applyMysqlSnapshotsDiff,
  applyPgSnapshotsDiff: () => applyPgSnapshotsDiff,
  applySingleStoreSnapshotsDiff: () => applySingleStoreSnapshotsDiff,
  applySqliteSnapshotsDiff: () => applySqliteSnapshotsDiff,
  diffResultScheme: () => diffResultScheme,
  diffResultSchemeMysql: () => diffResultSchemeMysql,
  diffResultSchemeSQLite: () => diffResultSchemeSQLite,
  diffResultSchemeSingleStore: () => diffResultSchemeSingleStore,
  makePatched: () => makePatched,
  makeSelfOrPatched: () => makeSelfOrPatched
});
var makeChanged, makeSelfOrChanged, makePatched, makeSelfOrPatched, columnSchema, alteredColumnSchema, enumSchema3, changedEnumSchema, tableScheme, alteredTableScheme, alteredViewCommon, alteredPgViewSchema, alteredMySqlViewSchema, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSingleStore, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySingleStoreSnapshotsDiff, applySqliteSnapshotsDiff, applyLibSQLSnapshotsDiff;
var init_snapshotsDiffer = __esm({
  "src/snapshotsDiffer.ts"() {
    "use strict";
    init_esm();
    init_jsonDiffer();
    init_sqlgenerator();
    init_jsonStatements();
    init_global();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    init_statementCombiner();
    init_utils();
    makeChanged = (schema6) => {
      return objectType({
        type: enumType(["changed"]),
        old: schema6,
        new: schema6
      });
    };
    makeSelfOrChanged = (schema6) => {
      return unionType([
        schema6,
        objectType({
          type: enumType(["changed"]),
          old: schema6,
          new: schema6
        })
      ]);
    };
    makePatched = (schema6) => {
      return unionType([
        objectType({
          type: literalType("added"),
          value: schema6
        }),
        objectType({
          type: literalType("deleted"),
          value: schema6
        }),
        objectType({
          type: literalType("changed"),
          old: schema6,
          new: schema6
        })
      ]);
    };
    makeSelfOrPatched = (schema6) => {
      return unionType([
        objectType({
          type: literalType("none"),
          value: schema6
        }),
        objectType({
          type: literalType("added"),
          value: schema6
        }),
        objectType({
          type: literalType("deleted"),
          value: schema6
        }),
        objectType({
          type: literalType("changed"),
          old: schema6,
          new: schema6
        })
      ]);
    };
    columnSchema = objectType({
      name: stringType(),
      type: stringType(),
      typeSchema: stringType().optional(),
      primaryKey: booleanType().optional(),
      default: anyType().optional(),
      notNull: booleanType().optional(),
      // should it be optional? should if be here?
      autoincrement: booleanType().optional(),
      onUpdate: booleanType().optional(),
      isUnique: anyType().optional(),
      uniqueName: stringType().optional(),
      nullsNotDistinct: booleanType().optional(),
      generated: objectType({
        as: stringType(),
        type: enumType(["stored", "virtual"]).default("stored")
      }).optional(),
      identity: stringType().optional()
    }).strict();
    alteredColumnSchema = objectType({
      name: makeSelfOrChanged(stringType()),
      type: makeChanged(stringType()).optional(),
      default: makePatched(anyType()).optional(),
      primaryKey: makePatched(booleanType()).optional(),
      notNull: makePatched(booleanType()).optional(),
      typeSchema: makePatched(stringType()).optional(),
      onUpdate: makePatched(booleanType()).optional(),
      autoincrement: makePatched(booleanType()).optional(),
      generated: makePatched(
        objectType({
          as: stringType(),
          type: enumType(["stored", "virtual"]).default("stored")
        })
      ).optional(),
      identity: makePatched(stringType()).optional()
    }).strict();
    enumSchema3 = objectType({
      name: stringType(),
      schema: stringType(),
      values: arrayType(stringType())
    }).strict();
    changedEnumSchema = objectType({
      name: stringType(),
      schema: stringType(),
      addedValues: objectType({
        before: stringType(),
        value: stringType()
      }).array(),
      deletedValues: arrayType(stringType())
    }).strict();
    tableScheme = objectType({
      name: stringType(),
      schema: stringType().default(""),
      columns: recordType(stringType(), columnSchema),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()).default({}),
      uniqueConstraints: recordType(stringType(), stringType()).default({}),
      policies: recordType(stringType(), stringType()).default({}),
      checkConstraints: recordType(stringType(), stringType()).default({}),
      isRLSEnabled: booleanType().default(false)
    }).strict();
    alteredTableScheme = objectType({
      name: stringType(),
      schema: stringType(),
      altered: alteredColumnSchema.array(),
      addedIndexes: recordType(stringType(), stringType()),
      deletedIndexes: recordType(stringType(), stringType()),
      alteredIndexes: recordType(
        stringType(),
        objectType({
          __new: stringType(),
          __old: stringType()
        }).strict()
      ),
      addedForeignKeys: recordType(stringType(), stringType()),
      deletedForeignKeys: recordType(stringType(), stringType()),
      alteredForeignKeys: recordType(
        stringType(),
        objectType({
          __new: stringType(),
          __old: stringType()
        }).strict()
      ),
      addedCompositePKs: recordType(stringType(), stringType()),
      deletedCompositePKs: recordType(stringType(), stringType()),
      alteredCompositePKs: recordType(
        stringType(),
        objectType({
          __new: stringType(),
          __old: stringType()
        })
      ),
      addedUniqueConstraints: recordType(stringType(), stringType()),
      deletedUniqueConstraints: recordType(stringType(), stringType()),
      alteredUniqueConstraints: recordType(
        stringType(),
        objectType({
          __new: stringType(),
          __old: stringType()
        })
      ),
      addedPolicies: recordType(stringType(), stringType()),
      deletedPolicies: recordType(stringType(), stringType()),
      alteredPolicies: recordType(
        stringType(),
        objectType({
          __new: stringType(),
          __old: stringType()
        })
      ),
      addedCheckConstraints: recordType(
        stringType(),
        stringType()
      ),
      deletedCheckConstraints: recordType(
        stringType(),
        stringType()
      ),
      alteredCheckConstraints: recordType(
        stringType(),
        objectType({
          __new: stringType(),
          __old: stringType()
        })
      )
    }).strict();
    alteredViewCommon = objectType({
      name: stringType(),
      alteredDefinition: objectType({
        __old: stringType(),
        __new: stringType()
      }).strict().optional(),
      alteredExisting: objectType({
        __old: booleanType(),
        __new: booleanType()
      }).strict().optional()
    });
    alteredPgViewSchema = alteredViewCommon.merge(
      objectType({
        schema: stringType(),
        deletedWithOption: mergedViewWithOption2.optional(),
        addedWithOption: mergedViewWithOption2.optional(),
        addedWith: mergedViewWithOption2.optional(),
        deletedWith: mergedViewWithOption2.optional(),
        alteredWith: mergedViewWithOption2.optional(),
        alteredSchema: objectType({
          __old: stringType(),
          __new: stringType()
        }).strict().optional(),
        alteredTablespace: objectType({
          __old: stringType(),
          __new: stringType()
        }).strict().optional(),
        alteredUsing: objectType({
          __old: stringType(),
          __new: stringType()
        }).strict().optional()
      }).strict()
    );
    alteredMySqlViewSchema = alteredViewCommon.merge(
      objectType({
        alteredMeta: objectType({
          __old: stringType(),
          __new: stringType()
        }).strict().optional()
      }).strict()
    );
    diffResultScheme = objectType({
      alteredTablesWithColumns: alteredTableScheme.array(),
      alteredEnums: changedEnumSchema.array(),
      alteredSequences: sequenceSquashed2.array(),
      alteredRoles: roleSchema2.array(),
      alteredPolicies: policySquashed2.array(),
      alteredViews: alteredPgViewSchema.array()
    }).strict();
    diffResultSchemeMysql = objectType({
      alteredTablesWithColumns: alteredTableScheme.array(),
      alteredEnums: neverType().array(),
      alteredViews: alteredMySqlViewSchema.array()
    });
    diffResultSchemeSingleStore = objectType({
      alteredTablesWithColumns: alteredTableScheme.array(),
      alteredEnums: neverType().array()
    });
    diffResultSchemeSQLite = objectType({
      alteredTablesWithColumns: alteredTableScheme.array(),
      alteredEnums: neverType().array(),
      alteredViews: alteredViewCommon.array()
    });
    schemaChangeFor = (table6, renamedSchemas) => {
      for (let ren of renamedSchemas) {
        if (table6.schema === ren.from.name) {
          return { key: `${ren.to.name}.${table6.name}`, schema: ren.to.name };
        }
      }
      return {
        key: `${table6.schema || "public"}.${table6.name}`,
        schema: table6.schema
      };
    };
    nameChangeFor = (table6, renamed) => {
      for (let ren of renamed) {
        if (table6.name === ren.from.name) {
          return { name: ren.to.name };
        }
      }
      return {
        name: table6.name
      };
    };
    nameSchemaChangeFor = (table6, renamedTables) => {
      for (let ren of renamedTables) {
        if (table6.name === ren.from.name && table6.schema === ren.from.schema) {
          return {
            key: `${ren.to.schema || "public"}.${ren.to.name}`,
            name: ren.to.name,
            schema: ren.to.schema
          };
        }
      }
      return {
        key: `${table6.schema || "public"}.${table6.name}`,
        name: table6.name,
        schema: table6.schema
      };
    };
    columnChangeFor = (column6, renamedColumns) => {
      for (let ren of renamedColumns) {
        if (column6 === ren.from.name) {
          return ren.to.name;
        }
      }
      return column6;
    };
    applyPgSnapshotsDiff = async (json1, json2, schemasResolver2, enumsResolver2, sequencesResolver2, policyResolver2, indPolicyResolver2, roleResolver2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
      const schemasDiff = diffSchemasOrTables(json1.schemas, json2.schemas);
      const {
        created: createdSchemas,
        deleted: deletedSchemas,
        renamed: renamedSchemas
      } = await schemasResolver2({
        created: schemasDiff.added.map((it) => ({ name: it })),
        deleted: schemasDiff.deleted.map((it) => ({ name: it }))
      });
      const schemasPatchedSnap1 = copy(json1);
      schemasPatchedSnap1.tables = mapEntries(
        schemasPatchedSnap1.tables,
        (_3, it) => {
          const { key, schema: schema6 } = schemaChangeFor(it, renamedSchemas);
          it.schema = schema6;
          return [key, it];
        }
      );
      schemasPatchedSnap1.enums = mapEntries(schemasPatchedSnap1.enums, (_3, it) => {
        const { key, schema: schema6 } = schemaChangeFor(it, renamedSchemas);
        it.schema = schema6;
        return [key, it];
      });
      const enumsDiff = diffSchemasOrTables(schemasPatchedSnap1.enums, json2.enums);
      const {
        created: createdEnums,
        deleted: deletedEnums,
        renamed: renamedEnums,
        moved: movedEnums
      } = await enumsResolver2({
        created: enumsDiff.added,
        deleted: enumsDiff.deleted
      });
      schemasPatchedSnap1.enums = mapEntries(schemasPatchedSnap1.enums, (_3, it) => {
        const { key, name, schema: schema6 } = nameSchemaChangeFor(it, renamedEnums);
        it.name = name;
        it.schema = schema6;
        return [key, it];
      });
      const columnTypesChangeMap = renamedEnums.reduce(
        (acc, it) => {
          acc[`${it.from.schema}.${it.from.name}`] = {
            nameFrom: it.from.name,
            nameTo: it.to.name,
            schemaFrom: it.from.schema,
            schemaTo: it.to.schema
          };
          return acc;
        },
        {}
      );
      const columnTypesMovesMap = movedEnums.reduce(
        (acc, it) => {
          acc[`${it.schemaFrom}.${it.name}`] = {
            nameFrom: it.name,
            nameTo: it.name,
            schemaFrom: it.schemaFrom,
            schemaTo: it.schemaTo
          };
          return acc;
        },
        {}
      );
      schemasPatchedSnap1.tables = mapEntries(
        schemasPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapValues(tableValue.columns, (column6) => {
            const key = `${column6.typeSchema || "public"}.${column6.type}`;
            const change = columnTypesChangeMap[key] || columnTypesMovesMap[key];
            if (change) {
              column6.type = change.nameTo;
              column6.typeSchema = change.schemaTo;
            }
            return column6;
          });
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      schemasPatchedSnap1.sequences = mapEntries(
        schemasPatchedSnap1.sequences,
        (_3, it) => {
          const { key, schema: schema6 } = schemaChangeFor(it, renamedSchemas);
          it.schema = schema6;
          return [key, it];
        }
      );
      const sequencesDiff = diffSchemasOrTables(
        schemasPatchedSnap1.sequences,
        json2.sequences
      );
      const {
        created: createdSequences,
        deleted: deletedSequences,
        renamed: renamedSequences,
        moved: movedSequences
      } = await sequencesResolver2({
        created: sequencesDiff.added,
        deleted: sequencesDiff.deleted
      });
      schemasPatchedSnap1.sequences = mapEntries(
        schemasPatchedSnap1.sequences,
        (_3, it) => {
          const { key, name, schema: schema6 } = nameSchemaChangeFor(it, renamedSequences);
          it.name = name;
          it.schema = schema6;
          return [key, it];
        }
      );
      const sequencesChangeMap = renamedSequences.reduce(
        (acc, it) => {
          acc[`${it.from.schema}.${it.from.name}`] = {
            nameFrom: it.from.name,
            nameTo: it.to.name,
            schemaFrom: it.from.schema,
            schemaTo: it.to.schema
          };
          return acc;
        },
        {}
      );
      const sequencesMovesMap = movedSequences.reduce(
        (acc, it) => {
          acc[`${it.schemaFrom}.${it.name}`] = {
            nameFrom: it.name,
            nameTo: it.name,
            schemaFrom: it.schemaFrom,
            schemaTo: it.schemaTo
          };
          return acc;
        },
        {}
      );
      schemasPatchedSnap1.tables = mapEntries(
        schemasPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapValues(tableValue.columns, (column6) => {
            const key = `${column6.typeSchema || "public"}.${column6.type}`;
            const change = sequencesChangeMap[key] || sequencesMovesMap[key];
            if (change) {
              column6.type = change.nameTo;
              column6.typeSchema = change.schemaTo;
            }
            return column6;
          });
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      const rolesDiff = diffSchemasOrTables(
        schemasPatchedSnap1.roles,
        json2.roles
      );
      const {
        created: createdRoles,
        deleted: deletedRoles,
        renamed: renamedRoles
      } = await roleResolver2({
        created: rolesDiff.added,
        deleted: rolesDiff.deleted
      });
      schemasPatchedSnap1.roles = mapEntries(
        schemasPatchedSnap1.roles,
        (_3, it) => {
          const { name } = nameChangeFor(it, renamedRoles);
          it.name = name;
          return [name, it];
        }
      );
      const rolesChangeMap = renamedRoles.reduce(
        (acc, it) => {
          acc[it.from.name] = {
            nameFrom: it.from.name,
            nameTo: it.to.name
          };
          return acc;
        },
        {}
      );
      schemasPatchedSnap1.roles = mapEntries(
        schemasPatchedSnap1.roles,
        (roleKey, roleValue) => {
          const key = roleKey;
          const change = rolesChangeMap[key];
          if (change) {
            roleValue.name = change.nameTo;
          }
          return [roleKey, roleValue];
        }
      );
      const tablesDiff = diffSchemasOrTables(
        schemasPatchedSnap1.tables,
        json2.tables
      );
      const {
        created: createdTables,
        deleted: deletedTables,
        moved: movedTables,
        renamed: renamedTables
        // renamed or moved
      } = await tablesResolver2({
        created: tablesDiff.added,
        deleted: tablesDiff.deleted
      });
      const tablesPatchedSnap1 = copy(schemasPatchedSnap1);
      tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
        const { key, name, schema: schema6 } = nameSchemaChangeFor(it, renamedTables);
        it.name = name;
        it.schema = schema6;
        return [key, it];
      });
      const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
      const columnRenames = [];
      const columnCreates = [];
      const columnDeletes = [];
      for (let entry of Object.values(res)) {
        const { renamed, created: created2, deleted: deleted2 } = await columnsResolver2({
          tableName: entry.name,
          schema: entry.schema,
          deleted: entry.columns.deleted,
          created: entry.columns.added
        });
        if (created2.length > 0) {
          columnCreates.push({
            table: entry.name,
            schema: entry.schema,
            columns: created2
          });
        }
        if (deleted2.length > 0) {
          columnDeletes.push({
            table: entry.name,
            schema: entry.schema,
            columns: deleted2
          });
        }
        if (renamed.length > 0) {
          columnRenames.push({
            table: entry.name,
            schema: entry.schema,
            renames: renamed
          });
        }
      }
      const columnRenamesDict = columnRenames.reduce(
        (acc, it) => {
          acc[`${it.schema || "public"}.${it.table}`] = it.renames;
          return acc;
        },
        {}
      );
      const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
      columnsPatchedSnap1.tables = mapEntries(
        columnsPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapKeys(
            tableValue.columns,
            (columnKey, column6) => {
              const rens = columnRenamesDict[`${tableValue.schema || "public"}.${tableValue.name}`] || [];
              const newName = columnChangeFor(columnKey, rens);
              column6.name = newName;
              return newName;
            }
          );
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      const policyRes = diffPolicies(tablesPatchedSnap1.tables, json2.tables);
      const policyRenames = [];
      const policyCreates = [];
      const policyDeletes = [];
      for (let entry of Object.values(policyRes)) {
        const { renamed, created: created2, deleted: deleted2 } = await policyResolver2({
          tableName: entry.name,
          schema: entry.schema,
          deleted: entry.policies.deleted.map(
            action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy
          ),
          created: entry.policies.added.map(action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy)
        });
        if (created2.length > 0) {
          policyCreates.push({
            table: entry.name,
            schema: entry.schema,
            columns: created2
          });
        }
        if (deleted2.length > 0) {
          policyDeletes.push({
            table: entry.name,
            schema: entry.schema,
            columns: deleted2
          });
        }
        if (renamed.length > 0) {
          policyRenames.push({
            table: entry.name,
            schema: entry.schema,
            renames: renamed
          });
        }
      }
      const policyRenamesDict = columnRenames.reduce(
        (acc, it) => {
          acc[`${it.schema || "public"}.${it.table}`] = it.renames;
          return acc;
        },
        {}
      );
      const policyPatchedSnap1 = copy(tablesPatchedSnap1);
      policyPatchedSnap1.tables = mapEntries(
        policyPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedPolicies = mapKeys(
            tableValue.policies,
            (policyKey, policy5) => {
              const rens = policyRenamesDict[`${tableValue.schema || "public"}.${tableValue.name}`] || [];
              const newName = columnChangeFor(policyKey, rens);
              const unsquashedPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(policy5) : PgSquasher.unsquashPolicy(policy5);
              unsquashedPolicy.name = newName;
              policy5 = PgSquasher.squashPolicy(unsquashedPolicy);
              return newName;
            }
          );
          tableValue.policies = patchedPolicies;
          return [tableKey2, tableValue];
        }
      );
      const indPolicyRes = diffIndPolicies(policyPatchedSnap1.policies, json2.policies);
      const indPolicyCreates = [];
      const indPolicyDeletes = [];
      const { renamed: indPolicyRenames, created, deleted } = await indPolicyResolver2({
        deleted: indPolicyRes.deleted.map(
          (t6) => action === "push" ? PgSquasher.unsquashPolicyPush(t6.values) : PgSquasher.unsquashPolicy(t6.values)
        ),
        created: indPolicyRes.added.map(
          (t6) => action === "push" ? PgSquasher.unsquashPolicyPush(t6.values) : PgSquasher.unsquashPolicy(t6.values)
        )
      });
      if (created.length > 0) {
        indPolicyCreates.push({
          policies: created
        });
      }
      if (deleted.length > 0) {
        indPolicyDeletes.push({
          policies: deleted
        });
      }
      const indPolicyRenamesDict = indPolicyRenames.reduce(
        (acc, it) => {
          acc[it.from.name] = {
            nameFrom: it.from.name,
            nameTo: it.to.name
          };
          return acc;
        },
        {}
      );
      const indPolicyPatchedSnap1 = copy(policyPatchedSnap1);
      indPolicyPatchedSnap1.policies = mapEntries(
        indPolicyPatchedSnap1.policies,
        (policyKey, policyValue) => {
          const key = policyKey;
          const change = indPolicyRenamesDict[key];
          if (change) {
            policyValue.name = change.nameTo;
          }
          return [policyKey, policyValue];
        }
      );
      const viewsDiff = diffSchemasOrTables(indPolicyPatchedSnap1.views, json2.views);
      const {
        created: createdViews,
        deleted: deletedViews,
        renamed: renamedViews,
        moved: movedViews
      } = await viewsResolver2({
        created: viewsDiff.added,
        deleted: viewsDiff.deleted
      });
      const renamesViewDic = {};
      renamedViews.forEach((it) => {
        renamesViewDic[`${it.from.schema}.${it.from.name}`] = { to: it.to.name, from: it.from.name };
      });
      const movedViewDic = {};
      movedViews.forEach((it) => {
        movedViewDic[`${it.schemaFrom}.${it.name}`] = { to: it.schemaTo, from: it.schemaFrom };
      });
      const viewsPatchedSnap1 = copy(policyPatchedSnap1);
      viewsPatchedSnap1.views = mapEntries(
        viewsPatchedSnap1.views,
        (viewKey, viewValue) => {
          const rename = renamesViewDic[`${viewValue.schema}.${viewValue.name}`];
          const moved = movedViewDic[`${viewValue.schema}.${viewValue.name}`];
          if (rename) {
            viewValue.name = rename.to;
            viewKey = `${viewValue.schema}.${viewValue.name}`;
          }
          if (moved) viewKey = `${moved.to}.${viewValue.name}`;
          return [viewKey, viewValue];
        }
      );
      const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
      const typedResult = diffResultScheme.parse(diffResult);
      const jsonStatements = [];
      const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
        return preparePgCreateIndexesJson(
          it.name,
          it.schema,
          it.indexes,
          curFull,
          action
        );
      }).flat();
      const jsonDropTables = deletedTables.map((it) => {
        return prepareDropTableJson(it);
      });
      const jsonRenameTables = renamedTables.map((it) => {
        return prepareRenameTableJson(it.from, it.to);
      });
      const alteredTables = typedResult.alteredTablesWithColumns;
      const jsonRenameColumnsStatements = [];
      const jsonDropColumnsStatemets = [];
      const jsonAddColumnsStatemets = [];
      for (let it of columnRenames) {
        jsonRenameColumnsStatements.push(
          ...prepareRenameColumns(it.table, it.schema, it.renames)
        );
      }
      for (let it of columnDeletes) {
        jsonDropColumnsStatemets.push(
          ..._prepareDropColumns(it.table, it.schema, it.columns)
        );
      }
      for (let it of columnCreates) {
        jsonAddColumnsStatemets.push(
          ..._prepareAddColumns(it.table, it.schema, it.columns)
        );
      }
      const jsonAddedCompositePKs = [];
      const jsonDeletedCompositePKs = [];
      const jsonAlteredCompositePKs = [];
      const jsonAddedUniqueConstraints = [];
      const jsonDeletedUniqueConstraints = [];
      const jsonAlteredUniqueConstraints = [];
      const jsonSetTableSchemas = [];
      if (movedTables) {
        for (let it of movedTables) {
          jsonSetTableSchemas.push({
            type: "alter_table_set_schema",
            tableName: it.name,
            schemaFrom: it.schemaFrom || "public",
            schemaTo: it.schemaTo || "public"
          });
        }
      }
      const jsonDeletedCheckConstraints = [];
      const jsonCreatedCheckConstraints = [];
      for (let it of alteredTables) {
        let addedColumns;
        for (const addedPkName of Object.keys(it.addedCompositePKs)) {
          const addedPkColumns = it.addedCompositePKs[addedPkName];
          addedColumns = PgSquasher.unsquashPK(addedPkColumns);
        }
        let deletedColumns;
        for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
          const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
          deletedColumns = PgSquasher.unsquashPK(deletedPkColumns);
        }
        const doPerformDeleteAndCreate = JSON.stringify(addedColumns ?? {}) !== JSON.stringify(deletedColumns ?? {});
        let addedCompositePKs = [];
        let deletedCompositePKs = [];
        let alteredCompositePKs = [];
        if (doPerformDeleteAndCreate) {
          addedCompositePKs = prepareAddCompositePrimaryKeyPg(
            it.name,
            it.schema,
            it.addedCompositePKs,
            curFull
          );
          deletedCompositePKs = prepareDeleteCompositePrimaryKeyPg(
            it.name,
            it.schema,
            it.deletedCompositePKs,
            prevFull
          );
        }
        alteredCompositePKs = prepareAlterCompositePrimaryKeyPg(
          it.name,
          it.schema,
          it.alteredCompositePKs,
          prevFull,
          curFull
        );
        let addedUniqueConstraints = [];
        let deletedUniqueConstraints = [];
        let alteredUniqueConstraints = [];
        let createCheckConstraints = [];
        let deleteCheckConstraints = [];
        addedUniqueConstraints = prepareAddUniqueConstraintPg(
          it.name,
          it.schema,
          it.addedUniqueConstraints
        );
        deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
          it.name,
          it.schema,
          it.deletedUniqueConstraints
        );
        if (it.alteredUniqueConstraints) {
          const added = {};
          const deleted2 = {};
          for (const k5 of Object.keys(it.alteredUniqueConstraints)) {
            added[k5] = it.alteredUniqueConstraints[k5].__new;
            deleted2[k5] = it.alteredUniqueConstraints[k5].__old;
          }
          addedUniqueConstraints.push(
            ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
          );
          deletedUniqueConstraints.push(
            ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted2)
          );
        }
        createCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
        deleteCheckConstraints = prepareDeleteCheckConstraint(
          it.name,
          it.schema,
          it.deletedCheckConstraints
        );
        if (it.alteredCheckConstraints && action !== "push") {
          const added = {};
          const deleted2 = {};
          for (const k5 of Object.keys(it.alteredCheckConstraints)) {
            added[k5] = it.alteredCheckConstraints[k5].__new;
            deleted2[k5] = it.alteredCheckConstraints[k5].__old;
          }
          createCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
          deleteCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted2));
        }
        jsonCreatedCheckConstraints.push(...createCheckConstraints);
        jsonDeletedCheckConstraints.push(...deleteCheckConstraints);
        jsonAddedCompositePKs.push(...addedCompositePKs);
        jsonDeletedCompositePKs.push(...deletedCompositePKs);
        jsonAlteredCompositePKs.push(...alteredCompositePKs);
        jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
        jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
        jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
      }
      const rColumns = jsonRenameColumnsStatements.map((it) => {
        const tableName = it.tableName;
        const schema6 = it.schema;
        return {
          from: { schema: schema6, table: tableName, column: it.oldColumnName },
          to: { schema: schema6, table: tableName, column: it.newColumnName }
        };
      });
      const jsonTableAlternations = alteredTables.map((it) => {
        return preparePgAlterColumns(
          it.name,
          it.schema,
          it.altered,
          json2,
          json1,
          action
        );
      }).flat();
      const jsonCreateIndexesFoAlteredTables = alteredTables.map((it) => {
        return preparePgCreateIndexesJson(
          it.name,
          it.schema,
          it.addedIndexes || {},
          curFull,
          action
        );
      }).flat();
      const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => {
        return prepareDropIndexesJson(
          it.name,
          it.schema,
          it.deletedIndexes || {}
        );
      }).flat();
      const jsonCreatePoliciesStatements = [];
      const jsonDropPoliciesStatements = [];
      const jsonAlterPoliciesStatements = [];
      const jsonRenamePoliciesStatements = [];
      const jsonRenameIndPoliciesStatements = [];
      const jsonCreateIndPoliciesStatements = [];
      const jsonDropIndPoliciesStatements = [];
      const jsonAlterIndPoliciesStatements = [];
      const jsonEnableRLSStatements = [];
      const jsonDisableRLSStatements = [];
      for (let it of indPolicyRenames) {
        jsonRenameIndPoliciesStatements.push(
          ...prepareRenameIndPolicyJsons([it])
        );
      }
      for (const it of indPolicyCreates) {
        jsonCreateIndPoliciesStatements.push(
          ...prepareCreateIndPolicyJsons(
            it.policies
          )
        );
      }
      for (const it of indPolicyDeletes) {
        jsonDropIndPoliciesStatements.push(
          ...prepareDropIndPolicyJsons(
            it.policies
          )
        );
      }
      typedResult.alteredPolicies.forEach(({ values }) => {
        const policy5 = action === "push" ? PgSquasher.unsquashPolicyPush(values) : PgSquasher.unsquashPolicy(values);
        const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(json2.policies[policy5.name].values) : PgSquasher.unsquashPolicy(json2.policies[policy5.name].values);
        const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(json2.policies[policy5.name].values) : PgSquasher.unsquashPolicy(json1.policies[policy5.name].values);
        if (newPolicy.as !== oldPolicy.as) {
          jsonDropIndPoliciesStatements.push(
            ...prepareDropIndPolicyJsons(
              [oldPolicy]
            )
          );
          jsonCreateIndPoliciesStatements.push(
            ...prepareCreateIndPolicyJsons(
              [newPolicy]
            )
          );
          return;
        }
        if (newPolicy.for !== oldPolicy.for) {
          jsonDropIndPoliciesStatements.push(
            ...prepareDropIndPolicyJsons(
              [oldPolicy]
            )
          );
          jsonCreateIndPoliciesStatements.push(
            ...prepareCreateIndPolicyJsons(
              [newPolicy]
            )
          );
          return;
        }
        jsonAlterIndPoliciesStatements.push(
          prepareAlterIndPolicyJson(
            oldPolicy,
            newPolicy
          )
        );
      });
      for (let it of policyRenames) {
        jsonRenamePoliciesStatements.push(
          ...prepareRenamePolicyJsons(it.table, it.schema, it.renames)
        );
      }
      for (const it of policyCreates) {
        jsonCreatePoliciesStatements.push(
          ...prepareCreatePolicyJsons(
            it.table,
            it.schema,
            it.columns
          )
        );
      }
      for (const it of policyDeletes) {
        jsonDropPoliciesStatements.push(
          ...prepareDropPolicyJsons(
            it.table,
            it.schema,
            it.columns
          )
        );
      }
      alteredTables.forEach((it) => {
        Object.keys(it.alteredPolicies).forEach((policyName) => {
          const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(it.alteredPolicies[policyName].__new) : PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__new);
          const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(it.alteredPolicies[policyName].__old) : PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__old);
          if (newPolicy.as !== oldPolicy.as) {
            jsonDropPoliciesStatements.push(
              ...prepareDropPolicyJsons(
                it.name,
                it.schema,
                [oldPolicy]
              )
            );
            jsonCreatePoliciesStatements.push(
              ...prepareCreatePolicyJsons(
                it.name,
                it.schema,
                [newPolicy]
              )
            );
            return;
          }
          if (newPolicy.for !== oldPolicy.for) {
            jsonDropPoliciesStatements.push(
              ...prepareDropPolicyJsons(
                it.name,
                it.schema,
                [oldPolicy]
              )
            );
            jsonCreatePoliciesStatements.push(
              ...prepareCreatePolicyJsons(
                it.name,
                it.schema,
                [newPolicy]
              )
            );
            return;
          }
          jsonAlterPoliciesStatements.push(
            prepareAlterPolicyJson(
              it.name,
              it.schema,
              it.alteredPolicies[policyName].__old,
              it.alteredPolicies[policyName].__new
            )
          );
        });
        for (const table6 of Object.values(json2.tables)) {
          const policiesInCurrentState = Object.keys(table6.policies);
          const tableInPreviousState = columnsPatchedSnap1.tables[`${table6.schema === "" ? "public" : table6.schema}.${table6.name}`];
          const policiesInPreviousState = tableInPreviousState ? Object.keys(tableInPreviousState.policies) : [];
          if (policiesInPreviousState.length === 0 && policiesInCurrentState.length > 0 && !table6.isRLSEnabled) {
            jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table6.name, schema: table6.schema });
          }
          if (policiesInPreviousState.length > 0 && policiesInCurrentState.length === 0 && !table6.isRLSEnabled) {
            jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema });
          }
          const wasRlsEnabled = tableInPreviousState ? tableInPreviousState.isRLSEnabled : false;
          if (table6.isRLSEnabled !== wasRlsEnabled) {
            if (table6.isRLSEnabled) {
              jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table6.name, schema: table6.schema });
            } else if (!table6.isRLSEnabled && policiesInCurrentState.length === 0) {
              jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema });
            }
          }
        }
        for (const table6 of Object.values(columnsPatchedSnap1.tables)) {
          const tableInCurrentState = json2.tables[`${table6.schema === "" ? "public" : table6.schema}.${table6.name}`];
          if (tableInCurrentState === void 0 && !table6.isRLSEnabled) {
            jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema });
          }
        }
        const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__old;
            return current;
          },
          {}
        );
        const createdIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__new;
            return current;
          },
          {}
        );
        jsonCreateIndexesFoAlteredTables.push(
          ...preparePgCreateIndexesJson(
            it.name,
            it.schema,
            createdIndexes || {},
            curFull,
            action
          )
        );
        jsonDropIndexesForAllAlteredTables.push(
          ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
        );
      });
      const jsonCreateReferencesForCreatedTables = createdTables.map((it) => {
        return prepareCreateReferencesJson(it.name, it.schema, it.foreignKeys);
      }).flat();
      const jsonReferencesForAlteredTables = alteredTables.map((it) => {
        const forAdded = prepareCreateReferencesJson(
          it.name,
          it.schema,
          it.addedForeignKeys
        );
        const forAltered = prepareDropReferencesJson(
          it.name,
          it.schema,
          it.deletedForeignKeys
        );
        const alteredFKs = prepareAlterReferencesJson(
          it.name,
          it.schema,
          it.alteredForeignKeys
        );
        return [...forAdded, ...forAltered, ...alteredFKs];
      }).flat();
      const jsonCreatedReferencesForAlteredTables = jsonReferencesForAlteredTables.filter(
        (t6) => t6.type === "create_reference"
      );
      const jsonDroppedReferencesForAlteredTables = jsonReferencesForAlteredTables.filter(
        (t6) => t6.type === "delete_reference"
      );
      const createEnums = createdEnums.map((it) => {
        return prepareCreateEnumJson(it.name, it.schema, it.values);
      }) ?? [];
      const dropEnums = deletedEnums.map((it) => {
        return prepareDropEnumJson(it.name, it.schema);
      });
      const moveEnums = movedEnums.map((it) => {
        return prepareMoveEnumJson(it.name, it.schemaFrom, it.schemaTo);
      });
      const renameEnums = renamedEnums.map((it) => {
        return prepareRenameEnumJson(it.from.name, it.to.name, it.to.schema);
      });
      const jsonAlterEnumsWithAddedValues = typedResult.alteredEnums.map((it) => {
        return prepareAddValuesToEnumJson(it.name, it.schema, it.addedValues);
      }).flat() ?? [];
      const jsonAlterEnumsWithDroppedValues = typedResult.alteredEnums.map((it) => {
        return prepareDropEnumValues(it.name, it.schema, it.deletedValues, curFull);
      }).flat() ?? [];
      const createSequences = createdSequences.map((it) => {
        return prepareCreateSequenceJson(it);
      }) ?? [];
      const dropSequences = deletedSequences.map((it) => {
        return prepareDropSequenceJson(it.name, it.schema);
      });
      const moveSequences = movedSequences.map((it) => {
        return prepareMoveSequenceJson(it.name, it.schemaFrom, it.schemaTo);
      });
      const renameSequences = renamedSequences.map((it) => {
        return prepareRenameSequenceJson(it.from.name, it.to.name, it.to.schema);
      });
      const jsonAlterSequences = typedResult.alteredSequences.map((it) => {
        return prepareAlterSequenceJson(it);
      }).flat() ?? [];
      const createRoles = createdRoles.map((it) => {
        return prepareCreateRoleJson(it);
      }) ?? [];
      const dropRoles = deletedRoles.map((it) => {
        return prepareDropRoleJson(it.name);
      });
      const renameRoles = renamedRoles.map((it) => {
        return prepareRenameRoleJson(it.from.name, it.to.name);
      });
      const jsonAlterRoles = typedResult.alteredRoles.map((it) => {
        return prepareAlterRoleJson(it);
      }).flat() ?? [];
      const createSchemas = prepareCreateSchemasJson(
        createdSchemas.map((it) => it.name)
      );
      const renameSchemas = prepareRenameSchemasJson(
        renamedSchemas.map((it) => ({ from: it.from.name, to: it.to.name }))
      );
      const dropSchemas = prepareDeleteSchemasJson(
        deletedSchemas.map((it) => it.name)
      );
      const createTables = createdTables.map((it) => {
        return preparePgCreateTableJson(it, curFull);
      });
      jsonCreatePoliciesStatements.push(...[].concat(
        ...createdTables.map(
          (it) => prepareCreatePolicyJsons(
            it.name,
            it.schema,
            Object.values(it.policies).map(action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy)
          )
        )
      ));
      const createViews = [];
      const dropViews = [];
      const renameViews = [];
      const alterViews = [];
      createViews.push(
        ...createdViews.filter((it) => !it.isExisting).map((it) => {
          return preparePgCreateViewJson(
            it.name,
            it.schema,
            it.definition,
            it.materialized,
            it.withNoData,
            it.with,
            it.using,
            it.tablespace
          );
        })
      );
      dropViews.push(
        ...deletedViews.filter((it) => !it.isExisting).map((it) => {
          return prepareDropViewJson(it.name, it.schema, it.materialized);
        })
      );
      renameViews.push(
        ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[`${it.from.schema}.${it.from.name}`].isExisting).map((it) => {
          return prepareRenameViewJson(it.to.name, it.from.name, it.to.schema, it.to.materialized);
        })
      );
      alterViews.push(
        ...movedViews.filter(
          (it) => !json2.views[`${it.schemaTo}.${it.name}`].isExisting && !json1.views[`${it.schemaFrom}.${it.name}`].isExisting
        ).map((it) => {
          return preparePgAlterViewAlterSchemaJson(
            it.schemaTo,
            it.schemaFrom,
            it.name,
            json2.views[`${it.schemaTo}.${it.name}`].materialized
          );
        })
      );
      const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[`${it.schema}.${it.name}`].isExisting);
      for (const alteredView of alteredViews) {
        const viewKey = `${alteredView.schema}.${alteredView.name}`;
        const { materialized, with: withOption, definition, withNoData, using, tablespace } = json2.views[viewKey];
        if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
          dropViews.push(prepareDropViewJson(alteredView.name, alteredView.schema, materialized));
          createViews.push(
            preparePgCreateViewJson(
              alteredView.name,
              alteredView.schema,
              definition,
              materialized,
              withNoData,
              withOption,
              using,
              tablespace
            )
          );
          continue;
        }
        if (alteredView.addedWithOption) {
          alterViews.push(
            preparePgAlterViewAddWithOptionJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.addedWithOption
            )
          );
        }
        if (alteredView.deletedWithOption) {
          alterViews.push(
            preparePgAlterViewDropWithOptionJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.deletedWithOption
            )
          );
        }
        if (alteredView.addedWith) {
          alterViews.push(
            preparePgAlterViewAddWithOptionJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.addedWith
            )
          );
        }
        if (alteredView.deletedWith) {
          alterViews.push(
            preparePgAlterViewDropWithOptionJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.deletedWith
            )
          );
        }
        if (alteredView.alteredWith) {
          alterViews.push(
            preparePgAlterViewAddWithOptionJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.alteredWith
            )
          );
        }
        if (alteredView.alteredTablespace) {
          alterViews.push(
            preparePgAlterViewAlterTablespaceJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.alteredTablespace.__new
            )
          );
        }
        if (alteredView.alteredUsing) {
          alterViews.push(
            preparePgAlterViewAlterUsingJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.alteredUsing.__new
            )
          );
        }
      }
      jsonStatements.push(...createSchemas);
      jsonStatements.push(...renameSchemas);
      jsonStatements.push(...createEnums);
      jsonStatements.push(...moveEnums);
      jsonStatements.push(...renameEnums);
      jsonStatements.push(...jsonAlterEnumsWithAddedValues);
      jsonStatements.push(...createSequences);
      jsonStatements.push(...moveSequences);
      jsonStatements.push(...renameSequences);
      jsonStatements.push(...jsonAlterSequences);
      jsonStatements.push(...renameRoles);
      jsonStatements.push(...dropRoles);
      jsonStatements.push(...createRoles);
      jsonStatements.push(...jsonAlterRoles);
      jsonStatements.push(...createTables);
      jsonStatements.push(...jsonEnableRLSStatements);
      jsonStatements.push(...jsonDisableRLSStatements);
      jsonStatements.push(...dropViews);
      jsonStatements.push(...renameViews);
      jsonStatements.push(...alterViews);
      jsonStatements.push(...jsonDropTables);
      jsonStatements.push(...jsonSetTableSchemas);
      jsonStatements.push(...jsonRenameTables);
      jsonStatements.push(...jsonRenameColumnsStatements);
      jsonStatements.push(...jsonDeletedUniqueConstraints);
      jsonStatements.push(...jsonDeletedCheckConstraints);
      jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
      jsonStatements.push(...jsonAlterEnumsWithDroppedValues);
      jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
      jsonStatements.push(...jsonDeletedCompositePKs);
      jsonStatements.push(...jsonTableAlternations);
      jsonStatements.push(...jsonAddedCompositePKs);
      jsonStatements.push(...jsonAddColumnsStatemets);
      jsonStatements.push(...jsonCreateReferencesForCreatedTables);
      jsonStatements.push(...jsonCreateIndexesForCreatedTables);
      jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
      jsonStatements.push(...jsonCreateIndexesFoAlteredTables);
      jsonStatements.push(...jsonDropColumnsStatemets);
      jsonStatements.push(...jsonAlteredCompositePKs);
      jsonStatements.push(...jsonAddedUniqueConstraints);
      jsonStatements.push(...jsonCreatedCheckConstraints);
      jsonStatements.push(...jsonAlteredUniqueConstraints);
      jsonStatements.push(...createViews);
      jsonStatements.push(...jsonRenamePoliciesStatements);
      jsonStatements.push(...jsonDropPoliciesStatements);
      jsonStatements.push(...jsonCreatePoliciesStatements);
      jsonStatements.push(...jsonAlterPoliciesStatements);
      jsonStatements.push(...jsonRenameIndPoliciesStatements);
      jsonStatements.push(...jsonDropIndPoliciesStatements);
      jsonStatements.push(...jsonCreateIndPoliciesStatements);
      jsonStatements.push(...jsonAlterIndPoliciesStatements);
      jsonStatements.push(...dropEnums);
      jsonStatements.push(...dropSequences);
      jsonStatements.push(...dropSchemas);
      const filteredJsonStatements = jsonStatements.filter((st) => {
        if (st.type === "alter_table_alter_column_drop_notnull") {
          if (jsonStatements.find(
            (it) => it.type === "alter_table_alter_column_drop_identity" && it.tableName === st.tableName && it.schema === st.schema
          )) {
            return false;
          }
        }
        if (st.type === "alter_table_alter_column_set_notnull") {
          if (jsonStatements.find(
            (it) => it.type === "alter_table_alter_column_set_identity" && it.tableName === st.tableName && it.schema === st.schema
          )) {
            return false;
          }
        }
        return true;
      });
      const filteredEnumsJsonStatements = filteredJsonStatements.filter((st) => {
        if (st.type === "alter_type_add_value") {
          if (filteredJsonStatements.find(
            (it) => it.type === "alter_type_drop_value" && it.name === st.name && it.enumSchema === st.schema
          )) {
            return false;
          }
        }
        return true;
      });
      const filteredEnums2JsonStatements = filteredEnumsJsonStatements.filter((st) => {
        if (st.type === "alter_table_alter_column_set_default") {
          if (filteredEnumsJsonStatements.find(
            (it) => it.type === "pg_alter_table_alter_column_set_type" && it.columnDefault === st.newDefaultValue && it.columnName === st.columnName && it.tableName === st.tableName && it.schema === st.schema
          )) {
            return false;
          }
          if (filteredEnumsJsonStatements.find(
            (it) => it.type === "alter_type_drop_value" && it.columnsWithEnum.find(
              (column6) => column6.default === st.newDefaultValue && column6.column === st.columnName && column6.table === st.tableName && column6.tableSchema === st.schema
            )
          )) {
            return false;
          }
        }
        return true;
      });
      const sqlStatements = fromJson(filteredEnums2JsonStatements, "postgresql", action);
      const uniqueSqlStatements = [];
      sqlStatements.forEach((ss) => {
        if (!uniqueSqlStatements.includes(ss)) {
          uniqueSqlStatements.push(ss);
        }
      });
      const rSchemas = renamedSchemas.map((it) => ({
        from: it.from.name,
        to: it.to.name
      }));
      const rTables = renamedTables.map((it) => {
        return { from: it.from, to: it.to };
      });
      const _meta = prepareMigrationMeta(rSchemas, rTables, rColumns);
      return {
        statements: filteredEnums2JsonStatements,
        sqlStatements: uniqueSqlStatements,
        _meta
      };
    };
    applyMysqlSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
      for (const tableName in json1.tables) {
        const table6 = json1.tables[tableName];
        for (const indexName2 in table6.indexes) {
          const index6 = MySqlSquasher.unsquashIdx(table6.indexes[indexName2]);
          if (index6.isUnique) {
            table6.uniqueConstraints[indexName2] = MySqlSquasher.squashUnique({
              name: index6.name,
              columns: index6.columns
            });
            delete json1.tables[tableName].indexes[index6.name];
          }
        }
      }
      for (const tableName in json2.tables) {
        const table6 = json2.tables[tableName];
        for (const indexName2 in table6.indexes) {
          const index6 = MySqlSquasher.unsquashIdx(table6.indexes[indexName2]);
          if (index6.isUnique) {
            table6.uniqueConstraints[indexName2] = MySqlSquasher.squashUnique({
              name: index6.name,
              columns: index6.columns
            });
            delete json2.tables[tableName].indexes[index6.name];
          }
        }
      }
      const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
      const {
        created: createdTables,
        deleted: deletedTables,
        renamed: renamedTables
        // renamed or moved
      } = await tablesResolver2({
        created: tablesDiff.added,
        deleted: tablesDiff.deleted
      });
      const tablesPatchedSnap1 = copy(json1);
      tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
        const { name } = nameChangeFor(it, renamedTables);
        it.name = name;
        return [name, it];
      });
      const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
      const columnRenames = [];
      const columnCreates = [];
      const columnDeletes = [];
      for (let entry of Object.values(res)) {
        const { renamed, created, deleted } = await columnsResolver2({
          tableName: entry.name,
          schema: entry.schema,
          deleted: entry.columns.deleted,
          created: entry.columns.added
        });
        if (created.length > 0) {
          columnCreates.push({
            table: entry.name,
            columns: created
          });
        }
        if (deleted.length > 0) {
          columnDeletes.push({
            table: entry.name,
            columns: deleted
          });
        }
        if (renamed.length > 0) {
          columnRenames.push({
            table: entry.name,
            renames: renamed
          });
        }
      }
      const columnRenamesDict = columnRenames.reduce(
        (acc, it) => {
          acc[it.table] = it.renames;
          return acc;
        },
        {}
      );
      const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
      columnsPatchedSnap1.tables = mapEntries(
        columnsPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapKeys(
            tableValue.columns,
            (columnKey, column6) => {
              const rens = columnRenamesDict[tableValue.name] || [];
              const newName = columnChangeFor(columnKey, rens);
              column6.name = newName;
              return newName;
            }
          );
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      const viewsDiff = diffSchemasOrTables(json1.views, json2.views);
      const {
        created: createdViews,
        deleted: deletedViews,
        renamed: renamedViews
        // renamed or moved
      } = await viewsResolver2({
        created: viewsDiff.added,
        deleted: viewsDiff.deleted
      });
      const renamesViewDic = {};
      renamedViews.forEach((it) => {
        renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
      });
      const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
      viewsPatchedSnap1.views = mapEntries(
        viewsPatchedSnap1.views,
        (viewKey, viewValue) => {
          const rename = renamesViewDic[viewValue.name];
          if (rename) {
            viewValue.name = rename.to;
            viewKey = rename.to;
          }
          return [viewKey, viewValue];
        }
      );
      const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
      const typedResult = diffResultSchemeMysql.parse(diffResult);
      const jsonStatements = [];
      const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.indexes,
          curFull.internal
        );
      }).flat();
      const jsonDropTables = deletedTables.map((it) => {
        return prepareDropTableJson(it);
      });
      const jsonRenameTables = renamedTables.map((it) => {
        return prepareRenameTableJson(it.from, it.to);
      });
      const alteredTables = typedResult.alteredTablesWithColumns;
      const jsonAddedCompositePKs = [];
      const jsonDeletedCompositePKs = [];
      const jsonAlteredCompositePKs = [];
      const jsonAddedUniqueConstraints = [];
      const jsonDeletedUniqueConstraints = [];
      const jsonAlteredUniqueConstraints = [];
      const jsonCreatedCheckConstraints = [];
      const jsonDeletedCheckConstraints = [];
      const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
      const jsonAddColumnsStatemets = columnCreates.map((it) => _prepareAddColumns(it.table, "", it.columns)).flat();
      const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
      alteredTables.forEach((it) => {
        let addedColumns = [];
        for (const addedPkName of Object.keys(it.addedCompositePKs)) {
          const addedPkColumns = it.addedCompositePKs[addedPkName];
          addedColumns = MySqlSquasher.unsquashPK(addedPkColumns).columns;
        }
        let deletedColumns = [];
        for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
          const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
          deletedColumns = MySqlSquasher.unsquashPK(deletedPkColumns).columns;
        }
        const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
        let addedCompositePKs = [];
        let deletedCompositePKs = [];
        let alteredCompositePKs = [];
        addedCompositePKs = prepareAddCompositePrimaryKeyMySql(
          it.name,
          it.addedCompositePKs,
          prevFull,
          curFull
        );
        deletedCompositePKs = prepareDeleteCompositePrimaryKeyMySql(
          it.name,
          it.deletedCompositePKs,
          prevFull
        );
        alteredCompositePKs = prepareAlterCompositePrimaryKeyMySql(
          it.name,
          it.alteredCompositePKs,
          prevFull,
          curFull
        );
        let addedUniqueConstraints = [];
        let deletedUniqueConstraints = [];
        let alteredUniqueConstraints = [];
        let createdCheckConstraints = [];
        let deletedCheckConstraints = [];
        addedUniqueConstraints = prepareAddUniqueConstraintPg(
          it.name,
          it.schema,
          it.addedUniqueConstraints
        );
        deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
          it.name,
          it.schema,
          it.deletedUniqueConstraints
        );
        if (it.alteredUniqueConstraints) {
          const added = {};
          const deleted = {};
          for (const k5 of Object.keys(it.alteredUniqueConstraints)) {
            added[k5] = it.alteredUniqueConstraints[k5].__new;
            deleted[k5] = it.alteredUniqueConstraints[k5].__old;
          }
          addedUniqueConstraints.push(
            ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
          );
          deletedUniqueConstraints.push(
            ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
          );
        }
        createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
        deletedCheckConstraints = prepareDeleteCheckConstraint(
          it.name,
          it.schema,
          it.deletedCheckConstraints
        );
        if (it.alteredCheckConstraints && action !== "push") {
          const added = {};
          const deleted = {};
          for (const k5 of Object.keys(it.alteredCheckConstraints)) {
            added[k5] = it.alteredCheckConstraints[k5].__new;
            deleted[k5] = it.alteredCheckConstraints[k5].__old;
          }
          createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
          deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
        }
        jsonAddedCompositePKs.push(...addedCompositePKs);
        jsonDeletedCompositePKs.push(...deletedCompositePKs);
        jsonAlteredCompositePKs.push(...alteredCompositePKs);
        jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
        jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
        jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
        jsonCreatedCheckConstraints.push(...createdCheckConstraints);
        jsonDeletedCheckConstraints.push(...deletedCheckConstraints);
      });
      const rColumns = jsonRenameColumnsStatements.map((it) => {
        const tableName = it.tableName;
        const schema6 = it.schema;
        return {
          from: { schema: schema6, table: tableName, column: it.oldColumnName },
          to: { schema: schema6, table: tableName, column: it.newColumnName }
        };
      });
      const jsonTableAlternations = alteredTables.map((it) => {
        return prepareAlterColumnsMysql(
          it.name,
          it.schema,
          it.altered,
          json1,
          json2,
          action
        );
      }).flat();
      const jsonCreateIndexesForAllAlteredTables = alteredTables.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.addedIndexes || {},
          curFull.internal
        );
      }).flat();
      const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => {
        return prepareDropIndexesJson(
          it.name,
          it.schema,
          it.deletedIndexes || {}
        );
      }).flat();
      alteredTables.forEach((it) => {
        const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__old;
            return current;
          },
          {}
        );
        const createdIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__new;
            return current;
          },
          {}
        );
        jsonCreateIndexesForAllAlteredTables.push(
          ...prepareCreateIndexesJson(it.name, it.schema, createdIndexes || {})
        );
        jsonDropIndexesForAllAlteredTables.push(
          ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
        );
      });
      const jsonCreateReferencesForCreatedTables = createdTables.map((it) => {
        return prepareCreateReferencesJson(it.name, it.schema, it.foreignKeys);
      }).flat();
      const jsonReferencesForAllAlteredTables = alteredTables.map((it) => {
        const forAdded = prepareCreateReferencesJson(
          it.name,
          it.schema,
          it.addedForeignKeys
        );
        const forAltered = prepareDropReferencesJson(
          it.name,
          it.schema,
          it.deletedForeignKeys
        );
        const alteredFKs = prepareAlterReferencesJson(
          it.name,
          it.schema,
          it.alteredForeignKeys
        );
        return [...forAdded, ...forAltered, ...alteredFKs];
      }).flat();
      const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t6) => t6.type === "create_reference"
      );
      const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t6) => t6.type === "delete_reference"
      );
      const jsonMySqlCreateTables = createdTables.map((it) => {
        return prepareMySqlCreateTableJson(
          it,
          curFull,
          curFull.internal
        );
      });
      const createViews = [];
      const dropViews = [];
      const renameViews = [];
      const alterViews = [];
      createViews.push(
        ...createdViews.filter((it) => !it.isExisting).map((it) => {
          return prepareMySqlCreateViewJson(
            it.name,
            it.definition,
            it.meta
          );
        })
      );
      dropViews.push(
        ...deletedViews.filter((it) => !it.isExisting).map((it) => {
          return prepareDropViewJson(it.name);
        })
      );
      renameViews.push(
        ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[it.from.name].isExisting).map((it) => {
          return prepareRenameViewJson(it.to.name, it.from.name);
        })
      );
      const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting);
      for (const alteredView of alteredViews) {
        const { definition, meta } = json2.views[alteredView.name];
        if (alteredView.alteredExisting) {
          dropViews.push(prepareDropViewJson(alteredView.name));
          createViews.push(
            prepareMySqlCreateViewJson(
              alteredView.name,
              definition,
              meta
            )
          );
          continue;
        }
        if (alteredView.alteredDefinition && action !== "push") {
          createViews.push(
            prepareMySqlCreateViewJson(
              alteredView.name,
              definition,
              meta,
              true
            )
          );
          continue;
        }
        if (alteredView.alteredMeta) {
          const view5 = curFull["views"][alteredView.name];
          alterViews.push(
            prepareMySqlAlterView(view5)
          );
        }
      }
      jsonStatements.push(...jsonMySqlCreateTables);
      jsonStatements.push(...jsonDropTables);
      jsonStatements.push(...jsonRenameTables);
      jsonStatements.push(...jsonRenameColumnsStatements);
      jsonStatements.push(...dropViews);
      jsonStatements.push(...renameViews);
      jsonStatements.push(...alterViews);
      jsonStatements.push(...jsonDeletedUniqueConstraints);
      jsonStatements.push(...jsonDeletedCheckConstraints);
      jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
      jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
      jsonStatements.push(...jsonDeletedCompositePKs);
      jsonStatements.push(...jsonTableAlternations);
      jsonStatements.push(...jsonAddedCompositePKs);
      jsonStatements.push(...jsonAddColumnsStatemets);
      jsonStatements.push(...jsonAddedUniqueConstraints);
      jsonStatements.push(...jsonDeletedUniqueConstraints);
      jsonStatements.push(...jsonCreateReferencesForCreatedTables);
      jsonStatements.push(...jsonCreateIndexesForCreatedTables);
      jsonStatements.push(...jsonCreatedCheckConstraints);
      jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
      jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
      jsonStatements.push(...jsonDropColumnsStatemets);
      jsonStatements.push(...jsonAlteredCompositePKs);
      jsonStatements.push(...createViews);
      jsonStatements.push(...jsonAlteredUniqueConstraints);
      const sqlStatements = fromJson(jsonStatements, "mysql");
      const uniqueSqlStatements = [];
      sqlStatements.forEach((ss) => {
        if (!uniqueSqlStatements.includes(ss)) {
          uniqueSqlStatements.push(ss);
        }
      });
      const rTables = renamedTables.map((it) => {
        return { from: it.from, to: it.to };
      });
      const _meta = prepareMigrationMeta([], rTables, rColumns);
      return {
        statements: jsonStatements,
        sqlStatements: uniqueSqlStatements,
        _meta
      };
    };
    applySingleStoreSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
      for (const tableName in json1.tables) {
        const table6 = json1.tables[tableName];
        for (const indexName2 in table6.indexes) {
          const index6 = SingleStoreSquasher.unsquashIdx(table6.indexes[indexName2]);
          if (index6.isUnique) {
            table6.uniqueConstraints[indexName2] = SingleStoreSquasher.squashUnique({
              name: index6.name,
              columns: index6.columns
            });
            delete json1.tables[tableName].indexes[index6.name];
          }
        }
      }
      for (const tableName in json2.tables) {
        const table6 = json2.tables[tableName];
        for (const indexName2 in table6.indexes) {
          const index6 = SingleStoreSquasher.unsquashIdx(table6.indexes[indexName2]);
          if (index6.isUnique) {
            table6.uniqueConstraints[indexName2] = SingleStoreSquasher.squashUnique({
              name: index6.name,
              columns: index6.columns
            });
            delete json2.tables[tableName].indexes[index6.name];
          }
        }
      }
      const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
      const {
        created: createdTables,
        deleted: deletedTables,
        renamed: renamedTables
        // renamed or moved
      } = await tablesResolver2({
        created: tablesDiff.added,
        deleted: tablesDiff.deleted
      });
      const tablesPatchedSnap1 = copy(json1);
      tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
        const { name } = nameChangeFor(it, renamedTables);
        it.name = name;
        return [name, it];
      });
      const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
      const columnRenames = [];
      const columnCreates = [];
      const columnDeletes = [];
      for (let entry of Object.values(res)) {
        const { renamed, created, deleted } = await columnsResolver2({
          tableName: entry.name,
          schema: entry.schema,
          deleted: entry.columns.deleted,
          created: entry.columns.added
        });
        if (created.length > 0) {
          columnCreates.push({
            table: entry.name,
            columns: created
          });
        }
        if (deleted.length > 0) {
          columnDeletes.push({
            table: entry.name,
            columns: deleted
          });
        }
        if (renamed.length > 0) {
          columnRenames.push({
            table: entry.name,
            renames: renamed
          });
        }
      }
      const columnRenamesDict = columnRenames.reduce(
        (acc, it) => {
          acc[it.table] = it.renames;
          return acc;
        },
        {}
      );
      const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
      columnsPatchedSnap1.tables = mapEntries(
        columnsPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapKeys(
            tableValue.columns,
            (columnKey, column6) => {
              const rens = columnRenamesDict[tableValue.name] || [];
              const newName = columnChangeFor(columnKey, rens);
              column6.name = newName;
              return newName;
            }
          );
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      const diffResult = applyJsonDiff(columnsPatchedSnap1, json2);
      const typedResult = diffResultSchemeSingleStore.parse(diffResult);
      const jsonStatements = [];
      const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.indexes,
          curFull.internal
        );
      }).flat();
      const jsonDropTables = deletedTables.map((it) => {
        return prepareDropTableJson(it);
      });
      const jsonRenameTables = renamedTables.map((it) => {
        return prepareRenameTableJson(it.from, it.to);
      });
      const alteredTables = typedResult.alteredTablesWithColumns;
      const jsonAddedCompositePKs = [];
      const jsonAddedUniqueConstraints = [];
      const jsonDeletedUniqueConstraints = [];
      const jsonAlteredUniqueConstraints = [];
      const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
      const jsonAddColumnsStatemets = columnCreates.map((it) => _prepareAddColumns(it.table, "", it.columns)).flat();
      const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
      alteredTables.forEach((it) => {
        let addedColumns = [];
        for (const addedPkName of Object.keys(it.addedCompositePKs)) {
          const addedPkColumns = it.addedCompositePKs[addedPkName];
          addedColumns = SingleStoreSquasher.unsquashPK(addedPkColumns).columns;
        }
        let deletedColumns = [];
        for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
          const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
          deletedColumns = SingleStoreSquasher.unsquashPK(deletedPkColumns).columns;
        }
        const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
        let addedUniqueConstraints = [];
        let deletedUniqueConstraints = [];
        let alteredUniqueConstraints = [];
        let createdCheckConstraints = [];
        let deletedCheckConstraints = [];
        addedUniqueConstraints = prepareAddUniqueConstraintPg(
          it.name,
          it.schema,
          it.addedUniqueConstraints
        );
        deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
          it.name,
          it.schema,
          it.deletedUniqueConstraints
        );
        if (it.alteredUniqueConstraints) {
          const added = {};
          const deleted = {};
          for (const k5 of Object.keys(it.alteredUniqueConstraints)) {
            added[k5] = it.alteredUniqueConstraints[k5].__new;
            deleted[k5] = it.alteredUniqueConstraints[k5].__old;
          }
          addedUniqueConstraints.push(
            ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
          );
          deletedUniqueConstraints.push(
            ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
          );
        }
        createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
        deletedCheckConstraints = prepareDeleteCheckConstraint(
          it.name,
          it.schema,
          it.deletedCheckConstraints
        );
        if (it.alteredCheckConstraints && action !== "push") {
          const added = {};
          const deleted = {};
          for (const k5 of Object.keys(it.alteredCheckConstraints)) {
            added[k5] = it.alteredCheckConstraints[k5].__new;
            deleted[k5] = it.alteredCheckConstraints[k5].__old;
          }
          createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
          deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
        }
        jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
        jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
        jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
      });
      const rColumns = jsonRenameColumnsStatements.map((it) => {
        const tableName = it.tableName;
        const schema6 = it.schema;
        return {
          from: { schema: schema6, table: tableName, column: it.oldColumnName },
          to: { schema: schema6, table: tableName, column: it.newColumnName }
        };
      });
      const jsonTableAlternations = alteredTables.map((it) => {
        return prepareAlterColumnsMysql(
          it.name,
          it.schema,
          it.altered,
          json1,
          json2,
          action
        );
      }).flat();
      const jsonCreateIndexesForAllAlteredTables = alteredTables.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.addedIndexes || {},
          curFull.internal
        );
      }).flat();
      const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => {
        return prepareDropIndexesJson(
          it.name,
          it.schema,
          it.deletedIndexes || {}
        );
      }).flat();
      alteredTables.forEach((it) => {
        const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__old;
            return current;
          },
          {}
        );
        const createdIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__new;
            return current;
          },
          {}
        );
        jsonCreateIndexesForAllAlteredTables.push(
          ...prepareCreateIndexesJson(it.name, it.schema, createdIndexes || {})
        );
        jsonDropIndexesForAllAlteredTables.push(
          ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
        );
      });
      const jsonSingleStoreCreateTables = createdTables.map((it) => {
        return prepareSingleStoreCreateTableJson(
          it,
          curFull,
          curFull.internal
        );
      });
      jsonStatements.push(...jsonSingleStoreCreateTables);
      jsonStatements.push(...jsonDropTables);
      jsonStatements.push(...jsonRenameTables);
      jsonStatements.push(...jsonRenameColumnsStatements);
      jsonStatements.push(...jsonDeletedUniqueConstraints);
      jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
      jsonStatements.push(...jsonTableAlternations);
      jsonStatements.push(...jsonAddedCompositePKs);
      jsonStatements.push(...jsonAddedUniqueConstraints);
      jsonStatements.push(...jsonDeletedUniqueConstraints);
      jsonStatements.push(...jsonAddColumnsStatemets);
      jsonStatements.push(...jsonCreateIndexesForCreatedTables);
      jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
      jsonStatements.push(...jsonDropColumnsStatemets);
      jsonStatements.push(...jsonAddedCompositePKs);
      jsonStatements.push(...jsonAlteredUniqueConstraints);
      const combinedJsonStatements = singleStoreCombineStatements(jsonStatements, json2);
      const sqlStatements = fromJson(combinedJsonStatements, "singlestore");
      const uniqueSqlStatements = [];
      sqlStatements.forEach((ss) => {
        if (!uniqueSqlStatements.includes(ss)) {
          uniqueSqlStatements.push(ss);
        }
      });
      const rTables = renamedTables.map((it) => {
        return { from: it.from, to: it.to };
      });
      const _meta = prepareMigrationMeta([], rTables, rColumns);
      return {
        statements: combinedJsonStatements,
        sqlStatements: uniqueSqlStatements,
        _meta
      };
    };
    applySqliteSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
      const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
      const {
        created: createdTables,
        deleted: deletedTables,
        renamed: renamedTables
      } = await tablesResolver2({
        created: tablesDiff.added,
        deleted: tablesDiff.deleted
      });
      const tablesPatchedSnap1 = copy(json1);
      tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
        const { name } = nameChangeFor(it, renamedTables);
        it.name = name;
        return [name, it];
      });
      const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
      const columnRenames = [];
      const columnCreates = [];
      const columnDeletes = [];
      for (let entry of Object.values(res)) {
        const { renamed, created, deleted } = await columnsResolver2({
          tableName: entry.name,
          schema: entry.schema,
          deleted: entry.columns.deleted,
          created: entry.columns.added
        });
        if (created.length > 0) {
          columnCreates.push({
            table: entry.name,
            columns: created
          });
        }
        if (deleted.length > 0) {
          columnDeletes.push({
            table: entry.name,
            columns: deleted
          });
        }
        if (renamed.length > 0) {
          columnRenames.push({
            table: entry.name,
            renames: renamed
          });
        }
      }
      const columnRenamesDict = columnRenames.reduce(
        (acc, it) => {
          acc[it.table] = it.renames;
          return acc;
        },
        {}
      );
      const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
      columnsPatchedSnap1.tables = mapEntries(
        columnsPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapKeys(
            tableValue.columns,
            (columnKey, column6) => {
              const rens = columnRenamesDict[tableValue.name] || [];
              const newName = columnChangeFor(columnKey, rens);
              column6.name = newName;
              return newName;
            }
          );
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      const viewsDiff = diffSchemasOrTables(json1.views, json2.views);
      const {
        created: createdViews,
        deleted: deletedViews,
        renamed: renamedViews
        // renamed or moved
      } = await viewsResolver2({
        created: viewsDiff.added,
        deleted: viewsDiff.deleted
      });
      const renamesViewDic = {};
      renamedViews.forEach((it) => {
        renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
      });
      const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
      viewsPatchedSnap1.views = mapEntries(
        viewsPatchedSnap1.views,
        (viewKey, viewValue) => {
          const rename = renamesViewDic[viewValue.name];
          if (rename) {
            viewValue.name = rename.to;
          }
          return [viewKey, viewValue];
        }
      );
      const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
      const typedResult = diffResultSchemeSQLite.parse(diffResult);
      const tablesMap = {};
      typedResult.alteredTablesWithColumns.forEach((obj) => {
        tablesMap[obj.name] = obj;
      });
      const jsonCreateTables = createdTables.map((it) => {
        return prepareSQLiteCreateTable(it, action);
      });
      const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.indexes,
          curFull.internal
        );
      }).flat();
      const jsonDropTables = deletedTables.map((it) => {
        return prepareDropTableJson(it);
      });
      const jsonRenameTables = renamedTables.map((it) => {
        return prepareRenameTableJson(it.from, it.to);
      });
      const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
      const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
      const jsonAddColumnsStatemets = columnCreates.map((it) => {
        return _prepareSqliteAddColumns(
          it.table,
          it.columns,
          tablesMap[it.table] && tablesMap[it.table].addedForeignKeys ? Object.values(tablesMap[it.table].addedForeignKeys) : []
        );
      }).flat();
      const allAltered = typedResult.alteredTablesWithColumns;
      const jsonAddedCompositePKs = [];
      const jsonDeletedCompositePKs = [];
      const jsonAlteredCompositePKs = [];
      const jsonAddedUniqueConstraints = [];
      const jsonDeletedUniqueConstraints = [];
      const jsonAlteredUniqueConstraints = [];
      const jsonDeletedCheckConstraints = [];
      const jsonCreatedCheckConstraints = [];
      allAltered.forEach((it) => {
        let addedColumns = [];
        for (const addedPkName of Object.keys(it.addedCompositePKs)) {
          const addedPkColumns = it.addedCompositePKs[addedPkName];
          addedColumns = SQLiteSquasher.unsquashPK(addedPkColumns);
        }
        let deletedColumns = [];
        for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
          const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
          deletedColumns = SQLiteSquasher.unsquashPK(deletedPkColumns);
        }
        const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
        let addedCompositePKs = [];
        let deletedCompositePKs = [];
        let alteredCompositePKs = [];
        if (doPerformDeleteAndCreate) {
          addedCompositePKs = prepareAddCompositePrimaryKeySqlite(
            it.name,
            it.addedCompositePKs
          );
          deletedCompositePKs = prepareDeleteCompositePrimaryKeySqlite(
            it.name,
            it.deletedCompositePKs
          );
        }
        alteredCompositePKs = prepareAlterCompositePrimaryKeySqlite(
          it.name,
          it.alteredCompositePKs
        );
        let addedUniqueConstraints = [];
        let deletedUniqueConstraints = [];
        let alteredUniqueConstraints = [];
        addedUniqueConstraints = prepareAddUniqueConstraintPg(
          it.name,
          it.schema,
          it.addedUniqueConstraints
        );
        deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
          it.name,
          it.schema,
          it.deletedUniqueConstraints
        );
        if (it.alteredUniqueConstraints) {
          const added = {};
          const deleted = {};
          for (const k5 of Object.keys(it.alteredUniqueConstraints)) {
            added[k5] = it.alteredUniqueConstraints[k5].__new;
            deleted[k5] = it.alteredUniqueConstraints[k5].__old;
          }
          addedUniqueConstraints.push(
            ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
          );
          deletedUniqueConstraints.push(
            ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
          );
        }
        let createdCheckConstraints = [];
        let deletedCheckConstraints = [];
        addedUniqueConstraints = prepareAddUniqueConstraintPg(
          it.name,
          it.schema,
          it.addedUniqueConstraints
        );
        deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
          it.name,
          it.schema,
          it.deletedUniqueConstraints
        );
        if (it.alteredUniqueConstraints) {
          const added = {};
          const deleted = {};
          for (const k5 of Object.keys(it.alteredUniqueConstraints)) {
            added[k5] = it.alteredUniqueConstraints[k5].__new;
            deleted[k5] = it.alteredUniqueConstraints[k5].__old;
          }
          addedUniqueConstraints.push(
            ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
          );
          deletedUniqueConstraints.push(
            ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
          );
        }
        createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
        deletedCheckConstraints = prepareDeleteCheckConstraint(
          it.name,
          it.schema,
          it.deletedCheckConstraints
        );
        if (it.alteredCheckConstraints && action !== "push") {
          const added = {};
          const deleted = {};
          for (const k5 of Object.keys(it.alteredCheckConstraints)) {
            added[k5] = it.alteredCheckConstraints[k5].__new;
            deleted[k5] = it.alteredCheckConstraints[k5].__old;
          }
          createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
          deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
        }
        jsonAddedCompositePKs.push(...addedCompositePKs);
        jsonDeletedCompositePKs.push(...deletedCompositePKs);
        jsonAlteredCompositePKs.push(...alteredCompositePKs);
        jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
        jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
        jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
        jsonCreatedCheckConstraints.push(...createdCheckConstraints);
        jsonDeletedCheckConstraints.push(...deletedCheckConstraints);
      });
      const rColumns = jsonRenameColumnsStatements.map((it) => {
        const tableName = it.tableName;
        const schema6 = it.schema;
        return {
          from: { schema: schema6, table: tableName, column: it.oldColumnName },
          to: { schema: schema6, table: tableName, column: it.newColumnName }
        };
      });
      const jsonTableAlternations = allAltered.map((it) => {
        return prepareSqliteAlterColumns(it.name, it.schema, it.altered, json2);
      }).flat();
      const jsonCreateIndexesForAllAlteredTables = allAltered.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.addedIndexes || {},
          curFull.internal
        );
      }).flat();
      const jsonDropIndexesForAllAlteredTables = allAltered.map((it) => {
        return prepareDropIndexesJson(
          it.name,
          it.schema,
          it.deletedIndexes || {}
        );
      }).flat();
      allAltered.forEach((it) => {
        const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__old;
            return current;
          },
          {}
        );
        const createdIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__new;
            return current;
          },
          {}
        );
        jsonCreateIndexesForAllAlteredTables.push(
          ...prepareCreateIndexesJson(
            it.name,
            it.schema,
            createdIndexes || {},
            curFull.internal
          )
        );
        jsonDropIndexesForAllAlteredTables.push(
          ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
        );
      });
      const jsonReferencesForAllAlteredTables = allAltered.map((it) => {
        const forAdded = prepareCreateReferencesJson(
          it.name,
          it.schema,
          it.addedForeignKeys
        );
        const forAltered = prepareDropReferencesJson(
          it.name,
          it.schema,
          it.deletedForeignKeys
        );
        const alteredFKs = prepareAlterReferencesJson(
          it.name,
          it.schema,
          it.alteredForeignKeys
        );
        return [...forAdded, ...forAltered, ...alteredFKs];
      }).flat();
      const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t6) => t6.type === "create_reference"
      );
      const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t6) => t6.type === "delete_reference"
      );
      const createViews = [];
      const dropViews = [];
      createViews.push(
        ...createdViews.filter((it) => !it.isExisting).map((it) => {
          return prepareSqliteCreateViewJson(
            it.name,
            it.definition
          );
        })
      );
      dropViews.push(
        ...deletedViews.filter((it) => !it.isExisting).map((it) => {
          return prepareDropViewJson(it.name);
        })
      );
      dropViews.push(
        ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
          return prepareDropViewJson(it.from.name);
        })
      );
      createViews.push(
        ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
          return prepareSqliteCreateViewJson(it.to.name, it.to.definition);
        })
      );
      const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting);
      for (const alteredView of alteredViews) {
        const { definition } = json2.views[alteredView.name];
        if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
          dropViews.push(prepareDropViewJson(alteredView.name));
          createViews.push(
            prepareSqliteCreateViewJson(
              alteredView.name,
              definition
            )
          );
        }
      }
      const jsonStatements = [];
      jsonStatements.push(...jsonCreateTables);
      jsonStatements.push(...jsonDropTables);
      jsonStatements.push(...jsonRenameTables);
      jsonStatements.push(...jsonRenameColumnsStatements);
      jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
      jsonStatements.push(...jsonDeletedCheckConstraints);
      jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
      jsonStatements.push(...jsonDeletedCompositePKs);
      jsonStatements.push(...jsonTableAlternations);
      jsonStatements.push(...jsonAddedCompositePKs);
      jsonStatements.push(...jsonAddColumnsStatemets);
      jsonStatements.push(...jsonCreateIndexesForCreatedTables);
      jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
      jsonStatements.push(...jsonCreatedCheckConstraints);
      jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
      jsonStatements.push(...jsonDropColumnsStatemets);
      jsonStatements.push(...jsonAlteredCompositePKs);
      jsonStatements.push(...jsonAlteredUniqueConstraints);
      jsonStatements.push(...dropViews);
      jsonStatements.push(...createViews);
      const combinedJsonStatements = sqliteCombineStatements(jsonStatements, json2, action);
      const sqlStatements = fromJson(combinedJsonStatements, "sqlite");
      const uniqueSqlStatements = [];
      sqlStatements.forEach((ss) => {
        if (!uniqueSqlStatements.includes(ss)) {
          uniqueSqlStatements.push(ss);
        }
      });
      const rTables = renamedTables.map((it) => {
        return { from: it.from, to: it.to };
      });
      const _meta = prepareMigrationMeta([], rTables, rColumns);
      return {
        statements: combinedJsonStatements,
        sqlStatements: uniqueSqlStatements,
        _meta
      };
    };
    applyLibSQLSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
      const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
      const {
        created: createdTables,
        deleted: deletedTables,
        renamed: renamedTables
      } = await tablesResolver2({
        created: tablesDiff.added,
        deleted: tablesDiff.deleted
      });
      const tablesPatchedSnap1 = copy(json1);
      tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
        const { name } = nameChangeFor(it, renamedTables);
        it.name = name;
        return [name, it];
      });
      const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
      const columnRenames = [];
      const columnCreates = [];
      const columnDeletes = [];
      for (let entry of Object.values(res)) {
        const { renamed, created, deleted } = await columnsResolver2({
          tableName: entry.name,
          schema: entry.schema,
          deleted: entry.columns.deleted,
          created: entry.columns.added
        });
        if (created.length > 0) {
          columnCreates.push({
            table: entry.name,
            columns: created
          });
        }
        if (deleted.length > 0) {
          columnDeletes.push({
            table: entry.name,
            columns: deleted
          });
        }
        if (renamed.length > 0) {
          columnRenames.push({
            table: entry.name,
            renames: renamed
          });
        }
      }
      const columnRenamesDict = columnRenames.reduce(
        (acc, it) => {
          acc[it.table] = it.renames;
          return acc;
        },
        {}
      );
      const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
      columnsPatchedSnap1.tables = mapEntries(
        columnsPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapKeys(
            tableValue.columns,
            (columnKey, column6) => {
              const rens = columnRenamesDict[tableValue.name] || [];
              const newName = columnChangeFor(columnKey, rens);
              column6.name = newName;
              return newName;
            }
          );
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      const viewsDiff = diffSchemasOrTables(json1.views, json2.views);
      const {
        created: createdViews,
        deleted: deletedViews,
        renamed: renamedViews
        // renamed or moved
      } = await viewsResolver2({
        created: viewsDiff.added,
        deleted: viewsDiff.deleted
      });
      const renamesViewDic = {};
      renamedViews.forEach((it) => {
        renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
      });
      const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
      viewsPatchedSnap1.views = mapEntries(
        viewsPatchedSnap1.views,
        (viewKey, viewValue) => {
          const rename = renamesViewDic[viewValue.name];
          if (rename) {
            viewValue.name = rename.to;
          }
          return [viewKey, viewValue];
        }
      );
      const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
      const typedResult = diffResultSchemeSQLite.parse(diffResult);
      const tablesMap = {};
      typedResult.alteredTablesWithColumns.forEach((obj) => {
        tablesMap[obj.name] = obj;
      });
      const jsonCreateTables = createdTables.map((it) => {
        return prepareSQLiteCreateTable(it, action);
      });
      const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.indexes,
          curFull.internal
        );
      }).flat();
      const jsonDropTables = deletedTables.map((it) => {
        return prepareDropTableJson(it);
      });
      const jsonRenameTables = renamedTables.map((it) => {
        return prepareRenameTableJson(it.from, it.to);
      });
      const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
      const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
      const jsonAddColumnsStatemets = columnCreates.map((it) => {
        return _prepareSqliteAddColumns(
          it.table,
          it.columns,
          tablesMap[it.table] && tablesMap[it.table].addedForeignKeys ? Object.values(tablesMap[it.table].addedForeignKeys) : []
        );
      }).flat();
      const rColumns = jsonRenameColumnsStatements.map((it) => {
        const tableName = it.tableName;
        const schema6 = it.schema;
        return {
          from: { schema: schema6, table: tableName, column: it.oldColumnName },
          to: { schema: schema6, table: tableName, column: it.newColumnName }
        };
      });
      const rTables = renamedTables.map((it) => {
        return { from: it.from, to: it.to };
      });
      const _meta = prepareMigrationMeta([], rTables, rColumns);
      const allAltered = typedResult.alteredTablesWithColumns;
      const jsonAddedCompositePKs = [];
      const jsonDeletedCompositePKs = [];
      const jsonAlteredCompositePKs = [];
      const jsonAddedUniqueConstraints = [];
      const jsonDeletedUniqueConstraints = [];
      const jsonAlteredUniqueConstraints = [];
      const jsonDeletedCheckConstraints = [];
      const jsonCreatedCheckConstraints = [];
      allAltered.forEach((it) => {
        let addedColumns = [];
        for (const addedPkName of Object.keys(it.addedCompositePKs)) {
          const addedPkColumns = it.addedCompositePKs[addedPkName];
          addedColumns = SQLiteSquasher.unsquashPK(addedPkColumns);
        }
        let deletedColumns = [];
        for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
          const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
          deletedColumns = SQLiteSquasher.unsquashPK(deletedPkColumns);
        }
        const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
        let addedCompositePKs = [];
        let deletedCompositePKs = [];
        let alteredCompositePKs = [];
        if (doPerformDeleteAndCreate) {
          addedCompositePKs = prepareAddCompositePrimaryKeySqlite(
            it.name,
            it.addedCompositePKs
          );
          deletedCompositePKs = prepareDeleteCompositePrimaryKeySqlite(
            it.name,
            it.deletedCompositePKs
          );
        }
        alteredCompositePKs = prepareAlterCompositePrimaryKeySqlite(
          it.name,
          it.alteredCompositePKs
        );
        let addedUniqueConstraints = [];
        let deletedUniqueConstraints = [];
        let alteredUniqueConstraints = [];
        let createdCheckConstraints = [];
        let deletedCheckConstraints = [];
        addedUniqueConstraints = prepareAddUniqueConstraintPg(
          it.name,
          it.schema,
          it.addedUniqueConstraints
        );
        deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
          it.name,
          it.schema,
          it.deletedUniqueConstraints
        );
        if (it.alteredUniqueConstraints) {
          const added = {};
          const deleted = {};
          for (const k5 of Object.keys(it.alteredUniqueConstraints)) {
            added[k5] = it.alteredUniqueConstraints[k5].__new;
            deleted[k5] = it.alteredUniqueConstraints[k5].__old;
          }
          addedUniqueConstraints.push(
            ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
          );
          deletedUniqueConstraints.push(
            ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
          );
        }
        createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
        deletedCheckConstraints = prepareDeleteCheckConstraint(
          it.name,
          it.schema,
          it.deletedCheckConstraints
        );
        if (it.alteredCheckConstraints && action !== "push") {
          const added = {};
          const deleted = {};
          for (const k5 of Object.keys(it.alteredCheckConstraints)) {
            added[k5] = it.alteredCheckConstraints[k5].__new;
            deleted[k5] = it.alteredCheckConstraints[k5].__old;
          }
          createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
          deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
        }
        jsonAddedCompositePKs.push(...addedCompositePKs);
        jsonDeletedCompositePKs.push(...deletedCompositePKs);
        jsonAlteredCompositePKs.push(...alteredCompositePKs);
        jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
        jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
        jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
        jsonCreatedCheckConstraints.push(...createdCheckConstraints);
        jsonDeletedCheckConstraints.push(...deletedCheckConstraints);
      });
      const jsonTableAlternations = allAltered.map((it) => {
        return prepareSqliteAlterColumns(it.name, it.schema, it.altered, json2);
      }).flat();
      const jsonCreateIndexesForAllAlteredTables = allAltered.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.addedIndexes || {},
          curFull.internal
        );
      }).flat();
      const jsonDropIndexesForAllAlteredTables = allAltered.map((it) => {
        return prepareDropIndexesJson(
          it.name,
          it.schema,
          it.deletedIndexes || {}
        );
      }).flat();
      allAltered.forEach((it) => {
        const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__old;
            return current;
          },
          {}
        );
        const createdIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__new;
            return current;
          },
          {}
        );
        jsonCreateIndexesForAllAlteredTables.push(
          ...prepareCreateIndexesJson(
            it.name,
            it.schema,
            createdIndexes || {},
            curFull.internal
          )
        );
        jsonDropIndexesForAllAlteredTables.push(
          ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
        );
      });
      const jsonReferencesForAllAlteredTables = allAltered.map((it) => {
        const forAdded = prepareLibSQLCreateReferencesJson(
          it.name,
          it.schema,
          it.addedForeignKeys,
          json2,
          action
        );
        const forAltered = prepareLibSQLDropReferencesJson(
          it.name,
          it.schema,
          it.deletedForeignKeys,
          json2,
          _meta,
          action
        );
        const alteredFKs = prepareAlterReferencesJson(it.name, it.schema, it.alteredForeignKeys);
        return [...forAdded, ...forAltered, ...alteredFKs];
      }).flat();
      const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t6) => t6.type === "create_reference"
      );
      const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t6) => t6.type === "delete_reference"
      );
      const createViews = [];
      const dropViews = [];
      createViews.push(
        ...createdViews.filter((it) => !it.isExisting).map((it) => {
          return prepareSqliteCreateViewJson(
            it.name,
            it.definition
          );
        })
      );
      dropViews.push(
        ...deletedViews.filter((it) => !it.isExisting).map((it) => {
          return prepareDropViewJson(it.name);
        })
      );
      dropViews.push(
        ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
          return prepareDropViewJson(it.from.name);
        })
      );
      createViews.push(
        ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
          return prepareSqliteCreateViewJson(it.to.name, it.to.definition);
        })
      );
      const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting);
      for (const alteredView of alteredViews) {
        const { definition } = json2.views[alteredView.name];
        if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
          dropViews.push(prepareDropViewJson(alteredView.name));
          createViews.push(
            prepareSqliteCreateViewJson(
              alteredView.name,
              definition
            )
          );
        }
      }
      const jsonStatements = [];
      jsonStatements.push(...jsonCreateTables);
      jsonStatements.push(...jsonDropTables);
      jsonStatements.push(...jsonRenameTables);
      jsonStatements.push(...jsonRenameColumnsStatements);
      jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
      jsonStatements.push(...jsonDeletedCheckConstraints);
      jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
      jsonStatements.push(...jsonDeletedCompositePKs);
      jsonStatements.push(...jsonTableAlternations);
      jsonStatements.push(...jsonAddedCompositePKs);
      jsonStatements.push(...jsonAddColumnsStatemets);
      jsonStatements.push(...jsonCreateIndexesForCreatedTables);
      jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
      jsonStatements.push(...jsonCreatedCheckConstraints);
      jsonStatements.push(...dropViews);
      jsonStatements.push(...createViews);
      jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
      jsonStatements.push(...jsonDropColumnsStatemets);
      jsonStatements.push(...jsonAlteredCompositePKs);
      jsonStatements.push(...jsonAlteredUniqueConstraints);
      const combinedJsonStatements = libSQLCombineStatements(jsonStatements, json2, action);
      const sqlStatements = fromJson(
        combinedJsonStatements,
        "turso",
        action,
        json2
      );
      const uniqueSqlStatements = [];
      sqlStatements.forEach((ss) => {
        if (!uniqueSqlStatements.includes(ss)) {
          uniqueSqlStatements.push(ss);
        }
      });
      return {
        statements: combinedJsonStatements,
        sqlStatements: uniqueSqlStatements,
        _meta
      };
    };
  }
});

// src/utils/words.ts
var init_words = __esm({
  "src/utils/words.ts"() {
    "use strict";
  }
});

// src/schemaValidator.ts
var dialects, dialect4, commonSquashedSchema, commonSchema;
var init_schemaValidator = __esm({
  "src/schemaValidator.ts"() {
    "use strict";
    init_esm();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    dialects = ["postgresql", "mysql", "sqlite", "turso", "singlestore", "gel"];
    dialect4 = enumType(dialects);
    commonSquashedSchema = unionType([
      pgSchemaSquashed,
      mysqlSchemaSquashed,
      SQLiteSchemaSquashed,
      singlestoreSchemaSquashed
    ]);
    commonSchema = unionType([pgSchema, mysqlSchema, sqliteSchema, singlestoreSchema]);
  }
});

// src/cli/validations/common.ts
var sqliteDriversLiterals, postgresqlDriversLiterals, prefixes, prefix, casingTypes, casingType, sqliteDriver, postgresDriver, driver, configMigrations, configCommonSchema, casing, introspectParams, configIntrospectCliSchema, configGenerateSchema, configPushSchema;
var init_common = __esm({
  "src/cli/validations/common.ts"() {
    "use strict";
    init_esm();
    init_schemaValidator();
    init_outputs();
    sqliteDriversLiterals = [
      literalType("d1-http"),
      literalType("expo"),
      literalType("durable-sqlite")
    ];
    postgresqlDriversLiterals = [
      literalType("aws-data-api"),
      literalType("pglite")
    ];
    prefixes = [
      "index",
      "timestamp",
      "supabase",
      "unix",
      "none"
    ];
    prefix = enumType(prefixes);
    {
      const _3 = "";
    }
    casingTypes = ["snake_case", "camelCase"];
    casingType = enumType(casingTypes);
    sqliteDriver = unionType(sqliteDriversLiterals);
    postgresDriver = unionType(postgresqlDriversLiterals);
    driver = unionType([sqliteDriver, postgresDriver]);
    configMigrations = objectType({
      table: stringType().optional(),
      schema: stringType().optional(),
      prefix: prefix.optional().default("index")
    }).optional();
    configCommonSchema = objectType({
      dialect: dialect4,
      schema: unionType([stringType(), stringType().array()]).optional(),
      out: stringType().optional(),
      breakpoints: booleanType().optional().default(true),
      verbose: booleanType().optional().default(false),
      driver: driver.optional(),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
      migrations: configMigrations,
      dbCredentials: anyType().optional(),
      casing: casingType.optional(),
      sql: booleanType().default(true)
    }).passthrough();
    casing = unionType([literalType("camel"), literalType("preserve")]).default(
      "camel"
    );
    introspectParams = objectType({
      schema: unionType([stringType(), stringType().array()]).optional(),
      out: stringType().optional().default("./drizzle"),
      breakpoints: booleanType().default(true),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
      introspect: objectType({
        casing
      }).default({ casing: "camel" })
    });
    configIntrospectCliSchema = objectType({
      schema: unionType([stringType(), stringType().array()]).optional(),
      out: stringType().optional().default("./drizzle"),
      breakpoints: booleanType().default(true),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
      introspectCasing: unionType([literalType("camel"), literalType("preserve")]).default(
        "camel"
      )
    });
    configGenerateSchema = objectType({
      schema: unionType([stringType(), stringType().array()]),
      out: stringType().optional().default("./drizzle"),
      breakpoints: booleanType().default(true)
    });
    configPushSchema = objectType({
      dialect: dialect4,
      schema: unionType([stringType(), stringType().array()]),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
      verbose: booleanType().default(false),
      strict: booleanType().default(false),
      out: stringType().optional()
    });
  }
});

// src/cli/validations/outputs.ts
var withStyle;
var init_outputs = __esm({
  "src/cli/validations/outputs.ts"() {
    "use strict";
    init_source();
    init_common();
    withStyle = {
      error: (str) => `${source_default.red(`${source_default.white.bgRed(" Invalid input ")} ${str}`)}`,
      warning: (str) => `${source_default.white.bgGray(" Warning ")} ${str}`,
      errorWarning: (str) => `${source_default.red(`${source_default.white.bgRed(" Warning ")} ${str}`)}`,
      fullWarning: (str) => `${source_default.black.bgYellow(" Warning ")} ${source_default.bold(str)}`,
      suggestion: (str) => `${source_default.white.bgGray(" Suggestion ")} ${str}`,
      info: (str) => `${source_default.grey(str)}`
    };
  }
});

// src/cli/commands/migrate.ts
var import_hanji2, schemasResolver, tablesResolver, viewsResolver, mySqlViewsResolver, sqliteViewsResolver, sequencesResolver, roleResolver, policyResolver, indPolicyResolver, enumsResolver, columnsResolver, promptColumnsConflicts, promptNamedConflict, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT;
var init_migrate = __esm({
  "src/cli/commands/migrate.ts"() {
    "use strict";
    init_migrationPreparator();
    init_source();
    import_hanji2 = __toESM(require_hanji());
    init_singlestoreSchema();
    init_mysqlSchema();
    init_pgSchema();
    init_sqliteSchema();
    init_snapshotsDiffer();
    init_utils();
    init_words();
    init_outputs();
    init_views();
    schemasResolver = async (input) => {
      try {
        const { created, deleted, renamed } = await promptSchemasConflict(
          input.created,
          input.deleted
        );
        return { created, deleted, renamed };
      } catch (e6) {
        console.error(e6);
        throw e6;
      }
    };
    tablesResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "table"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e6) {
        console.error(e6);
        throw e6;
      }
    };
    viewsResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "view"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e6) {
        console.error(e6);
        throw e6;
      }
    };
    mySqlViewsResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "view"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e6) {
        console.error(e6);
        throw e6;
      }
    };
    sqliteViewsResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "view"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e6) {
        console.error(e6);
        throw e6;
      }
    };
    sequencesResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "sequence"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e6) {
        console.error(e6);
        throw e6;
      }
    };
    roleResolver = async (input) => {
      const result = await promptNamedConflict(
        input.created,
        input.deleted,
        "role"
      );
      return {
        created: result.created,
        deleted: result.deleted,
        renamed: result.renamed
      };
    };
    policyResolver = async (input) => {
      const result = await promptColumnsConflicts(
        input.tableName,
        input.created,
        input.deleted
      );
      return {
        tableName: input.tableName,
        schema: input.schema,
        created: result.created,
        deleted: result.deleted,
        renamed: result.renamed
      };
    };
    indPolicyResolver = async (input) => {
      const result = await promptNamedConflict(
        input.created,
        input.deleted,
        "policy"
      );
      return {
        created: result.created,
        deleted: result.deleted,
        renamed: result.renamed
      };
    };
    enumsResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "enum"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e6) {
        console.error(e6);
        throw e6;
      }
    };
    columnsResolver = async (input) => {
      const result = await promptColumnsConflicts(
        input.tableName,
        input.created,
        input.deleted
      );
      return {
        tableName: input.tableName,
        schema: input.schema,
        created: result.created,
        deleted: result.deleted,
        renamed: result.renamed
      };
    };
    promptColumnsConflicts = async (tableName, newColumns, missingColumns) => {
      if (newColumns.length === 0 || missingColumns.length === 0) {
        return { created: newColumns, renamed: [], deleted: missingColumns };
      }
      const result = {
        created: [],
        renamed: [],
        deleted: []
      };
      let index6 = 0;
      let leftMissing = [...missingColumns];
      do {
        const created = newColumns[index6];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji2.render)(
          new ResolveColumnSelect(tableName, created, promptData)
        );
        if (status === "aborted") {
          console.error("ERROR");
          process.exit(1);
        }
        if (isRenamePromptItem(data)) {
          console.log(
            `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
              "column will be renamed"
            )}`
          );
          result.renamed.push(data);
          delete leftMissing[leftMissing.indexOf(data.from)];
          leftMissing = leftMissing.filter(Boolean);
        } else {
          console.log(
            `${source_default.green("+")} ${data.name} ${source_default.gray(
              "column will be created"
            )}`
          );
          result.created.push(created);
        }
        index6 += 1;
      } while (index6 < newColumns.length);
      console.log(
        source_default.gray(`--- all columns conflicts in ${tableName} table resolved ---
`)
      );
      result.deleted.push(...leftMissing);
      return result;
    };
    promptNamedConflict = async (newItems, missingItems, entity) => {
      if (missingItems.length === 0 || newItems.length === 0) {
        return {
          created: newItems,
          renamed: [],
          deleted: missingItems
        };
      }
      const result = { created: [], renamed: [], deleted: [] };
      let index6 = 0;
      let leftMissing = [...missingItems];
      do {
        const created = newItems[index6];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji2.render)(
          new ResolveSelectNamed(created, promptData, entity)
        );
        if (status === "aborted") {
          console.error("ERROR");
          process.exit(1);
        }
        if (isRenamePromptItem(data)) {
          console.log(
            `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
              `${entity} will be renamed/moved`
            )}`
          );
          if (data.from.name !== data.to.name) {
            result.renamed.push(data);
          }
          delete leftMissing[leftMissing.indexOf(data.from)];
          leftMissing = leftMissing.filter(Boolean);
        } else {
          console.log(
            `${source_default.green("+")} ${data.name} ${source_default.gray(
              `${entity} will be created`
            )}`
          );
          result.created.push(created);
        }
        index6 += 1;
      } while (index6 < newItems.length);
      console.log(source_default.gray(`--- all ${entity} conflicts resolved ---
`));
      result.deleted.push(...leftMissing);
      return result;
    };
    promptNamedWithSchemasConflict = async (newItems, missingItems, entity) => {
      if (missingItems.length === 0 || newItems.length === 0) {
        return {
          created: newItems,
          renamed: [],
          moved: [],
          deleted: missingItems
        };
      }
      const result = { created: [], renamed: [], moved: [], deleted: [] };
      let index6 = 0;
      let leftMissing = [...missingItems];
      do {
        const created = newItems[index6];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji2.render)(
          new ResolveSelect(created, promptData, entity)
        );
        if (status === "aborted") {
          console.error("ERROR");
          process.exit(1);
        }
        if (isRenamePromptItem(data)) {
          const schemaFromPrefix = !data.from.schema || data.from.schema === "public" ? "" : `${data.from.schema}.`;
          const schemaToPrefix = !data.to.schema || data.to.schema === "public" ? "" : `${data.to.schema}.`;
          console.log(
            `${source_default.yellow("~")} ${schemaFromPrefix}${data.from.name} \u203A ${schemaToPrefix}${data.to.name} ${source_default.gray(
              `${entity} will be renamed/moved`
            )}`
          );
          if (data.from.name !== data.to.name) {
            result.renamed.push(data);
          }
          if (data.from.schema !== data.to.schema) {
            result.moved.push({
              name: data.from.name,
              schemaFrom: data.from.schema || "public",
              schemaTo: data.to.schema || "public"
            });
          }
          delete leftMissing[leftMissing.indexOf(data.from)];
          leftMissing = leftMissing.filter(Boolean);
        } else {
          console.log(
            `${source_default.green("+")} ${data.name} ${source_default.gray(
              `${entity} will be created`
            )}`
          );
          result.created.push(created);
        }
        index6 += 1;
      } while (index6 < newItems.length);
      console.log(source_default.gray(`--- all ${entity} conflicts resolved ---
`));
      result.deleted.push(...leftMissing);
      return result;
    };
    promptSchemasConflict = async (newSchemas, missingSchemas) => {
      if (missingSchemas.length === 0 || newSchemas.length === 0) {
        return { created: newSchemas, renamed: [], deleted: missingSchemas };
      }
      const result = {
        created: [],
        renamed: [],
        deleted: []
      };
      let index6 = 0;
      let leftMissing = [...missingSchemas];
      do {
        const created = newSchemas[index6];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji2.render)(
          new ResolveSchemasSelect(created, promptData)
        );
        if (status === "aborted") {
          console.error("ERROR");
          process.exit(1);
        }
        if (isRenamePromptItem(data)) {
          console.log(
            `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
              "schema will be renamed"
            )}`
          );
          result.renamed.push(data);
          delete leftMissing[leftMissing.indexOf(data.from)];
          leftMissing = leftMissing.filter(Boolean);
        } else {
          console.log(
            `${source_default.green("+")} ${data.name} ${source_default.gray(
              "schema will be created"
            )}`
          );
          result.created.push(created);
        }
        index6 += 1;
      } while (index6 < newSchemas.length);
      console.log(source_default.gray("--- all schemas conflicts resolved ---\n"));
      result.deleted.push(...leftMissing);
      return result;
    };
    BREAKPOINT = "--> statement-breakpoint\n";
  }
});

// ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/brace-expressions.js
var posixClasses, braceEscape, regexpEscape, rangesToString, parseClass;
var init_brace_expressions = __esm({
  "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/brace-expressions.js"() {
    "use strict";
    posixClasses = {
      "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
      "[:alpha:]": ["\\p{L}\\p{Nl}", true],
      "[:ascii:]": ["\\x00-\\x7f", false],
      "[:blank:]": ["\\p{Zs}\\t", true],
      "[:cntrl:]": ["\\p{Cc}", true],
      "[:digit:]": ["\\p{Nd}", true],
      "[:graph:]": ["\\p{Z}\\p{C}", true, true],
      "[:lower:]": ["\\p{Ll}", true],
      "[:print:]": ["\\p{C}", true],
      "[:punct:]": ["\\p{P}", true],
      "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true],
      "[:upper:]": ["\\p{Lu}", true],
      "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true],
      "[:xdigit:]": ["A-Fa-f0-9", false]
    };
    braceEscape = (s6) => s6.replace(/[[\]\\-]/g, "\\$&");
    regexpEscape = (s6) => s6.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    rangesToString = (ranges) => ranges.join("");
    parseClass = (glob2, position) => {
      const pos = position;
      if (glob2.charAt(pos) !== "[") {
        throw new Error("not in a brace expression");
      }
      const ranges = [];
      const negs = [];
      let i6 = pos + 1;
      let sawStart = false;
      let uflag = false;
      let escaping = false;
      let negate2 = false;
      let endPos = pos;
      let rangeStart = "";
      WHILE: while (i6 < glob2.length) {
        const c5 = glob2.charAt(i6);
        if ((c5 === "!" || c5 === "^") && i6 === pos + 1) {
          negate2 = true;
          i6++;
          continue;
        }
        if (c5 === "]" && sawStart && !escaping) {
          endPos = i6 + 1;
          break;
        }
        sawStart = true;
        if (c5 === "\\") {
          if (!escaping) {
            escaping = true;
            i6++;
            continue;
          }
        }
        if (c5 === "[" && !escaping) {
          for (const [cls, [unip, u5, neg]] of Object.entries(posixClasses)) {
            if (glob2.startsWith(cls, i6)) {
              if (rangeStart) {
                return ["$.", false, glob2.length - pos, true];
              }
              i6 += cls.length;
              if (neg)
                negs.push(unip);
              else
                ranges.push(unip);
              uflag = uflag || u5;
              continue WHILE;
            }
          }
        }
        escaping = false;
        if (rangeStart) {
          if (c5 > rangeStart) {
            ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c5));
          } else if (c5 === rangeStart) {
            ranges.push(braceEscape(c5));
          }
          rangeStart = "";
          i6++;
          continue;
        }
        if (glob2.startsWith("-]", i6 + 1)) {
          ranges.push(braceEscape(c5 + "-"));
          i6 += 2;
          continue;
        }
        if (glob2.startsWith("-", i6 + 1)) {
          rangeStart = c5;
          i6 += 2;
          continue;
        }
        ranges.push(braceEscape(c5));
        i6++;
      }
      if (endPos < i6) {
        return ["", false, 0, false];
      }
      if (!ranges.length && !negs.length) {
        return ["$.", false, glob2.length - pos, true];
      }
      if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate2) {
        const r6 = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
        return [regexpEscape(r6), false, endPos - pos, false];
      }
      const sranges = "[" + (negate2 ? "^" : "") + rangesToString(ranges) + "]";
      const snegs = "[" + (negate2 ? "" : "^") + rangesToString(negs) + "]";
      const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs;
      return [comb, uflag, endPos - pos, true];
    };
  }
});

// ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/escape.js
var escape;
var init_escape = __esm({
  "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/escape.js"() {
    "use strict";
    escape = (s6, { windowsPathsNoEscape = false } = {}) => {
      return windowsPathsNoEscape ? s6.replace(/[?*()[\]]/g, "[$&]") : s6.replace(/[?*()[\]\\]/g, "\\$&");
    };
  }
});

// ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/unescape.js
var unescape2;
var init_unescape = __esm({
  "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/unescape.js"() {
    "use strict";
    unescape2 = (s6, { windowsPathsNoEscape = false } = {}) => {
      return windowsPathsNoEscape ? s6.replace(/\[([^\/\\])\]/g, "$1") : s6.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
    };
  }
});

// ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/index.js
var import_brace_expansion, minimatch, starDotExtRE, starDotExtTest, starDotExtTestDot, starDotExtTestNocase, starDotExtTestNocaseDot, starDotStarRE, starDotStarTest, starDotStarTestDot, dotStarRE, dotStarTest, starRE, starTest, starTestDot, qmarksRE, qmarksTestNocase, qmarksTestNocaseDot, qmarksTestDot, qmarksTest, qmarksTestNoExt, qmarksTestNoExtDot, defaultPlatform, path, sep, GLOBSTAR, plTypes, qmark, star, twoStarDot, twoStarNoDot, charSet, reSpecials, addPatternStartSet, filter, ext, defaults, braceExpand, MAX_PATTERN_LENGTH, assertValidPattern, makeRe, match, globUnescape, globMagic, regExpEscape, Minimatch;
var init_mjs = __esm({
  "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/index.js"() {
    "use strict";
    import_brace_expansion = __toESM(require_brace_expansion(), 1);
    init_brace_expressions();
    init_escape();
    init_unescape();
    init_escape();
    init_unescape();
    minimatch = (p5, pattern, options = {}) => {
      assertValidPattern(pattern);
      if (!options.nocomment && pattern.charAt(0) === "#") {
        return false;
      }
      return new Minimatch(pattern, options).match(p5);
    };
    starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
    starDotExtTest = (ext2) => (f7) => !f7.startsWith(".") && f7.endsWith(ext2);
    starDotExtTestDot = (ext2) => (f7) => f7.endsWith(ext2);
    starDotExtTestNocase = (ext2) => {
      ext2 = ext2.toLowerCase();
      return (f7) => !f7.startsWith(".") && f7.toLowerCase().endsWith(ext2);
    };
    starDotExtTestNocaseDot = (ext2) => {
      ext2 = ext2.toLowerCase();
      return (f7) => f7.toLowerCase().endsWith(ext2);
    };
    starDotStarRE = /^\*+\.\*+$/;
    starDotStarTest = (f7) => !f7.startsWith(".") && f7.includes(".");
    starDotStarTestDot = (f7) => f7 !== "." && f7 !== ".." && f7.includes(".");
    dotStarRE = /^\.\*+$/;
    dotStarTest = (f7) => f7 !== "." && f7 !== ".." && f7.startsWith(".");
    starRE = /^\*+$/;
    starTest = (f7) => f7.length !== 0 && !f7.startsWith(".");
    starTestDot = (f7) => f7.length !== 0 && f7 !== "." && f7 !== "..";
    qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
    qmarksTestNocase = ([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExt([$0]);
      if (!ext2)
        return noext;
      ext2 = ext2.toLowerCase();
      return (f7) => noext(f7) && f7.toLowerCase().endsWith(ext2);
    };
    qmarksTestNocaseDot = ([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExtDot([$0]);
      if (!ext2)
        return noext;
      ext2 = ext2.toLowerCase();
      return (f7) => noext(f7) && f7.toLowerCase().endsWith(ext2);
    };
    qmarksTestDot = ([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExtDot([$0]);
      return !ext2 ? noext : (f7) => noext(f7) && f7.endsWith(ext2);
    };
    qmarksTest = ([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExt([$0]);
      return !ext2 ? noext : (f7) => noext(f7) && f7.endsWith(ext2);
    };
    qmarksTestNoExt = ([$0]) => {
      const len = $0.length;
      return (f7) => f7.length === len && !f7.startsWith(".");
    };
    qmarksTestNoExtDot = ([$0]) => {
      const len = $0.length;
      return (f7) => f7.length === len && f7 !== "." && f7 !== "..";
    };
    defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
    path = {
      win32: { sep: "\\" },
      posix: { sep: "/" }
    };
    sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep;
    minimatch.sep = sep;
    GLOBSTAR = Symbol("globstar **");
    minimatch.GLOBSTAR = GLOBSTAR;
    plTypes = {
      "!": { open: "(?:(?!(?:", close: "))[^/]*?)" },
      "?": { open: "(?:", close: ")?" },
      "+": { open: "(?:", close: ")+" },
      "*": { open: "(?:", close: ")*" },
      "@": { open: "(?:", close: ")" }
    };
    qmark = "[^/]";
    star = qmark + "*?";
    twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
    twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
    charSet = (s6) => s6.split("").reduce((set, c5) => {
      set[c5] = true;
      return set;
    }, {});
    reSpecials = charSet("().*{}+?[]^$\\!");
    addPatternStartSet = charSet("[.(");
    filter = (pattern, options = {}) => (p5) => minimatch(p5, pattern, options);
    minimatch.filter = filter;
    ext = (a5, b5 = {}) => Object.assign({}, a5, b5);
    defaults = (def) => {
      if (!def || typeof def !== "object" || !Object.keys(def).length) {
        return minimatch;
      }
      const orig = minimatch;
      const m6 = (p5, pattern, options = {}) => orig(p5, pattern, ext(def, options));
      return Object.assign(m6, {
        Minimatch: class Minimatch extends orig.Minimatch {
          constructor(pattern, options = {}) {
            super(pattern, ext(def, options));
          }
          static defaults(options) {
            return orig.defaults(ext(def, options)).Minimatch;
          }
        },
        unescape: (s6, options = {}) => orig.unescape(s6, ext(def, options)),
        escape: (s6, options = {}) => orig.escape(s6, ext(def, options)),
        filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
        defaults: (options) => orig.defaults(ext(def, options)),
        makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
        braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
        match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
        sep: orig.sep,
        GLOBSTAR
      });
    };
    minimatch.defaults = defaults;
    braceExpand = (pattern, options = {}) => {
      assertValidPattern(pattern);
      if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
        return [pattern];
      }
      return (0, import_brace_expansion.default)(pattern);
    };
    minimatch.braceExpand = braceExpand;
    MAX_PATTERN_LENGTH = 1024 * 64;
    assertValidPattern = (pattern) => {
      if (typeof pattern !== "string") {
        throw new TypeError("invalid pattern");
      }
      if (pattern.length > MAX_PATTERN_LENGTH) {
        throw new TypeError("pattern is too long");
      }
    };
    makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
    minimatch.makeRe = makeRe;
    match = (list, pattern, options = {}) => {
      const mm = new Minimatch(pattern, options);
      list = list.filter((f7) => mm.match(f7));
      if (mm.options.nonull && !list.length) {
        list.push(pattern);
      }
      return list;
    };
    minimatch.match = match;
    globUnescape = (s6) => s6.replace(/\\(.)/g, "$1");
    globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
    regExpEscape = (s6) => s6.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    Minimatch = class {
      constructor(pattern, options = {}) {
        __publicField(this, "options");
        __publicField(this, "set");
        __publicField(this, "pattern");
        __publicField(this, "windowsPathsNoEscape");
        __publicField(this, "nonegate");
        __publicField(this, "negate");
        __publicField(this, "comment");
        __publicField(this, "empty");
        __publicField(this, "preserveMultipleSlashes");
        __publicField(this, "partial");
        __publicField(this, "globSet");
        __publicField(this, "globParts");
        __publicField(this, "nocase");
        __publicField(this, "isWindows");
        __publicField(this, "platform");
        __publicField(this, "windowsNoMagicRoot");
        __publicField(this, "regexp");
        assertValidPattern(pattern);
        options = options || {};
        this.options = options;
        this.pattern = pattern;
        this.platform = options.platform || defaultPlatform;
        this.isWindows = this.platform === "win32";
        this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
        if (this.windowsPathsNoEscape) {
          this.pattern = this.pattern.replace(/\\/g, "/");
        }
        this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
        this.regexp = null;
        this.negate = false;
        this.nonegate = !!options.nonegate;
        this.comment = false;
        this.empty = false;
        this.partial = !!options.partial;
        this.nocase = !!this.options.nocase;
        this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
        this.globSet = [];
        this.globParts = [];
        this.set = [];
        this.make();
      }
      hasMagic() {
        if (this.options.magicalBraces && this.set.length > 1) {
          return true;
        }
        for (const pattern of this.set) {
          for (const part of pattern) {
            if (typeof part !== "string")
              return true;
          }
        }
        return false;
      }
      debug(..._3) {
      }
      make() {
        const pattern = this.pattern;
        const options = this.options;
        if (!options.nocomment && pattern.charAt(0) === "#") {
          this.comment = true;
          return;
        }
        if (!pattern) {
          this.empty = true;
          return;
        }
        this.parseNegate();
        this.globSet = [...new Set(this.braceExpand())];
        if (options.debug) {
          this.debug = (...args) => console.error(...args);
        }
        this.debug(this.pattern, this.globSet);
        const rawGlobParts = this.globSet.map((s6) => this.slashSplit(s6));
        this.globParts = this.preprocess(rawGlobParts);
        this.debug(this.pattern, this.globParts);
        let set = this.globParts.map((s6, _3, __) => {
          if (this.isWindows && this.windowsNoMagicRoot) {
            const isUNC = s6[0] === "" && s6[1] === "" && (s6[2] === "?" || !globMagic.test(s6[2])) && !globMagic.test(s6[3]);
            const isDrive = /^[a-z]:/i.test(s6[0]);
            if (isUNC) {
              return [...s6.slice(0, 4), ...s6.slice(4).map((ss) => this.parse(ss))];
            } else if (isDrive) {
              return [s6[0], ...s6.slice(1).map((ss) => this.parse(ss))];
            }
          }
          return s6.map((ss) => this.parse(ss));
        });
        this.debug(this.pattern, set);
        this.set = set.filter((s6) => s6.indexOf(false) === -1);
        if (this.isWindows) {
          for (let i6 = 0; i6 < this.set.length; i6++) {
            const p5 = this.set[i6];
            if (p5[0] === "" && p5[1] === "" && this.globParts[i6][2] === "?" && typeof p5[3] === "string" && /^[a-z]:$/i.test(p5[3])) {
              p5[2] = "?";
            }
          }
        }
        this.debug(this.pattern, this.set);
      }
      // various transforms to equivalent pattern sets that are
      // faster to process in a filesystem walk.  The goal is to
      // eliminate what we can, and push all ** patterns as far
      // to the right as possible, even if it increases the number
      // of patterns that we have to process.
      preprocess(globParts) {
        if (this.options.noglobstar) {
          for (let i6 = 0; i6 < globParts.length; i6++) {
            for (let j5 = 0; j5 < globParts[i6].length; j5++) {
              if (globParts[i6][j5] === "**") {
                globParts[i6][j5] = "*";
              }
            }
          }
        }
        const { optimizationLevel = 1 } = this.options;
        if (optimizationLevel >= 2) {
          globParts = this.firstPhasePreProcess(globParts);
          globParts = this.secondPhasePreProcess(globParts);
        } else if (optimizationLevel >= 1) {
          globParts = this.levelOneOptimize(globParts);
        } else {
          globParts = this.adjascentGlobstarOptimize(globParts);
        }
        return globParts;
      }
      // just get rid of adjascent ** portions
      adjascentGlobstarOptimize(globParts) {
        return globParts.map((parts) => {
          let gs = -1;
          while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
            let i6 = gs;
            while (parts[i6 + 1] === "**") {
              i6++;
            }
            if (i6 !== gs) {
              parts.splice(gs, i6 - gs);
            }
          }
          return parts;
        });
      }
      // get rid of adjascent ** and resolve .. portions
      levelOneOptimize(globParts) {
        return globParts.map((parts) => {
          parts = parts.reduce((set, part) => {
            const prev = set[set.length - 1];
            if (part === "**" && prev === "**") {
              return set;
            }
            if (part === "..") {
              if (prev && prev !== ".." && prev !== "." && prev !== "**") {
                set.pop();
                return set;
              }
            }
            set.push(part);
            return set;
          }, []);
          return parts.length === 0 ? [""] : parts;
        });
      }
      levelTwoFileOptimize(parts) {
        if (!Array.isArray(parts)) {
          parts = this.slashSplit(parts);
        }
        let didSomething = false;
        do {
          didSomething = false;
          if (!this.preserveMultipleSlashes) {
            for (let i6 = 1; i6 < parts.length - 1; i6++) {
              const p5 = parts[i6];
              if (i6 === 1 && p5 === "" && parts[0] === "")
                continue;
              if (p5 === "." || p5 === "") {
                didSomething = true;
                parts.splice(i6, 1);
                i6--;
              }
            }
            if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
              didSomething = true;
              parts.pop();
            }
          }
          let dd = 0;
          while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
            const p5 = parts[dd - 1];
            if (p5 && p5 !== "." && p5 !== ".." && p5 !== "**") {
              didSomething = true;
              parts.splice(dd - 1, 2);
              dd -= 2;
            }
          }
        } while (didSomething);
        return parts.length === 0 ? [""] : parts;
      }
      // First phase: single-pattern processing
      // <pre> is 1 or more portions
      // <rest> is 1 or more portions
      // <p> is any portion other than ., .., '', or **
      // <e> is . or ''
      //
      // **/.. is *brutal* for filesystem walking performance, because
      // it effectively resets the recursive walk each time it occurs,
      // and ** cannot be reduced out by a .. pattern part like a regexp
      // or most strings (other than .., ., and '') can be.
      //
      // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
      // <pre>/<e>/<rest> -> <pre>/<rest>
      // <pre>/<p>/../<rest> -> <pre>/<rest>
      // **/**/<rest> -> **/<rest>
      //
      // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
      // this WOULD be allowed if ** did follow symlinks, or * didn't
      firstPhasePreProcess(globParts) {
        let didSomething = false;
        do {
          didSomething = false;
          for (let parts of globParts) {
            let gs = -1;
            while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
              let gss = gs;
              while (parts[gss + 1] === "**") {
                gss++;
              }
              if (gss > gs) {
                parts.splice(gs + 1, gss - gs);
              }
              let next = parts[gs + 1];
              const p5 = parts[gs + 2];
              const p22 = parts[gs + 3];
              if (next !== "..")
                continue;
              if (!p5 || p5 === "." || p5 === ".." || !p22 || p22 === "." || p22 === "..") {
                continue;
              }
              didSomething = true;
              parts.splice(gs, 1);
              const other = parts.slice(0);
              other[gs] = "**";
              globParts.push(other);
              gs--;
            }
            if (!this.preserveMultipleSlashes) {
              for (let i6 = 1; i6 < parts.length - 1; i6++) {
                const p5 = parts[i6];
                if (i6 === 1 && p5 === "" && parts[0] === "")
                  continue;
                if (p5 === "." || p5 === "") {
                  didSomething = true;
                  parts.splice(i6, 1);
                  i6--;
                }
              }
              if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
                didSomething = true;
                parts.pop();
              }
            }
            let dd = 0;
            while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
              const p5 = parts[dd - 1];
              if (p5 && p5 !== "." && p5 !== ".." && p5 !== "**") {
                didSomething = true;
                const needDot = dd === 1 && parts[dd + 1] === "**";
                const splin = needDot ? ["."] : [];
                parts.splice(dd - 1, 2, ...splin);
                if (parts.length === 0)
                  parts.push("");
                dd -= 2;
              }
            }
          }
        } while (didSomething);
        return globParts;
      }
      // second phase: multi-pattern dedupes
      // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
      // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
      // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
      //
      // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
      // ^-- not valid because ** doens't follow symlinks
      secondPhasePreProcess(globParts) {
        for (let i6 = 0; i6 < globParts.length - 1; i6++) {
          for (let j5 = i6 + 1; j5 < globParts.length; j5++) {
            const matched = this.partsMatch(globParts[i6], globParts[j5], !this.preserveMultipleSlashes);
            if (!matched)
              continue;
            globParts[i6] = matched;
            globParts[j5] = [];
          }
        }
        return globParts.filter((gs) => gs.length);
      }
      partsMatch(a5, b5, emptyGSMatch = false) {
        let ai = 0;
        let bi = 0;
        let result = [];
        let which = "";
        while (ai < a5.length && bi < b5.length) {
          if (a5[ai] === b5[bi]) {
            result.push(which === "b" ? b5[bi] : a5[ai]);
            ai++;
            bi++;
          } else if (emptyGSMatch && a5[ai] === "**" && b5[bi] === a5[ai + 1]) {
            result.push(a5[ai]);
            ai++;
          } else if (emptyGSMatch && b5[bi] === "**" && a5[ai] === b5[bi + 1]) {
            result.push(b5[bi]);
            bi++;
          } else if (a5[ai] === "*" && b5[bi] && (this.options.dot || !b5[bi].startsWith(".")) && b5[bi] !== "**") {
            if (which === "b")
              return false;
            which = "a";
            result.push(a5[ai]);
            ai++;
            bi++;
          } else if (b5[bi] === "*" && a5[ai] && (this.options.dot || !a5[ai].startsWith(".")) && a5[ai] !== "**") {
            if (which === "a")
              return false;
            which = "b";
            result.push(b5[bi]);
            ai++;
            bi++;
          } else {
            return false;
          }
        }
        return a5.length === b5.length && result;
      }
      parseNegate() {
        if (this.nonegate)
          return;
        const pattern = this.pattern;
        let negate2 = false;
        let negateOffset = 0;
        for (let i6 = 0; i6 < pattern.length && pattern.charAt(i6) === "!"; i6++) {
          negate2 = !negate2;
          negateOffset++;
        }
        if (negateOffset)
          this.pattern = pattern.slice(negateOffset);
        this.negate = negate2;
      }
      // set partial to true to test if, for example,
      // "/a/b" matches the start of "/*/b/*/d"
      // Partial means, if you run out of file before you run
      // out of pattern, then that's fine, as long as all
      // the parts match.
      matchOne(file, pattern, partial = false) {
        const options = this.options;
        if (this.isWindows) {
          const fileUNC = file[0] === "" && file[1] === "" && file[2] === "?" && typeof file[3] === "string" && /^[a-z]:$/i.test(file[3]);
          const patternUNC = pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);
          if (fileUNC && patternUNC) {
            const fd = file[3];
            const pd = pattern[3];
            if (fd.toLowerCase() === pd.toLowerCase()) {
              file[3] = pd;
            }
          } else if (patternUNC && typeof file[0] === "string") {
            const pd = pattern[3];
            const fd = file[0];
            if (pd.toLowerCase() === fd.toLowerCase()) {
              pattern[3] = fd;
              pattern = pattern.slice(3);
            }
          } else if (fileUNC && typeof pattern[0] === "string") {
            const fd = file[3];
            if (fd.toLowerCase() === pattern[0].toLowerCase()) {
              pattern[0] = fd;
              file = file.slice(3);
            }
          }
        }
        const { optimizationLevel = 1 } = this.options;
        if (optimizationLevel >= 2) {
          file = this.levelTwoFileOptimize(file);
        }
        this.debug("matchOne", this, { file, pattern });
        this.debug("matchOne", file.length, pattern.length);
        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
          this.debug("matchOne loop");
          var p5 = pattern[pi];
          var f7 = file[fi];
          this.debug(pattern, p5, f7);
          if (p5 === false) {
            return false;
          }
          if (p5 === GLOBSTAR) {
            this.debug("GLOBSTAR", [pattern, p5, f7]);
            var fr = fi;
            var pr = pi + 1;
            if (pr === pl) {
              this.debug("** at the end");
              for (; fi < fl; fi++) {
                if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".")
                  return false;
              }
              return true;
            }
            while (fr < fl) {
              var swallowee = file[fr];
              this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
              if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
                this.debug("globstar found match!", fr, fl, swallowee);
                return true;
              } else {
                if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
                  this.debug("dot detected!", file, fr, pattern, pr);
                  break;
                }
                this.debug("globstar swallow a segment, and continue");
                fr++;
              }
            }
            if (partial) {
              this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
              if (fr === fl) {
                return true;
              }
            }
            return false;
          }
          let hit;
          if (typeof p5 === "string") {
            hit = f7 === p5;
            this.debug("string match", p5, f7, hit);
          } else {
            hit = p5.test(f7);
            this.debug("pattern match", p5, f7, hit);
          }
          if (!hit)
            return false;
        }
        if (fi === fl && pi === pl) {
          return true;
        } else if (fi === fl) {
          return partial;
        } else if (pi === pl) {
          return fi === fl - 1 && file[fi] === "";
        } else {
          throw new Error("wtf?");
        }
      }
      braceExpand() {
        return braceExpand(this.pattern, this.options);
      }
      parse(pattern) {
        assertValidPattern(pattern);
        const options = this.options;
        if (pattern === "**")
          return GLOBSTAR;
        if (pattern === "")
          return "";
        let m6;
        let fastTest = null;
        if (m6 = pattern.match(starRE)) {
          fastTest = options.dot ? starTestDot : starTest;
        } else if (m6 = pattern.match(starDotExtRE)) {
          fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m6[1]);
        } else if (m6 = pattern.match(qmarksRE)) {
          fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m6);
        } else if (m6 = pattern.match(starDotStarRE)) {
          fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
        } else if (m6 = pattern.match(dotStarRE)) {
          fastTest = dotStarTest;
        }
        let re = "";
        let hasMagic = false;
        let escaping = false;
        const patternListStack = [];
        const negativeLists = [];
        let stateChar = false;
        let uflag = false;
        let pl;
        let dotTravAllowed = pattern.charAt(0) === ".";
        let dotFileAllowed = options.dot || dotTravAllowed;
        const patternStart = () => dotTravAllowed ? "" : dotFileAllowed ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
        const subPatternStart = (p5) => p5.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
        const clearStateChar = () => {
          if (stateChar) {
            switch (stateChar) {
              case "*":
                re += star;
                hasMagic = true;
                break;
              case "?":
                re += qmark;
                hasMagic = true;
                break;
              default:
                re += "\\" + stateChar;
                break;
            }
            this.debug("clearStateChar %j %j", stateChar, re);
            stateChar = false;
          }
        };
        for (let i6 = 0, c5; i6 < pattern.length && (c5 = pattern.charAt(i6)); i6++) {
          this.debug("%s	%s %s %j", pattern, i6, re, c5);
          if (escaping) {
            if (c5 === "/") {
              return false;
            }
            if (reSpecials[c5]) {
              re += "\\";
            }
            re += c5;
            escaping = false;
            continue;
          }
          switch (c5) {
            // Should already be path-split by now.
            /* c8 ignore start */
            case "/": {
              return false;
            }
            /* c8 ignore stop */
            case "\\":
              clearStateChar();
              escaping = true;
              continue;
            // the various stateChar values
            // for the "extglob" stuff.
            case "?":
            case "*":
            case "+":
            case "@":
            case "!":
              this.debug("%s	%s %s %j <-- stateChar", pattern, i6, re, c5);
              this.debug("call clearStateChar %j", stateChar);
              clearStateChar();
              stateChar = c5;
              if (options.noext)
                clearStateChar();
              continue;
            case "(": {
              if (!stateChar) {
                re += "\\(";
                continue;
              }
              const plEntry = {
                type: stateChar,
                start: i6 - 1,
                reStart: re.length,
                open: plTypes[stateChar].open,
                close: plTypes[stateChar].close
              };
              this.debug(this.pattern, "	", plEntry);
              patternListStack.push(plEntry);
              re += plEntry.open;
              if (plEntry.start === 0 && plEntry.type !== "!") {
                dotTravAllowed = true;
                re += subPatternStart(pattern.slice(i6 + 1));
              }
              this.debug("plType %j %j", stateChar, re);
              stateChar = false;
              continue;
            }
            case ")": {
              const plEntry = patternListStack[patternListStack.length - 1];
              if (!plEntry) {
                re += "\\)";
                continue;
              }
              patternListStack.pop();
              clearStateChar();
              hasMagic = true;
              pl = plEntry;
              re += pl.close;
              if (pl.type === "!") {
                negativeLists.push(Object.assign(pl, { reEnd: re.length }));
              }
              continue;
            }
            case "|": {
              const plEntry = patternListStack[patternListStack.length - 1];
              if (!plEntry) {
                re += "\\|";
                continue;
              }
              clearStateChar();
              re += "|";
              if (plEntry.start === 0 && plEntry.type !== "!") {
                dotTravAllowed = true;
                re += subPatternStart(pattern.slice(i6 + 1));
              }
              continue;
            }
            // these are mostly the same in regexp and glob
            case "[":
              clearStateChar();
              const [src, needUflag, consumed, magic] = parseClass(pattern, i6);
              if (consumed) {
                re += src;
                uflag = uflag || needUflag;
                i6 += consumed - 1;
                hasMagic = hasMagic || magic;
              } else {
                re += "\\[";
              }
              continue;
            case "]":
              re += "\\" + c5;
              continue;
            default:
              clearStateChar();
              re += regExpEscape(c5);
              break;
          }
        }
        for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
          let tail;
          tail = re.slice(pl.reStart + pl.open.length);
          this.debug(this.pattern, "setting tail", re, pl);
          tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_3, $1, $2) => {
            if (!$2) {
              $2 = "\\";
            }
            return $1 + $1 + $2 + "|";
          });
          this.debug("tail=%j\n   %s", tail, tail, pl, re);
          const t6 = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
          hasMagic = true;
          re = re.slice(0, pl.reStart) + t6 + "\\(" + tail;
        }
        clearStateChar();
        if (escaping) {
          re += "\\\\";
        }
        const addPatternStart = addPatternStartSet[re.charAt(0)];
        for (let n5 = negativeLists.length - 1; n5 > -1; n5--) {
          const nl = negativeLists[n5];
          const nlBefore = re.slice(0, nl.reStart);
          const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
          let nlAfter = re.slice(nl.reEnd);
          const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
          const closeParensBefore = nlBefore.split(")").length;
          const openParensBefore = nlBefore.split("(").length - closeParensBefore;
          let cleanAfter = nlAfter;
          for (let i6 = 0; i6 < openParensBefore; i6++) {
            cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
          }
          nlAfter = cleanAfter;
          const dollar = nlAfter === "" ? "(?:$|\\/)" : "";
          re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
        }
        if (re !== "" && hasMagic) {
          re = "(?=.)" + re;
        }
        if (addPatternStart) {
          re = patternStart() + re;
        }
        if (options.nocase && !hasMagic && !options.nocaseMagicOnly) {
          hasMagic = pattern.toUpperCase() !== pattern.toLowerCase();
        }
        if (!hasMagic) {
          return globUnescape(re);
        }
        const flags = (options.nocase ? "i" : "") + (uflag ? "u" : "");
        try {
          const ext2 = fastTest ? {
            _glob: pattern,
            _src: re,
            test: fastTest
          } : {
            _glob: pattern,
            _src: re
          };
          return Object.assign(new RegExp("^" + re + "$", flags), ext2);
        } catch (er) {
          this.debug("invalid regexp", er);
          return new RegExp("$.");
        }
      }
      makeRe() {
        if (this.regexp || this.regexp === false)
          return this.regexp;
        const set = this.set;
        if (!set.length) {
          this.regexp = false;
          return this.regexp;
        }
        const options = this.options;
        const twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
        const flags = options.nocase ? "i" : "";
        let re = set.map((pattern) => {
          const pp = pattern.map((p5) => typeof p5 === "string" ? regExpEscape(p5) : p5 === GLOBSTAR ? GLOBSTAR : p5._src);
          pp.forEach((p5, i6) => {
            const next = pp[i6 + 1];
            const prev = pp[i6 - 1];
            if (p5 !== GLOBSTAR || prev === GLOBSTAR) {
              return;
            }
            if (prev === void 0) {
              if (next !== void 0 && next !== GLOBSTAR) {
                pp[i6 + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
              } else {
                pp[i6] = twoStar;
              }
            } else if (next === void 0) {
              pp[i6 - 1] = prev + "(?:\\/|" + twoStar + ")?";
            } else if (next !== GLOBSTAR) {
              pp[i6 - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
              pp[i6 + 1] = GLOBSTAR;
            }
          });
          return pp.filter((p5) => p5 !== GLOBSTAR).join("/");
        }).join("|");
        re = "^(?:" + re + ")$";
        if (this.negate)
          re = "^(?!" + re + ").*$";
        try {
          this.regexp = new RegExp(re, flags);
        } catch (ex) {
          this.regexp = false;
        }
        return this.regexp;
      }
      slashSplit(p5) {
        if (this.preserveMultipleSlashes) {
          return p5.split("/");
        } else if (this.isWindows && /^\/\/[^\/]+/.test(p5)) {
          return ["", ...p5.split(/\/+/)];
        } else {
          return p5.split(/\/+/);
        }
      }
      match(f7, partial = this.partial) {
        this.debug("match", f7, this.pattern);
        if (this.comment) {
          return false;
        }
        if (this.empty) {
          return f7 === "";
        }
        if (f7 === "/" && partial) {
          return true;
        }
        const options = this.options;
        if (this.isWindows) {
          f7 = f7.split("\\").join("/");
        }
        const ff = this.slashSplit(f7);
        this.debug(this.pattern, "split", ff);
        const set = this.set;
        this.debug(this.pattern, "set", set);
        let filename = ff[ff.length - 1];
        if (!filename) {
          for (let i6 = ff.length - 2; !filename && i6 >= 0; i6--) {
            filename = ff[i6];
          }
        }
        for (let i6 = 0; i6 < set.length; i6++) {
          const pattern = set[i6];
          let file = ff;
          if (options.matchBase && pattern.length === 1) {
            file = [filename];
          }
          const hit = this.matchOne(file, pattern, partial);
          if (hit) {
            if (options.flipNegate) {
              return true;
            }
            return !this.negate;
          }
        }
        if (options.flipNegate) {
          return false;
        }
        return this.negate;
      }
      static defaults(def) {
        return minimatch.defaults(def).Minimatch;
      }
    };
    minimatch.Minimatch = Minimatch;
    minimatch.escape = escape;
    minimatch.unescape = unescape2;
  }
});

// src/extensions/vector.ts
var vectorOps;
var init_vector = __esm({
  "src/extensions/vector.ts"() {
    "use strict";
    vectorOps = [
      "vector_l2_ops",
      "vector_ip_ops",
      "vector_cosine_ops",
      "vector_l1_ops",
      "bit_hamming_ops",
      "bit_jaccard_ops",
      "halfvec_l2_ops",
      "sparsevec_l2_ops"
    ];
  }
});

// src/serializer/utils.ts
function getColumnCasing(column6, casing2) {
  if (!column6.name) return "";
  return !column6.keyAsName || casing2 === void 0 ? column6.name : casing2 === "camelCase" ? (0, import_casing.toCamelCase)(column6.name) : (0, import_casing.toSnakeCase)(column6.name);
}
var import_casing, sqlToStr;
var init_utils2 = __esm({
  "src/serializer/utils.ts"() {
    "use strict";
    import_casing = require("drizzle-orm/casing");
    sqlToStr = (sql, casing2) => {
      return sql.toQuery({
        escapeName: () => {
          throw new Error("we don't support params for `sql` default values");
        },
        escapeParam: () => {
          throw new Error("we don't support params for `sql` default values");
        },
        escapeString: () => {
          throw new Error("we don't support params for `sql` default values");
        },
        casing: new import_casing.CasingCache(casing2)
      }).sql;
    };
  }
});

// src/serializer/pgSerializer.ts
function stringFromIdentityProperty(field) {
  return typeof field === "string" ? field : typeof field === "undefined" ? void 0 : String(field);
}
function maxRangeForIdentityBasedOn(columnType) {
  return columnType === "integer" ? "2147483647" : columnType === "bigint" ? "9223372036854775807" : "32767";
}
function minRangeForIdentityBasedOn(columnType) {
  return columnType === "integer" ? "-2147483648" : columnType === "bigint" ? "-9223372036854775808" : "-32768";
}
function stringFromDatabaseIdentityProperty(field) {
  return typeof field === "string" ? field : typeof field === "undefined" ? void 0 : typeof field === "bigint" ? field.toString() : String(field);
}
function buildArrayString(array2, sqlType) {
  sqlType = sqlType.split("[")[0];
  const values = array2.map((value) => {
    if (typeof value === "number" || typeof value === "bigint") {
      return value.toString();
    } else if (typeof value === "boolean") {
      return value ? "true" : "false";
    } else if (Array.isArray(value)) {
      return buildArrayString(value, sqlType);
    } else if (value instanceof Date) {
      if (sqlType === "date") {
        return `"${value.toISOString().split("T")[0]}"`;
      } else if (sqlType === "timestamp") {
        return `"${value.toISOString().replace("T", " ").slice(0, 23)}"`;
      } else {
        return `"${value.toISOString()}"`;
      }
    } else if (typeof value === "object") {
      return `"${JSON.stringify(value).replaceAll('"', '\\"')}"`;
    }
    return `"${value}"`;
  }).join(",");
  return `{${values}}`;
}
function prepareRoles(entities) {
  let useRoles = false;
  const includeRoles = [];
  const excludeRoles = [];
  if (entities && entities.roles) {
    if (typeof entities.roles === "object") {
      if (entities.roles.provider) {
        if (entities.roles.provider === "supabase") {
          excludeRoles.push(...[
            "anon",
            "authenticator",
            "authenticated",
            "service_role",
            "supabase_auth_admin",
            "supabase_storage_admin",
            "dashboard_user",
            "supabase_admin"
          ]);
        } else if (entities.roles.provider === "neon") {
          excludeRoles.push(...["authenticated", "anonymous"]);
        }
      }
      if (entities.roles.include) {
        includeRoles.push(...entities.roles.include);
      }
      if (entities.roles.exclude) {
        excludeRoles.push(...entities.roles.exclude);
      }
    } else {
      useRoles = entities.roles;
    }
  }
  return { useRoles, includeRoles, excludeRoles };
}
var import_drizzle_orm, import_pg_core, indexName, generatePgSnapshot, trimChar, fromDatabase, defaultForColumn, getColumnsInfoQuery;
var init_pgSerializer = __esm({
  "src/serializer/pgSerializer.ts"() {
    "use strict";
    init_source();
    import_drizzle_orm = require("drizzle-orm");
    import_pg_core = require("drizzle-orm/pg-core");
    init_vector();
    init_outputs();
    init_utils();
    init_utils2();
    indexName = (tableName, columns) => {
      return `${tableName}_${columns.join("_")}_index`;
    };
    generatePgSnapshot = (tables, enums, schemas, sequences, roles, policies, views, matViews, casing2, schemaFilter) => {
      const dialect6 = new import_pg_core.PgDialect({ casing: casing2 });
      const result = {};
      const resultViews = {};
      const sequencesToReturn = {};
      const rolesToReturn = {};
      const policiesToReturn = {};
      const indexesInSchema = {};
      for (const table6 of tables) {
        const checksInTable = {};
        const {
          name: tableName,
          columns,
          indexes,
          foreignKeys,
          checks,
          schema: schema6,
          primaryKeys,
          uniqueConstraints,
          policies: policies2,
          enableRLS
        } = (0, import_pg_core.getTableConfig)(table6);
        if (schemaFilter && !schemaFilter.includes(schema6 ?? "public")) {
          continue;
        }
        const columnsObject = {};
        const indexesObject = {};
        const checksObject = {};
        const foreignKeysObject = {};
        const primaryKeysObject = {};
        const uniqueConstraintObject = {};
        const policiesObject = {};
        columns.forEach((column6) => {
          const name = getColumnCasing(column6, casing2);
          const notNull = column6.notNull;
          const primaryKey = column6.primary;
          const sqlTypeLowered = column6.getSQLType().toLowerCase();
          const getEnumSchema = (column7) => {
            while ((0, import_drizzle_orm.is)(column7, import_pg_core.PgArray)) {
              column7 = column7.baseColumn;
            }
            return (0, import_drizzle_orm.is)(column7, import_pg_core.PgEnumColumn) ? column7.enum.schema || "public" : void 0;
          };
          const typeSchema = getEnumSchema(column6);
          const generated = column6.generated;
          const identity = column6.generatedIdentity;
          const increment = stringFromIdentityProperty(identity?.sequenceOptions?.increment) ?? "1";
          const minValue = stringFromIdentityProperty(identity?.sequenceOptions?.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column6.columnType) : "1");
          const maxValue = stringFromIdentityProperty(identity?.sequenceOptions?.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column6.getSQLType()));
          const startWith = stringFromIdentityProperty(identity?.sequenceOptions?.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
          const cache5 = stringFromIdentityProperty(identity?.sequenceOptions?.cache) ?? "1";
          const columnToSet = {
            name,
            type: column6.getSQLType(),
            typeSchema,
            primaryKey,
            notNull,
            generated: generated ? {
              as: (0, import_drizzle_orm.is)(generated.as, import_drizzle_orm.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
              type: "stored"
            } : void 0,
            identity: identity ? {
              type: identity.type,
              name: identity.sequenceName ?? `${tableName}_${name}_seq`,
              schema: schema6 ?? "public",
              increment,
              startWith,
              minValue,
              maxValue,
              cache: cache5,
              cycle: identity?.sequenceOptions?.cycle ?? false
            } : void 0
          };
          if (column6.isUnique) {
            const existingUnique = uniqueConstraintObject[column6.uniqueName];
            if (typeof existingUnique !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
          The unique constraint ${source_default.underline.blue(
                  column6.uniqueName
                )} on the ${source_default.underline.blue(
                  name
                )} column is conflicting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`)}`
              );
              process.exit(1);
            }
            uniqueConstraintObject[column6.uniqueName] = {
              name: column6.uniqueName,
              nullsNotDistinct: column6.uniqueType === "not distinct",
              columns: [columnToSet.name]
            };
          }
          if (column6.default !== void 0) {
            if ((0, import_drizzle_orm.is)(column6.default, import_drizzle_orm.SQL)) {
              columnToSet.default = sqlToStr(column6.default, casing2);
            } else {
              if (typeof column6.default === "string") {
                columnToSet.default = `'${escapeSingleQuotes(column6.default)}'`;
              } else {
                if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
                  columnToSet.default = `'${JSON.stringify(column6.default)}'::${sqlTypeLowered}`;
                } else if (column6.default instanceof Date) {
                  if (sqlTypeLowered === "date") {
                    columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`;
                  } else if (sqlTypeLowered === "timestamp") {
                    columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                  } else {
                    columnToSet.default = `'${column6.default.toISOString()}'`;
                  }
                } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column6.default)) {
                  columnToSet.default = `'${buildArrayString(column6.default, sqlTypeLowered)}'`;
                } else {
                  columnToSet.default = column6.default;
                }
              }
            }
          }
          columnsObject[name] = columnToSet;
        });
        primaryKeys.map((pk) => {
          const originalColumnNames = pk.columns.map((c5) => c5.name);
          const columnNames = pk.columns.map((c5) => getColumnCasing(c5, casing2));
          let name = pk.getName();
          if (casing2 !== void 0) {
            for (let i6 = 0; i6 < originalColumnNames.length; i6++) {
              name = name.replace(originalColumnNames[i6], columnNames[i6]);
            }
          }
          primaryKeysObject[name] = {
            name,
            columns: columnNames
          };
        });
        uniqueConstraints?.map((unq) => {
          const columnNames = unq.columns.map((c5) => getColumnCasing(c5, casing2));
          const name = unq.name ?? (0, import_pg_core.uniqueKeyName)(table6, columnNames);
          const existingUnique = uniqueConstraintObject[name];
          if (typeof existingUnique !== "undefined") {
            console.log(
              `
${withStyle.errorWarning(
                `We've found duplicated unique constraint names in ${source_default.underline.blue(tableName)} table. 
        The unique constraint ${source_default.underline.blue(name)} on the ${source_default.underline.blue(
                  columnNames.join(",")
                )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns
`
              )}`
            );
            process.exit(1);
          }
          uniqueConstraintObject[name] = {
            name: unq.name,
            nullsNotDistinct: unq.nullsNotDistinct,
            columns: columnNames
          };
        });
        const fks = foreignKeys.map((fk5) => {
          const tableFrom = tableName;
          const onDelete = fk5.onDelete;
          const onUpdate = fk5.onUpdate;
          const reference = fk5.reference();
          const tableTo = (0, import_drizzle_orm.getTableName)(reference.foreignTable);
          const schemaTo = (0, import_pg_core.getTableConfig)(reference.foreignTable).schema;
          const originalColumnsFrom = reference.columns.map((it) => it.name);
          const columnsFrom = reference.columns.map((it) => getColumnCasing(it, casing2));
          const originalColumnsTo = reference.foreignColumns.map((it) => it.name);
          const columnsTo = reference.foreignColumns.map((it) => getColumnCasing(it, casing2));
          let name = fk5.getName();
          if (casing2 !== void 0) {
            for (let i6 = 0; i6 < originalColumnsFrom.length; i6++) {
              name = name.replace(originalColumnsFrom[i6], columnsFrom[i6]);
            }
            for (let i6 = 0; i6 < originalColumnsTo.length; i6++) {
              name = name.replace(originalColumnsTo[i6], columnsTo[i6]);
            }
          }
          return {
            name,
            tableFrom,
            tableTo,
            schemaTo,
            columnsFrom,
            columnsTo,
            onDelete,
            onUpdate
          };
        });
        fks.forEach((it) => {
          foreignKeysObject[it.name] = it;
        });
        indexes.forEach((value) => {
          const columns2 = value.config.columns;
          let indexColumnNames = [];
          columns2.forEach((it) => {
            if ((0, import_drizzle_orm.is)(it, import_drizzle_orm.SQL)) {
              if (typeof value.config.name === "undefined") {
                console.log(
                  `
${withStyle.errorWarning(
                    `Please specify an index name in ${(0, import_drizzle_orm.getTableName)(value.config.table)} table that has "${dialect6.sqlToQuery(it).sql}" expression. We can generate index names for indexes on columns only; for expressions in indexes, you need to specify the name yourself.`
                  )}`
                );
                process.exit(1);
              }
            }
            it = it;
            const name2 = getColumnCasing(it, casing2);
            if (!(0, import_drizzle_orm.is)(it, import_drizzle_orm.SQL) && it.type === "PgVector" && typeof it.indexConfig.opClass === "undefined") {
              console.log(
                `
${withStyle.errorWarning(
                  `You are specifying an index on the ${source_default.blueBright(
                    name2
                  )} column inside the ${source_default.blueBright(
                    tableName
                  )} table with the ${source_default.blueBright(
                    "vector"
                  )} type without specifying an operator class. Vector extension doesn't have a default operator class, so you need to specify one of the available options. Here is a list of available op classes for the vector extension: [${vectorOps.map((it2) => `${source_default.underline(`${it2}`)}`).join(", ")}].

You can specify it using current syntax: ${source_default.underline(
                    `index("${value.config.name}").using("${value.config.method}", table.${name2}.op("${vectorOps[0]}"))`
                  )}

You can check the "pg_vector" docs for more info: https://github.com/pgvector/pgvector?tab=readme-ov-file#indexing
`
                )}`
              );
              process.exit(1);
            }
            indexColumnNames.push(name2);
          });
          const name = value.config.name ? value.config.name : indexName(tableName, indexColumnNames);
          let indexColumns = columns2.map(
            (it) => {
              if ((0, import_drizzle_orm.is)(it, import_drizzle_orm.SQL)) {
                return {
                  expression: dialect6.sqlToQuery(it, "indexes").sql,
                  asc: true,
                  isExpression: true,
                  nulls: "last"
                };
              } else {
                it = it;
                return {
                  expression: getColumnCasing(it, casing2),
                  isExpression: false,
                  asc: it.indexConfig?.order === "asc",
                  nulls: it.indexConfig?.nulls ? it.indexConfig?.nulls : it.indexConfig?.order === "desc" ? "first" : "last",
                  opclass: it.indexConfig?.opClass
                };
              }
            }
          );
          if (typeof indexesInSchema[schema6 ?? "public"] !== "undefined") {
            if (indexesInSchema[schema6 ?? "public"].includes(name)) {
              console.log(
                `
${withStyle.errorWarning(
                  `We've found duplicated index name across ${source_default.underline.blue(schema6 ?? "public")} schema. Please rename your index in either the ${source_default.underline.blue(
                    tableName
                  )} table or the table with the duplicated index name`
                )}`
              );
              process.exit(1);
            }
            indexesInSchema[schema6 ?? "public"].push(name);
          } else {
            indexesInSchema[schema6 ?? "public"] = [name];
          }
          indexesObject[name] = {
            name,
            columns: indexColumns,
            isUnique: value.config.unique ?? false,
            where: value.config.where ? dialect6.sqlToQuery(value.config.where).sql : void 0,
            concurrently: value.config.concurrently ?? false,
            method: value.config.method ?? "btree",
            with: value.config.with ?? {}
          };
        });
        policies2.forEach((policy5) => {
          const mappedTo = [];
          if (!policy5.to) {
            mappedTo.push("public");
          } else {
            if (policy5.to && typeof policy5.to === "string") {
              mappedTo.push(policy5.to);
            } else if (policy5.to && (0, import_drizzle_orm.is)(policy5.to, import_pg_core.PgRole)) {
              mappedTo.push(policy5.to.name);
            } else if (policy5.to && Array.isArray(policy5.to)) {
              policy5.to.forEach((it) => {
                if (typeof it === "string") {
                  mappedTo.push(it);
                } else if ((0, import_drizzle_orm.is)(it, import_pg_core.PgRole)) {
                  mappedTo.push(it.name);
                }
              });
            }
          }
          if (policiesObject[policy5.name] !== void 0) {
            console.log(
              `
${withStyle.errorWarning(
                `We've found duplicated policy name across ${source_default.underline.blue(tableKey2)} table. Please rename one of the policies with ${source_default.underline.blue(
                  policy5.name
                )} name`
              )}`
            );
            process.exit(1);
          }
          policiesObject[policy5.name] = {
            name: policy5.name,
            as: policy5.as?.toUpperCase() ?? "PERMISSIVE",
            for: policy5.for?.toUpperCase() ?? "ALL",
            to: mappedTo.sort(),
            using: (0, import_drizzle_orm.is)(policy5.using, import_drizzle_orm.SQL) ? dialect6.sqlToQuery(policy5.using).sql : void 0,
            withCheck: (0, import_drizzle_orm.is)(policy5.withCheck, import_drizzle_orm.SQL) ? dialect6.sqlToQuery(policy5.withCheck).sql : void 0
          };
        });
        checks.forEach((check) => {
          const checkName = check.name;
          if (typeof checksInTable[`"${schema6 ?? "public"}"."${tableName}"`] !== "undefined") {
            if (checksInTable[`"${schema6 ?? "public"}"."${tableName}"`].includes(check.name)) {
              console.log(
                `
${withStyle.errorWarning(
                  `We've found duplicated check constraint name across ${source_default.underline.blue(
                    schema6 ?? "public"
                  )} schema in ${source_default.underline.blue(
                    tableName
                  )}. Please rename your check constraint in either the ${source_default.underline.blue(
                    tableName
                  )} table or the table with the duplicated check contraint name`
                )}`
              );
              process.exit(1);
            }
            checksInTable[`"${schema6 ?? "public"}"."${tableName}"`].push(checkName);
          } else {
            checksInTable[`"${schema6 ?? "public"}"."${tableName}"`] = [check.name];
          }
          checksObject[checkName] = {
            name: checkName,
            value: dialect6.sqlToQuery(check.value).sql
          };
        });
        const tableKey2 = `${schema6 ?? "public"}.${tableName}`;
        result[tableKey2] = {
          name: tableName,
          schema: schema6 ?? "",
          columns: columnsObject,
          indexes: indexesObject,
          foreignKeys: foreignKeysObject,
          compositePrimaryKeys: primaryKeysObject,
          uniqueConstraints: uniqueConstraintObject,
          policies: policiesObject,
          checkConstraints: checksObject,
          isRLSEnabled: enableRLS
        };
      }
      for (const policy5 of policies) {
        if (!policy5._linkedTable) {
          console.log(
            `
${withStyle.errorWarning(
              `"Policy ${policy5.name} was skipped because it was not linked to any table. You should either include the policy in a table or use .link() on the policy to link it to any table you have. For more information, please check:`
            )}`
          );
          continue;
        }
        const tableConfig = (0, import_pg_core.getTableConfig)(policy5._linkedTable);
        const tableKey2 = `${tableConfig.schema ?? "public"}.${tableConfig.name}`;
        const mappedTo = [];
        if (!policy5.to) {
          mappedTo.push("public");
        } else {
          if (policy5.to && typeof policy5.to === "string") {
            mappedTo.push(policy5.to);
          } else if (policy5.to && (0, import_drizzle_orm.is)(policy5.to, import_pg_core.PgRole)) {
            mappedTo.push(policy5.to.name);
          } else if (policy5.to && Array.isArray(policy5.to)) {
            policy5.to.forEach((it) => {
              if (typeof it === "string") {
                mappedTo.push(it);
              } else if ((0, import_drizzle_orm.is)(it, import_pg_core.PgRole)) {
                mappedTo.push(it.name);
              }
            });
          }
        }
        if (result[tableKey2]?.policies[policy5.name] !== void 0 || policiesToReturn[policy5.name] !== void 0) {
          console.log(
            `
${withStyle.errorWarning(
              `We've found duplicated policy name across ${source_default.underline.blue(tableKey2)} table. Please rename one of the policies with ${source_default.underline.blue(
                policy5.name
              )} name`
            )}`
          );
          process.exit(1);
        }
        const mappedPolicy = {
          name: policy5.name,
          as: policy5.as?.toUpperCase() ?? "PERMISSIVE",
          for: policy5.for?.toUpperCase() ?? "ALL",
          to: mappedTo.sort(),
          using: (0, import_drizzle_orm.is)(policy5.using, import_drizzle_orm.SQL) ? dialect6.sqlToQuery(policy5.using).sql : void 0,
          withCheck: (0, import_drizzle_orm.is)(policy5.withCheck, import_drizzle_orm.SQL) ? dialect6.sqlToQuery(policy5.withCheck).sql : void 0
        };
        if (result[tableKey2]) {
          result[tableKey2].policies[policy5.name] = mappedPolicy;
        } else {
          policiesToReturn[policy5.name] = {
            ...mappedPolicy,
            schema: tableConfig.schema ?? "public",
            on: `"${tableConfig.schema ?? "public"}"."${tableConfig.name}"`
          };
        }
      }
      for (const sequence of sequences) {
        const name = sequence.seqName;
        if (typeof sequencesToReturn[`${sequence.schema ?? "public"}.${name}`] === "undefined") {
          const increment = stringFromIdentityProperty(sequence?.seqOptions?.increment) ?? "1";
          const minValue = stringFromIdentityProperty(sequence?.seqOptions?.minValue) ?? (parseFloat(increment) < 0 ? "-9223372036854775808" : "1");
          const maxValue = stringFromIdentityProperty(sequence?.seqOptions?.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : "9223372036854775807");
          const startWith = stringFromIdentityProperty(sequence?.seqOptions?.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
          const cache5 = stringFromIdentityProperty(sequence?.seqOptions?.cache) ?? "1";
          sequencesToReturn[`${sequence.schema ?? "public"}.${name}`] = {
            name,
            schema: sequence.schema ?? "public",
            increment,
            startWith,
            minValue,
            maxValue,
            cache: cache5,
            cycle: sequence.seqOptions?.cycle ?? false
          };
        } else {
        }
      }
      for (const role of roles) {
        if (!role._existing) {
          rolesToReturn[role.name] = {
            name: role.name,
            createDb: role.createDb === void 0 ? false : role.createDb,
            createRole: role.createRole === void 0 ? false : role.createRole,
            inherit: role.inherit === void 0 ? true : role.inherit
          };
        }
      }
      const combinedViews = [...views, ...matViews];
      for (const view5 of combinedViews) {
        let viewName;
        let schema6;
        let query;
        let selectedFields;
        let isExisting;
        let withOption;
        let tablespace;
        let using;
        let withNoData;
        let materialized = false;
        if ((0, import_drizzle_orm.is)(view5, import_pg_core.PgView)) {
          ({ name: viewName, schema: schema6, query, selectedFields, isExisting, with: withOption } = (0, import_pg_core.getViewConfig)(view5));
        } else {
          ({ name: viewName, schema: schema6, query, selectedFields, isExisting, with: withOption, tablespace, using, withNoData } = (0, import_pg_core.getMaterializedViewConfig)(view5));
          materialized = true;
        }
        const viewSchema = schema6 ?? "public";
        const viewKey = `${viewSchema}.${viewName}`;
        const columnsObject = {};
        const uniqueConstraintObject = {};
        const existingView = resultViews[viewKey];
        if (typeof existingView !== "undefined") {
          console.log(
            `
${withStyle.errorWarning(
              `We've found duplicated view name across ${source_default.underline.blue(schema6 ?? "public")} schema. Please rename your view`
            )}`
          );
          process.exit(1);
        }
        for (const key in selectedFields) {
          if ((0, import_drizzle_orm.is)(selectedFields[key], import_pg_core.PgColumn)) {
            const column6 = selectedFields[key];
            const notNull = column6.notNull;
            const primaryKey = column6.primary;
            const sqlTypeLowered = column6.getSQLType().toLowerCase();
            const typeSchema = (0, import_drizzle_orm.is)(column6, import_pg_core.PgEnumColumn) ? column6.enum.schema || "public" : void 0;
            const generated = column6.generated;
            const identity = column6.generatedIdentity;
            const increment = stringFromIdentityProperty(identity?.sequenceOptions?.increment) ?? "1";
            const minValue = stringFromIdentityProperty(identity?.sequenceOptions?.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column6.columnType) : "1");
            const maxValue = stringFromIdentityProperty(identity?.sequenceOptions?.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column6.getSQLType()));
            const startWith = stringFromIdentityProperty(identity?.sequenceOptions?.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
            const cache5 = stringFromIdentityProperty(identity?.sequenceOptions?.cache) ?? "1";
            const columnToSet = {
              name: column6.name,
              type: column6.getSQLType(),
              typeSchema,
              primaryKey,
              notNull,
              generated: generated ? {
                as: (0, import_drizzle_orm.is)(generated.as, import_drizzle_orm.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
                type: "stored"
              } : void 0,
              identity: identity ? {
                type: identity.type,
                name: identity.sequenceName ?? `${viewName}_${column6.name}_seq`,
                schema: schema6 ?? "public",
                increment,
                startWith,
                minValue,
                maxValue,
                cache: cache5,
                cycle: identity?.sequenceOptions?.cycle ?? false
              } : void 0
            };
            if (column6.isUnique) {
              const existingUnique = uniqueConstraintObject[column6.uniqueName];
              if (typeof existingUnique !== "undefined") {
                console.log(
                  `
${withStyle.errorWarning(
                    `We've found duplicated unique constraint names in ${source_default.underline.blue(viewName)} table. 
          The unique constraint ${source_default.underline.blue(column6.uniqueName)} on the ${source_default.underline.blue(
                      column6.name
                    )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns
`
                  )}`
                );
                process.exit(1);
              }
              uniqueConstraintObject[column6.uniqueName] = {
                name: column6.uniqueName,
                nullsNotDistinct: column6.uniqueType === "not distinct",
                columns: [columnToSet.name]
              };
            }
            if (column6.default !== void 0) {
              if ((0, import_drizzle_orm.is)(column6.default, import_drizzle_orm.SQL)) {
                columnToSet.default = sqlToStr(column6.default, casing2);
              } else {
                if (typeof column6.default === "string") {
                  columnToSet.default = `'${column6.default}'`;
                } else {
                  if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
                    columnToSet.default = `'${JSON.stringify(column6.default)}'::${sqlTypeLowered}`;
                  } else if (column6.default instanceof Date) {
                    if (sqlTypeLowered === "date") {
                      columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`;
                    } else if (sqlTypeLowered === "timestamp") {
                      columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                    } else {
                      columnToSet.default = `'${column6.default.toISOString()}'`;
                    }
                  } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column6.default)) {
                    columnToSet.default = `'${buildArrayString(column6.default, sqlTypeLowered)}'`;
                  } else {
                    columnToSet.default = column6.default;
                  }
                }
              }
            }
            columnsObject[column6.name] = columnToSet;
          }
        }
        resultViews[viewKey] = {
          columns: columnsObject,
          definition: isExisting ? void 0 : dialect6.sqlToQuery(query).sql,
          name: viewName,
          schema: viewSchema,
          isExisting,
          with: withOption,
          withNoData,
          materialized,
          tablespace,
          using
        };
      }
      const enumsToReturn = enums.reduce((map2, obj) => {
        const enumSchema4 = obj.schema || "public";
        const key = `${enumSchema4}.${obj.enumName}`;
        map2[key] = {
          name: obj.enumName,
          schema: enumSchema4,
          values: obj.enumValues
        };
        return map2;
      }, {});
      const schemasObject = Object.fromEntries(
        schemas.filter((it) => {
          if (schemaFilter) {
            return schemaFilter.includes(it.schemaName) && it.schemaName !== "public";
          } else {
            return it.schemaName !== "public";
          }
        }).map((it) => [it.schemaName, it.schemaName])
      );
      return {
        version: "7",
        dialect: "postgresql",
        tables: result,
        enums: enumsToReturn,
        schemas: schemasObject,
        sequences: sequencesToReturn,
        roles: rolesToReturn,
        policies: policiesToReturn,
        views: resultViews,
        _meta: {
          schemas: {},
          tables: {},
          columns: {}
        }
      };
    };
    trimChar = (str, char) => {
      let start = 0;
      let end = str.length;
      while (start < end && str[start] === char) ++start;
      while (end > start && str[end - 1] === char) --end;
      return start > 0 || end < str.length ? str.substring(start, end) : str.toString();
    };
    fromDatabase = async (db, tablesFilter = () => true, schemaFilters, entities, progressCallback, tsSchema) => {
      const result = {};
      const views = {};
      const policies = {};
      const internals = { tables: {} };
      const where = schemaFilters.map((t6) => `n.nspname = '${t6}'`).join(" or ");
      const allTables = await db.query(
        `SELECT 
    n.nspname AS table_schema, 
    c.relname AS table_name, 
    CASE 
        WHEN c.relkind = 'r' THEN 'table'
        WHEN c.relkind = 'v' THEN 'view'
        WHEN c.relkind = 'm' THEN 'materialized_view'
    END AS type,
	c.relrowsecurity AS rls_enabled
FROM 
    pg_catalog.pg_class c
JOIN 
    pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE 
	c.relkind IN ('r', 'v', 'm') 
    ${where === "" ? "" : ` AND ${where}`};`
      );
      const schemas = new Set(allTables.map((it) => it.table_schema));
      schemas.delete("public");
      const allSchemas = await db.query(`select s.nspname as table_schema
  from pg_catalog.pg_namespace s
  join pg_catalog.pg_user u on u.usesysid = s.nspowner
  where nspname not in ('information_schema', 'pg_catalog', 'public')
        and nspname not like 'pg_toast%'
        and nspname not like 'pg_temp_%'
  order by table_schema;`);
      allSchemas.forEach((item) => {
        if (schemaFilters.includes(item.table_schema)) {
          schemas.add(item.table_schema);
        }
      });
      let columnsCount = 0;
      let indexesCount = 0;
      let foreignKeysCount = 0;
      let tableCount = 0;
      let checksCount = 0;
      let viewsCount = 0;
      const sequencesToReturn = {};
      const seqWhere = schemaFilters.map((t6) => `schemaname = '${t6}'`).join(" or ");
      const allSequences = await db.query(
        `select schemaname, sequencename, start_value, min_value, max_value, increment_by, cycle, cache_size from pg_sequences as seq${seqWhere === "" ? "" : ` WHERE ${seqWhere}`};`
      );
      for (const dbSeq of allSequences) {
        const schemaName = dbSeq.schemaname;
        const sequenceName = dbSeq.sequencename;
        const startValue = stringFromDatabaseIdentityProperty(dbSeq.start_value);
        const minValue = stringFromDatabaseIdentityProperty(dbSeq.min_value);
        const maxValue = stringFromDatabaseIdentityProperty(dbSeq.max_value);
        const incrementBy = stringFromDatabaseIdentityProperty(dbSeq.increment_by);
        const cycle = dbSeq.cycle;
        const cacheSize = stringFromDatabaseIdentityProperty(dbSeq.cache_size);
        const key = `${schemaName}.${sequenceName}`;
        sequencesToReturn[key] = {
          name: sequenceName,
          schema: schemaName,
          startWith: startValue,
          minValue,
          maxValue,
          increment: incrementBy,
          cycle,
          cache: cacheSize
        };
      }
      const whereEnums = schemaFilters.map((t6) => `n.nspname = '${t6}'`).join(" or ");
      const allEnums = await db.query(
        `select n.nspname as enum_schema,
  t.typname as enum_name,
  e.enumlabel as enum_value,
  e.enumsortorder as sort_order
  from pg_type t
  join pg_enum e on t.oid = e.enumtypid
  join pg_catalog.pg_namespace n ON n.oid = t.typnamespace
  ${whereEnums === "" ? "" : ` WHERE ${whereEnums}`}
  order by enum_schema, enum_name, sort_order;`
      );
      const enumsToReturn = {};
      for (const dbEnum of allEnums) {
        const enumName = dbEnum.enum_name;
        const enumValue = dbEnum.enum_value;
        const enumSchema4 = dbEnum.enum_schema || "public";
        const key = `${enumSchema4}.${enumName}`;
        if (enumsToReturn[key] !== void 0 && enumsToReturn[key] !== null) {
          enumsToReturn[key].values.push(enumValue);
        } else {
          enumsToReturn[key] = {
            name: enumName,
            values: [enumValue],
            schema: enumSchema4
          };
        }
      }
      if (progressCallback) {
        progressCallback("enums", Object.keys(enumsToReturn).length, "done");
      }
      const allRoles = await db.query(
        `SELECT rolname, rolinherit, rolcreatedb, rolcreaterole FROM pg_roles;`
      );
      const rolesToReturn = {};
      const preparedRoles = prepareRoles(entities);
      if (preparedRoles.useRoles || !(preparedRoles.includeRoles.length === 0 && preparedRoles.excludeRoles.length === 0)) {
        for (const dbRole of allRoles) {
          if (preparedRoles.useRoles) {
            rolesToReturn[dbRole.rolname] = {
              createDb: dbRole.rolcreatedb,
              createRole: dbRole.rolcreatedb,
              inherit: dbRole.rolinherit,
              name: dbRole.rolname
            };
          } else {
            if (preparedRoles.includeRoles.length === 0 && preparedRoles.excludeRoles.length === 0) continue;
            if (preparedRoles.includeRoles.includes(dbRole.rolname) && preparedRoles.excludeRoles.includes(dbRole.rolname)) continue;
            if (preparedRoles.excludeRoles.includes(dbRole.rolname)) continue;
            if (!preparedRoles.includeRoles.includes(dbRole.rolname)) continue;
            rolesToReturn[dbRole.rolname] = {
              createDb: dbRole.rolcreatedb,
              createRole: dbRole.rolcreaterole,
              inherit: dbRole.rolinherit,
              name: dbRole.rolname
            };
          }
        }
      }
      const schemasForLinkedPoliciesInSchema = Object.values(tsSchema?.policies ?? {}).map((it) => it.schema);
      const wherePolicies = [...schemaFilters, ...schemasForLinkedPoliciesInSchema].map((t6) => `schemaname = '${t6}'`).join(" or ");
      const policiesByTable = {};
      const allPolicies = await db.query(`SELECT schemaname, tablename, policyname as name, permissive as "as", roles as to, cmd as for, qual as using, with_check as "withCheck" FROM pg_policies${wherePolicies === "" ? "" : ` WHERE ${wherePolicies}`};`);
      for (const dbPolicy of allPolicies) {
        const { tablename, schemaname, to, withCheck, using, ...rest } = dbPolicy;
        const tableForPolicy = policiesByTable[`${schemaname}.${tablename}`];
        const parsedTo = typeof to === "string" ? to.slice(1, -1).split(",") : to;
        const parsedWithCheck = withCheck === null ? void 0 : withCheck;
        const parsedUsing = using === null ? void 0 : using;
        if (tableForPolicy) {
          tableForPolicy[dbPolicy.name] = { ...rest, to: parsedTo };
        } else {
          policiesByTable[`${schemaname}.${tablename}`] = {
            [dbPolicy.name]: { ...rest, to: parsedTo, withCheck: parsedWithCheck, using: parsedUsing }
          };
        }
        if (tsSchema?.policies[dbPolicy.name]) {
          policies[dbPolicy.name] = {
            ...rest,
            to: parsedTo,
            withCheck: parsedWithCheck,
            using: parsedUsing,
            on: tsSchema?.policies[dbPolicy.name].on
          };
        }
      }
      if (progressCallback) {
        progressCallback(
          "policies",
          Object.values(policiesByTable).reduce((total, innerRecord) => {
            return total + Object.keys(innerRecord).length;
          }, 0),
          "done"
        );
      }
      const sequencesInColumns = [];
      const all = allTables.filter((it) => it.type === "table").map((row) => {
        return new Promise(async (res, rej) => {
          const tableName = row.table_name;
          if (!tablesFilter(tableName)) return res("");
          tableCount += 1;
          const tableSchema = row.table_schema;
          try {
            const columnToReturn = {};
            const indexToReturn = {};
            const foreignKeysToReturn = {};
            const primaryKeys = {};
            const uniqueConstrains = {};
            const checkConstraints = {};
            const tableResponse = await getColumnsInfoQuery({ schema: tableSchema, table: tableName, db });
            const tableConstraints = await db.query(
              `SELECT c.column_name, c.data_type, constraint_type, constraint_name, constraint_schema
      FROM information_schema.table_constraints tc
      JOIN information_schema.constraint_column_usage AS ccu USING (constraint_schema, constraint_name)
      JOIN information_schema.columns AS c ON c.table_schema = tc.constraint_schema
        AND tc.table_name = c.table_name AND ccu.column_name = c.column_name
      WHERE tc.table_name = '${tableName}' and constraint_schema = '${tableSchema}';`
            );
            const tableChecks = await db.query(`SELECT 
						tc.constraint_name,
						tc.constraint_type,
						pg_get_constraintdef(con.oid) AS constraint_definition
					FROM 
						information_schema.table_constraints AS tc
						JOIN pg_constraint AS con 
							ON tc.constraint_name = con.conname
							AND con.conrelid = (
								SELECT oid 
								FROM pg_class 
								WHERE relname = tc.table_name 
								AND relnamespace = (
									SELECT oid 
									FROM pg_namespace 
									WHERE nspname = tc.constraint_schema
								)
							)
					WHERE 
						tc.table_name = '${tableName}'
						AND tc.constraint_schema = '${tableSchema}'
						AND tc.constraint_type = 'CHECK'
						AND con.contype = 'c';`);
            columnsCount += tableResponse.length;
            if (progressCallback) {
              progressCallback("columns", columnsCount, "fetching");
            }
            const tableForeignKeys = await db.query(
              `SELECT
            con.contype AS constraint_type,
            nsp.nspname AS constraint_schema,
            con.conname AS constraint_name,
            rel.relname AS table_name,
            att.attname AS column_name,
            fnsp.nspname AS foreign_table_schema,
            frel.relname AS foreign_table_name,
            fatt.attname AS foreign_column_name,
            CASE con.confupdtype
              WHEN 'a' THEN 'NO ACTION'
              WHEN 'r' THEN 'RESTRICT'
              WHEN 'n' THEN 'SET NULL'
              WHEN 'c' THEN 'CASCADE'
              WHEN 'd' THEN 'SET DEFAULT'
            END AS update_rule,
            CASE con.confdeltype
              WHEN 'a' THEN 'NO ACTION'
              WHEN 'r' THEN 'RESTRICT'
              WHEN 'n' THEN 'SET NULL'
              WHEN 'c' THEN 'CASCADE'
              WHEN 'd' THEN 'SET DEFAULT'
            END AS delete_rule
          FROM
            pg_catalog.pg_constraint con
            JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid
            JOIN pg_catalog.pg_namespace nsp ON nsp.oid = con.connamespace
            LEFT JOIN pg_catalog.pg_attribute att ON att.attnum = ANY (con.conkey)
              AND att.attrelid = con.conrelid
            LEFT JOIN pg_catalog.pg_class frel ON frel.oid = con.confrelid
            LEFT JOIN pg_catalog.pg_namespace fnsp ON fnsp.oid = frel.relnamespace
            LEFT JOIN pg_catalog.pg_attribute fatt ON fatt.attnum = ANY (con.confkey)
              AND fatt.attrelid = con.confrelid
          WHERE
            nsp.nspname = '${tableSchema}'
            AND rel.relname = '${tableName}'
            AND con.contype IN ('f');`
            );
            foreignKeysCount += tableForeignKeys.length;
            if (progressCallback) {
              progressCallback("fks", foreignKeysCount, "fetching");
            }
            for (const fk5 of tableForeignKeys) {
              const columnFrom = fk5.column_name;
              const tableTo = fk5.foreign_table_name;
              const columnTo = fk5.foreign_column_name;
              const schemaTo = fk5.foreign_table_schema;
              const foreignKeyName = fk5.constraint_name;
              const onUpdate = fk5.update_rule?.toLowerCase();
              const onDelete = fk5.delete_rule?.toLowerCase();
              if (typeof foreignKeysToReturn[foreignKeyName] !== "undefined") {
                foreignKeysToReturn[foreignKeyName].columnsFrom.push(columnFrom);
                foreignKeysToReturn[foreignKeyName].columnsTo.push(columnTo);
              } else {
                foreignKeysToReturn[foreignKeyName] = {
                  name: foreignKeyName,
                  tableFrom: tableName,
                  tableTo,
                  schemaTo,
                  columnsFrom: [columnFrom],
                  columnsTo: [columnTo],
                  onDelete,
                  onUpdate
                };
              }
              foreignKeysToReturn[foreignKeyName].columnsFrom = [
                ...new Set(foreignKeysToReturn[foreignKeyName].columnsFrom)
              ];
              foreignKeysToReturn[foreignKeyName].columnsTo = [...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)];
            }
            const uniqueConstrainsRows = tableConstraints.filter((mapRow) => mapRow.constraint_type === "UNIQUE");
            for (const unqs of uniqueConstrainsRows) {
              const columnName = unqs.column_name;
              const constraintName = unqs.constraint_name;
              if (typeof uniqueConstrains[constraintName] !== "undefined") {
                uniqueConstrains[constraintName].columns.push(columnName);
              } else {
                uniqueConstrains[constraintName] = {
                  columns: [columnName],
                  nullsNotDistinct: false,
                  name: constraintName
                };
              }
            }
            checksCount += tableChecks.length;
            if (progressCallback) {
              progressCallback("checks", checksCount, "fetching");
            }
            for (const checks of tableChecks) {
              let checkValue = checks.constraint_definition;
              const constraintName = checks.constraint_name;
              checkValue = checkValue.replace(/^CHECK\s*\(\(/, "").replace(/\)\)\s*$/, "");
              checkConstraints[constraintName] = {
                name: constraintName,
                value: checkValue
              };
            }
            for (const columnResponse of tableResponse) {
              const columnName = columnResponse.column_name;
              const columnAdditionalDT = columnResponse.additional_dt;
              const columnDimensions = columnResponse.array_dimensions;
              const enumType2 = columnResponse.enum_name;
              let columnType = columnResponse.data_type;
              const typeSchema = columnResponse.type_schema;
              const defaultValueRes = columnResponse.column_default;
              const isGenerated = columnResponse.is_generated === "ALWAYS";
              const generationExpression = columnResponse.generation_expression;
              const isIdentity = columnResponse.is_identity === "YES";
              const identityGeneration = columnResponse.identity_generation === "ALWAYS" ? "always" : "byDefault";
              const identityStart = columnResponse.identity_start;
              const identityIncrement = columnResponse.identity_increment;
              const identityMaximum = columnResponse.identity_maximum;
              const identityMinimum = columnResponse.identity_minimum;
              const identityCycle = columnResponse.identity_cycle === "YES";
              const identityName = columnResponse.seq_name;
              const primaryKey = tableConstraints.filter(
                (mapRow) => columnName === mapRow.column_name && mapRow.constraint_type === "PRIMARY KEY"
              );
              const cprimaryKey = tableConstraints.filter((mapRow) => mapRow.constraint_type === "PRIMARY KEY");
              if (cprimaryKey.length > 1) {
                const tableCompositePkName = await db.query(
                  `SELECT conname AS primary_key
            FROM   pg_constraint join pg_class on (pg_class.oid = conrelid)
            WHERE  contype = 'p' 
            AND    connamespace = $1::regnamespace  
            AND    pg_class.relname = $2;`,
                  [tableSchema, tableName]
                );
                primaryKeys[tableCompositePkName[0].primary_key] = {
                  name: tableCompositePkName[0].primary_key,
                  columns: cprimaryKey.map((c5) => c5.column_name)
                };
              }
              let columnTypeMapped = columnType;
              if (columnAdditionalDT === "ARRAY") {
                if (typeof internals.tables[tableName] === "undefined") {
                  internals.tables[tableName] = {
                    columns: {
                      [columnName]: {
                        isArray: true,
                        dimensions: columnDimensions,
                        rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
                      }
                    }
                  };
                } else {
                  if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
                    internals.tables[tableName].columns[columnName] = {
                      isArray: true,
                      dimensions: columnDimensions,
                      rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
                    };
                  }
                }
              }
              const defaultValue = defaultForColumn(columnResponse, internals, tableName);
              if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
                if (typeof internals.tables[tableName] === "undefined") {
                  internals.tables[tableName] = {
                    columns: {
                      [columnName]: {
                        isDefaultAnExpression: true
                      }
                    }
                  };
                } else {
                  if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
                    internals.tables[tableName].columns[columnName] = {
                      isDefaultAnExpression: true
                    };
                  } else {
                    internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
                  }
                }
              }
              const isSerial = columnType === "serial";
              if (columnTypeMapped.startsWith("numeric(")) {
                columnTypeMapped = columnTypeMapped.replace(",", ", ");
              }
              if (columnAdditionalDT === "ARRAY") {
                for (let i6 = 1; i6 < Number(columnDimensions); i6++) {
                  columnTypeMapped += "[]";
                }
              }
              columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
              columnTypeMapped = trimChar(columnTypeMapped, '"');
              columnToReturn[columnName] = {
                name: columnName,
                type: (
                  // filter vectors, but in future we should filter any extension that was installed by user
                  columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry", "halfvec", "sparsevec", "bit"].includes(enumType2) ? enumType2 : columnTypeMapped
                ),
                typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0,
                primaryKey: primaryKey.length === 1 && cprimaryKey.length < 2,
                // default: isSerial ? undefined : defaultValue,
                notNull: columnResponse.is_nullable === "NO",
                generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0,
                identity: isIdentity ? {
                  type: identityGeneration,
                  name: identityName,
                  increment: stringFromDatabaseIdentityProperty(identityIncrement),
                  minValue: stringFromDatabaseIdentityProperty(identityMinimum),
                  maxValue: stringFromDatabaseIdentityProperty(identityMaximum),
                  startWith: stringFromDatabaseIdentityProperty(identityStart),
                  cache: sequencesToReturn[identityName]?.cache ? sequencesToReturn[identityName]?.cache : sequencesToReturn[`${tableSchema}.${identityName}`]?.cache ? sequencesToReturn[`${tableSchema}.${identityName}`]?.cache : void 0,
                  cycle: identityCycle,
                  schema: tableSchema
                } : void 0
              };
              if (identityName && typeof identityName === "string") {
                delete sequencesToReturn[`${tableSchema}.${identityName.startsWith('"') && identityName.endsWith('"') ? identityName.slice(1, -1) : identityName}`];
                delete sequencesToReturn[identityName];
              }
              if (!isSerial && typeof defaultValue !== "undefined") {
                columnToReturn[columnName].default = defaultValue;
              }
            }
            const dbIndexes = await db.query(
              `SELECT  DISTINCT ON (t.relname, ic.relname, k.i) t.relname as table_name, ic.relname AS indexname,
        k.i AS index_order,
        i.indisunique as is_unique,
        am.amname as method,
        ic.reloptions as with,
        coalesce(a.attname, pg_get_indexdef(i.indexrelid, k.i, false)) AS column_name,
          CASE
        WHEN pg_get_expr(i.indexprs, i.indrelid) IS NOT NULL THEN 1
        ELSE 0
    END AS is_expression,
        i.indoption[k.i-1] & 1 = 1 AS descending,
        i.indoption[k.i-1] & 2 = 2 AS nulls_first,
        pg_get_expr(
                              i.indpred,
                              i.indrelid
                          ) as where,
         opc.opcname
      FROM pg_class t
          LEFT JOIN pg_index i ON t.oid = i.indrelid
          LEFT JOIN pg_class ic ON ic.oid = i.indexrelid
		  CROSS JOIN LATERAL (SELECT unnest(i.indkey), generate_subscripts(i.indkey, 1) + 1) AS k(attnum, i)
          LEFT JOIN pg_attribute AS a
            ON i.indrelid = a.attrelid AND k.attnum = a.attnum
          JOIN pg_namespace c on c.oid = t.relnamespace
        LEFT JOIN pg_am AS am ON ic.relam = am.oid
        JOIN pg_opclass opc ON opc.oid = ANY(i.indclass)
      WHERE
      c.nspname = '${tableSchema}' AND
      t.relname = '${tableName}';`
            );
            const dbIndexFromConstraint = await db.query(
              `SELECT
          idx.indexrelname AS index_name,
          idx.relname AS table_name,
          schemaname,
          CASE WHEN con.conname IS NOT NULL THEN 1 ELSE 0 END AS generated_by_constraint
        FROM
          pg_stat_user_indexes idx
        LEFT JOIN
          pg_constraint con ON con.conindid = idx.indexrelid
        WHERE idx.relname = '${tableName}' and schemaname = '${tableSchema}'
        group by index_name, table_name,schemaname, generated_by_constraint;`
            );
            const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map(
              (it) => it.index_name
            );
            for (const dbIndex of dbIndexes) {
              const indexName2 = dbIndex.indexname;
              const indexColumnName = dbIndex.column_name;
              const indexIsUnique = dbIndex.is_unique;
              const indexMethod = dbIndex.method;
              const indexWith = dbIndex.with;
              const indexWhere = dbIndex.where;
              const opclass = dbIndex.opcname;
              const isExpression = dbIndex.is_expression === 1;
              const desc = dbIndex.descending;
              const nullsFirst = dbIndex.nulls_first;
              const mappedWith = {};
              if (indexWith !== null) {
                indexWith.forEach((it) => {
                  const splitted = it.split("=");
                  mappedWith[splitted[0]] = splitted[1];
                });
              }
              if (idxsInConsteraint.includes(indexName2)) continue;
              if (typeof indexToReturn[indexName2] !== "undefined") {
                indexToReturn[indexName2].columns.push({
                  expression: indexColumnName,
                  asc: !desc,
                  nulls: nullsFirst ? "first" : "last",
                  opclass,
                  isExpression
                });
              } else {
                indexToReturn[indexName2] = {
                  name: indexName2,
                  columns: [
                    {
                      expression: indexColumnName,
                      asc: !desc,
                      nulls: nullsFirst ? "first" : "last",
                      opclass,
                      isExpression
                    }
                  ],
                  isUnique: indexIsUnique,
                  // should not be a part of diff detects
                  concurrently: false,
                  method: indexMethod,
                  where: indexWhere === null ? void 0 : indexWhere,
                  with: mappedWith
                };
              }
            }
            indexesCount += Object.keys(indexToReturn).length;
            if (progressCallback) {
              progressCallback("indexes", indexesCount, "fetching");
            }
            result[`${tableSchema}.${tableName}`] = {
              name: tableName,
              schema: tableSchema !== "public" ? tableSchema : "",
              columns: columnToReturn,
              indexes: indexToReturn,
              foreignKeys: foreignKeysToReturn,
              compositePrimaryKeys: primaryKeys,
              uniqueConstraints: uniqueConstrains,
              checkConstraints,
              policies: policiesByTable[`${tableSchema}.${tableName}`] ?? {},
              isRLSEnabled: row.rls_enabled
            };
          } catch (e6) {
            rej(e6);
            return;
          }
          res("");
        });
      });
      if (progressCallback) {
        progressCallback("tables", tableCount, "done");
      }
      for await (const _3 of all) {
      }
      const allViews = allTables.filter((it) => it.type === "view" || it.type === "materialized_view").map((row) => {
        return new Promise(async (res, rej) => {
          const viewName = row.table_name;
          if (!tablesFilter(viewName)) return res("");
          tableCount += 1;
          const viewSchema = row.table_schema;
          try {
            const columnToReturn = {};
            const viewResponses = await getColumnsInfoQuery({ schema: viewSchema, table: viewName, db });
            for (const viewResponse of viewResponses) {
              const columnName = viewResponse.column_name;
              const columnAdditionalDT = viewResponse.additional_dt;
              const columnDimensions = viewResponse.array_dimensions;
              const enumType2 = viewResponse.enum_name;
              let columnType = viewResponse.data_type;
              const typeSchema = viewResponse.type_schema;
              const isGenerated = viewResponse.is_generated === "ALWAYS";
              const generationExpression = viewResponse.generation_expression;
              const isIdentity = viewResponse.is_identity === "YES";
              const identityGeneration = viewResponse.identity_generation === "ALWAYS" ? "always" : "byDefault";
              const identityStart = viewResponse.identity_start;
              const identityIncrement = viewResponse.identity_increment;
              const identityMaximum = viewResponse.identity_maximum;
              const identityMinimum = viewResponse.identity_minimum;
              const identityCycle = viewResponse.identity_cycle === "YES";
              const identityName = viewResponse.seq_name;
              const defaultValueRes = viewResponse.column_default;
              const primaryKey = viewResponse.constraint_type === "PRIMARY KEY";
              let columnTypeMapped = columnType;
              if (columnAdditionalDT === "ARRAY") {
                if (typeof internals.tables[viewName] === "undefined") {
                  internals.tables[viewName] = {
                    columns: {
                      [columnName]: {
                        isArray: true,
                        dimensions: columnDimensions,
                        rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
                      }
                    }
                  };
                } else {
                  if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
                    internals.tables[viewName].columns[columnName] = {
                      isArray: true,
                      dimensions: columnDimensions,
                      rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
                    };
                  }
                }
              }
              const defaultValue = defaultForColumn(viewResponse, internals, viewName);
              if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
                if (typeof internals.tables[viewName] === "undefined") {
                  internals.tables[viewName] = {
                    columns: {
                      [columnName]: {
                        isDefaultAnExpression: true
                      }
                    }
                  };
                } else {
                  if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
                    internals.tables[viewName].columns[columnName] = {
                      isDefaultAnExpression: true
                    };
                  } else {
                    internals.tables[viewName].columns[columnName].isDefaultAnExpression = true;
                  }
                }
              }
              const isSerial = columnType === "serial";
              if (columnTypeMapped.startsWith("numeric(")) {
                columnTypeMapped = columnTypeMapped.replace(",", ", ");
              }
              if (columnAdditionalDT === "ARRAY") {
                for (let i6 = 1; i6 < Number(columnDimensions); i6++) {
                  columnTypeMapped += "[]";
                }
              }
              columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
              columnTypeMapped = trimChar(columnTypeMapped, '"');
              columnToReturn[columnName] = {
                name: columnName,
                type: (
                  // filter vectors, but in future we should filter any extension that was installed by user
                  columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry", "halfvec", "sparsevec", "bit"].includes(enumType2) ? enumType2 : columnTypeMapped
                ),
                typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0,
                primaryKey,
                notNull: viewResponse.is_nullable === "NO",
                generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0,
                identity: isIdentity ? {
                  type: identityGeneration,
                  name: identityName,
                  increment: stringFromDatabaseIdentityProperty(identityIncrement),
                  minValue: stringFromDatabaseIdentityProperty(identityMinimum),
                  maxValue: stringFromDatabaseIdentityProperty(identityMaximum),
                  startWith: stringFromDatabaseIdentityProperty(identityStart),
                  cache: sequencesToReturn[identityName]?.cache ? sequencesToReturn[identityName]?.cache : sequencesToReturn[`${viewSchema}.${identityName}`]?.cache ? sequencesToReturn[`${viewSchema}.${identityName}`]?.cache : void 0,
                  cycle: identityCycle,
                  schema: viewSchema
                } : void 0
              };
              if (identityName) {
                delete sequencesToReturn[`${viewSchema}.${identityName.startsWith('"') && identityName.endsWith('"') ? identityName.slice(1, -1) : identityName}`];
                delete sequencesToReturn[identityName];
              }
              if (!isSerial && typeof defaultValue !== "undefined") {
                columnToReturn[columnName].default = defaultValue;
              }
            }
            const [viewInfo] = await db.query(`
					SELECT
    c.relname AS view_name,
    n.nspname AS schema_name,
    pg_get_viewdef(c.oid, true) AS definition,
    ts.spcname AS tablespace_name,
    c.reloptions AS options,
    pg_tablespace_location(ts.oid) AS location
FROM
    pg_class c
JOIN
    pg_namespace n ON c.relnamespace = n.oid
LEFT JOIN
    pg_tablespace ts ON c.reltablespace = ts.oid 
WHERE
    (c.relkind = 'm' OR c.relkind = 'v')
    AND n.nspname = '${viewSchema}'
    AND c.relname = '${viewName}';`);
            const resultWith = {};
            if (viewInfo.options) {
              viewInfo.options.forEach((pair) => {
                const splitted = pair.split("=");
                const key = splitted[0];
                const value = splitted[1];
                if (value === "true") {
                  resultWith[key] = true;
                } else if (value === "false") {
                  resultWith[key] = false;
                } else if (!isNaN(Number(value))) {
                  resultWith[key] = Number(value);
                } else {
                  resultWith[key] = value;
                }
              });
            }
            const definition = viewInfo.definition.replace(/\s+/g, " ").replace(";", "").trim();
            const withOption = Object.values(resultWith).length ? Object.fromEntries(Object.entries(resultWith).map(([key, value]) => [key.camelCase(), value])) : void 0;
            const materialized = row.type === "materialized_view";
            views[`${viewSchema}.${viewName}`] = {
              name: viewName,
              schema: viewSchema,
              columns: columnToReturn,
              isExisting: false,
              definition,
              materialized,
              with: withOption,
              tablespace: viewInfo.tablespace_name ?? void 0
            };
          } catch (e6) {
            rej(e6);
            return;
          }
          res("");
        });
      });
      viewsCount = allViews.length;
      for await (const _3 of allViews) {
      }
      if (progressCallback) {
        progressCallback("columns", columnsCount, "done");
        progressCallback("indexes", indexesCount, "done");
        progressCallback("fks", foreignKeysCount, "done");
        progressCallback("checks", checksCount, "done");
        progressCallback("views", viewsCount, "done");
      }
      const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it]));
      return {
        version: "7",
        dialect: "postgresql",
        tables: result,
        enums: enumsToReturn,
        schemas: schemasObject,
        sequences: sequencesToReturn,
        roles: rolesToReturn,
        policies,
        views,
        _meta: {
          schemas: {},
          tables: {},
          columns: {}
        },
        internal: internals
      };
    };
    defaultForColumn = (column6, internals, tableName) => {
      const columnName = column6.column_name;
      const isArray = internals?.tables[tableName]?.columns[columnName]?.isArray ?? false;
      if (column6.column_default === null || column6.column_default === void 0 || column6.data_type === "serial" || column6.data_type === "smallserial" || column6.data_type === "bigserial") {
        return void 0;
      }
      if (column6.column_default.endsWith("[]")) {
        column6.column_default = column6.column_default.slice(0, -2);
      }
      column6.column_default = column6.column_default.replace(/::(.*?)(?<![^\w"])(?=$)/, "");
      const columnDefaultAsString = column6.column_default.toString();
      if (isArray) {
        return `'{${columnDefaultAsString.slice(2, -2).split(/\s*,\s*/g).map((value) => {
          if (["integer", "smallint", "bigint", "double precision", "real"].includes(column6.data_type.slice(0, -2))) {
            return value;
          } else if (column6.data_type.startsWith("timestamp")) {
            return `${value}`;
          } else if (column6.data_type.slice(0, -2) === "interval") {
            return value.replaceAll('"', `"`);
          } else if (column6.data_type.slice(0, -2) === "boolean") {
            return value === "t" ? "true" : "false";
          } else if (["json", "jsonb"].includes(column6.data_type.slice(0, -2))) {
            return JSON.stringify(JSON.stringify(JSON.parse(JSON.parse(value)), null, 0));
          } else {
            return `"${value}"`;
          }
        }).join(",")}}'`;
      }
      if (["integer", "smallint", "bigint", "double precision", "real"].includes(column6.data_type)) {
        if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString)) {
          return Number(columnDefaultAsString);
        } else {
          if (typeof internals.tables[tableName] === "undefined") {
            internals.tables[tableName] = {
              columns: {
                [columnName]: {
                  isDefaultAnExpression: true
                }
              }
            };
          } else {
            if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
              internals.tables[tableName].columns[columnName] = {
                isDefaultAnExpression: true
              };
            } else {
              internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
            }
          }
          return columnDefaultAsString;
        }
      } else if (column6.data_type.includes("numeric")) {
        return columnDefaultAsString.includes("'") ? columnDefaultAsString : `'${columnDefaultAsString}'`;
      } else if (column6.data_type === "json" || column6.data_type === "jsonb") {
        const jsonWithoutSpaces = JSON.stringify(JSON.parse(columnDefaultAsString.slice(1, -1)));
        return `'${jsonWithoutSpaces}'::${column6.data_type}`;
      } else if (column6.data_type === "boolean") {
        return column6.column_default === "true";
      } else if (columnDefaultAsString === "NULL") {
        return `NULL`;
      } else if (columnDefaultAsString.startsWith("'") && columnDefaultAsString.endsWith("'")) {
        return columnDefaultAsString;
      } else {
        return `${columnDefaultAsString.replace(/\\/g, "`\\")}`;
      }
    };
    getColumnsInfoQuery = ({ schema: schema6, table: table6, db }) => {
      return db.query(
        `SELECT 
    a.attrelid::regclass::text AS table_name,  -- Table, view, or materialized view name
    a.attname AS column_name,   -- Column name
    CASE 
        WHEN NOT a.attisdropped THEN 
            CASE 
                WHEN a.attnotnull THEN 'NO'
                ELSE 'YES'
            END 
        ELSE NULL 
    END AS is_nullable,  -- NULL or NOT NULL constraint
    a.attndims AS array_dimensions,  -- Array dimensions
    CASE 
        WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[]) 
        AND EXISTS (
            SELECT FROM pg_attrdef ad
            WHERE ad.adrelid = a.attrelid 
            AND ad.adnum = a.attnum 
            AND pg_get_expr(ad.adbin, ad.adrelid) = 'nextval(''' 
                || pg_get_serial_sequence(a.attrelid::regclass::text, a.attname)::regclass || '''::regclass)'
        )
        THEN CASE a.atttypid
            WHEN 'int'::regtype THEN 'serial'
            WHEN 'int8'::regtype THEN 'bigserial'
            WHEN 'int2'::regtype THEN 'smallserial'
        END
        ELSE format_type(a.atttypid, a.atttypmod)
    END AS data_type,  -- Column data type
--    ns.nspname AS type_schema,  -- Schema name
    pg_get_serial_sequence('"${schema6}"."${table6}"', a.attname)::regclass AS seq_name,  -- Serial sequence (if any)
    c.column_default,  -- Column default value
    c.data_type AS additional_dt,  -- Data type from information_schema
    c.udt_name AS enum_name,  -- Enum type (if applicable)
    c.is_generated,  -- Is it a generated column?
    c.generation_expression,  -- Generation expression (if generated)
    c.is_identity,  -- Is it an identity column?
    c.identity_generation,  -- Identity generation strategy (ALWAYS or BY DEFAULT)
    c.identity_start,  -- Start value of identity column
    c.identity_increment,  -- Increment for identity column
    c.identity_maximum,  -- Maximum value for identity column
    c.identity_minimum,  -- Minimum value for identity column
    c.identity_cycle,  -- Does the identity column cycle?
    enum_ns.nspname AS type_schema  -- Schema of the enum type
FROM 
    pg_attribute a
JOIN 
    pg_class cls ON cls.oid = a.attrelid  -- Join pg_class to get table/view/materialized view info
JOIN 
    pg_namespace ns ON ns.oid = cls.relnamespace  -- Join namespace to get schema info
LEFT JOIN 
    information_schema.columns c ON c.column_name = a.attname 
        AND c.table_schema = ns.nspname 
        AND c.table_name = cls.relname  -- Match schema and table/view name
LEFT JOIN 
    pg_type enum_t ON enum_t.oid = a.atttypid  -- Join to get the type info
LEFT JOIN 
    pg_namespace enum_ns ON enum_ns.oid = enum_t.typnamespace  -- Join to get the enum schema
WHERE 
    a.attnum > 0  -- Valid column numbers only
    AND NOT a.attisdropped  -- Skip dropped columns
    AND cls.relkind IN ('r', 'v', 'm')  -- Include regular tables ('r'), views ('v'), and materialized views ('m')
    AND ns.nspname = '${schema6}'  -- Filter by schema
    AND cls.relname = '${table6}'  -- Filter by table name
ORDER BY 
    a.attnum;  -- Order by column number`
      );
    };
  }
});

// src/cli/selector-ui.ts
var import_hanji4, Select;
var init_selector_ui = __esm({
  "src/cli/selector-ui.ts"() {
    "use strict";
    init_source();
    import_hanji4 = __toESM(require_hanji());
    Select = class extends import_hanji4.Prompt {
      constructor(items) {
        super();
        this.on("attach", (terminal) => terminal.toggleCursor("hide"));
        this.on("detach", (terminal) => terminal.toggleCursor("show"));
        this.data = new import_hanji4.SelectState(
          items.map((it) => ({ label: it, value: `${it}-value` }))
        );
        this.data.bind(this);
      }
      render(status) {
        if (status === "submitted" || status === "aborted") return "";
        let text = ``;
        this.data.items.forEach((it, idx) => {
          text += idx === this.data.selectedIdx ? `${source_default.green("\u276F " + it.label)}` : `  ${it.label}`;
          text += idx != this.data.items.length - 1 ? "\n" : "";
        });
        return text;
      }
      result() {
        return {
          index: this.data.selectedIdx,
          value: this.data.items[this.data.selectedIdx].value
        };
      }
    };
  }
});

// src/serializer/sqliteSerializer.ts
function mapSqlToSqliteType(sqlType) {
  const lowered = sqlType.toLowerCase();
  if ([
    "int",
    "integer",
    "integer auto_increment",
    "tinyint",
    "smallint",
    "mediumint",
    "bigint",
    "unsigned big int",
    "int2",
    "int8"
  ].some((it) => lowered.startsWith(it))) {
    return "integer";
  } else if ([
    "character",
    "varchar",
    "varying character",
    "national varying character",
    "nchar",
    "native character",
    "nvarchar",
    "text",
    "clob"
  ].some((it) => lowered.startsWith(it))) {
    const match2 = lowered.match(/\d+/);
    if (match2) {
      return `text(${match2[0]})`;
    }
    return "text";
  } else if (lowered.startsWith("blob")) {
    return "blob";
  } else if (["real", "double", "double precision", "float"].some((it) => lowered.startsWith(it))) {
    return "real";
  } else {
    return "numeric";
  }
}
function extractGeneratedColumns(input) {
  const columns = {};
  const lines = input.split(/,\s*(?![^()]*\))/);
  for (const line of lines) {
    if (line.includes("GENERATED ALWAYS AS")) {
      const parts = line.trim().split(/\s+/);
      const columnName = parts[0].replace(/[`'"]/g, "");
      const expression = line.substring(line.indexOf("("), line.indexOf(")") + 1).trim();
      const typeIndex = parts.findIndex((part) => part.match(/(stored|virtual)/i));
      let type = "virtual";
      if (typeIndex !== -1) {
        type = parts[typeIndex].replace(/[^a-z]/gi, "").toLowerCase();
      }
      columns[columnName] = {
        columnName,
        expression,
        type
      };
    }
  }
  return columns;
}
function filterIgnoredTablesByField(fieldName) {
  return `${fieldName} != '__drizzle_migrations'
			AND ${fieldName} NOT LIKE '\\_cf\\_%' ESCAPE '\\'
			AND ${fieldName} NOT LIKE '\\_litestream\\_%' ESCAPE '\\'
			AND ${fieldName} NOT LIKE 'libsql\\_%' ESCAPE '\\'
			AND ${fieldName} NOT LIKE 'sqlite\\_%' ESCAPE '\\'`;
}
var import_drizzle_orm2, import_sqlite_core, generateSqliteSnapshot, fromDatabase2;
var init_sqliteSerializer = __esm({
  "src/serializer/sqliteSerializer.ts"() {
    "use strict";
    init_source();
    import_drizzle_orm2 = require("drizzle-orm");
    import_sqlite_core = require("drizzle-orm/sqlite-core");
    init_outputs();
    init_utils();
    init_utils2();
    generateSqliteSnapshot = (tables, views, casing2) => {
      const dialect6 = new import_sqlite_core.SQLiteSyncDialect({ casing: casing2 });
      const result = {};
      const resultViews = {};
      const internal = { indexes: {} };
      for (const table6 of tables) {
        const columnsObject = {};
        const indexesObject = {};
        const foreignKeysObject = {};
        const primaryKeysObject = {};
        const uniqueConstraintObject = {};
        const checkConstraintObject = {};
        const checksInTable = {};
        const {
          name: tableName,
          columns,
          indexes,
          checks,
          foreignKeys: tableForeignKeys,
          primaryKeys,
          uniqueConstraints
        } = (0, import_sqlite_core.getTableConfig)(table6);
        columns.forEach((column6) => {
          const name = getColumnCasing(column6, casing2);
          const notNull = column6.notNull;
          const primaryKey = column6.primary;
          const generated = column6.generated;
          const columnToSet = {
            name,
            type: column6.getSQLType(),
            primaryKey,
            notNull,
            autoincrement: (0, import_drizzle_orm2.is)(column6, import_sqlite_core.SQLiteBaseInteger) ? column6.autoIncrement : false,
            generated: generated ? {
              as: (0, import_drizzle_orm2.is)(generated.as, import_drizzle_orm2.SQL) ? `(${dialect6.sqlToQuery(generated.as, "indexes").sql})` : typeof generated.as === "function" ? `(${dialect6.sqlToQuery(generated.as(), "indexes").sql})` : `(${generated.as})`,
              type: generated.mode ?? "virtual"
            } : void 0
          };
          if (column6.default !== void 0) {
            if ((0, import_drizzle_orm2.is)(column6.default, import_drizzle_orm2.SQL)) {
              columnToSet.default = sqlToStr(column6.default, casing2);
            } else {
              columnToSet.default = typeof column6.default === "string" ? `'${escapeSingleQuotes(column6.default)}'` : typeof column6.default === "object" || Array.isArray(column6.default) ? `'${JSON.stringify(column6.default)}'` : column6.default;
            }
          }
          columnsObject[name] = columnToSet;
          if (column6.isUnique) {
            const existingUnique = indexesObject[column6.uniqueName];
            if (typeof existingUnique !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
          The unique constraint ${source_default.underline.blue(
                  column6.uniqueName
                )} on the ${source_default.underline.blue(
                  name
                )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`)}`
              );
              process.exit(1);
            }
            indexesObject[column6.uniqueName] = {
              name: column6.uniqueName,
              columns: [columnToSet.name],
              isUnique: true
            };
          }
        });
        const foreignKeys = tableForeignKeys.map((fk5) => {
          const tableFrom = tableName;
          const onDelete = fk5.onDelete ?? "no action";
          const onUpdate = fk5.onUpdate ?? "no action";
          const reference = fk5.reference();
          const referenceFT = reference.foreignTable;
          const tableTo = (0, import_drizzle_orm2.getTableName)(referenceFT);
          const originalColumnsFrom = reference.columns.map((it) => it.name);
          const columnsFrom = reference.columns.map((it) => getColumnCasing(it, casing2));
          const originalColumnsTo = reference.foreignColumns.map((it) => it.name);
          const columnsTo = reference.foreignColumns.map((it) => getColumnCasing(it, casing2));
          let name = fk5.getName();
          if (casing2 !== void 0) {
            for (let i6 = 0; i6 < originalColumnsFrom.length; i6++) {
              name = name.replace(originalColumnsFrom[i6], columnsFrom[i6]);
            }
            for (let i6 = 0; i6 < originalColumnsTo.length; i6++) {
              name = name.replace(originalColumnsTo[i6], columnsTo[i6]);
            }
          }
          return {
            name,
            tableFrom,
            tableTo,
            columnsFrom,
            columnsTo,
            onDelete,
            onUpdate
          };
        });
        foreignKeys.forEach((it) => {
          foreignKeysObject[it.name] = it;
        });
        indexes.forEach((value) => {
          const columns2 = value.config.columns;
          const name = value.config.name;
          let indexColumns = columns2.map((it) => {
            if ((0, import_drizzle_orm2.is)(it, import_drizzle_orm2.SQL)) {
              const sql = dialect6.sqlToQuery(it, "indexes").sql;
              if (typeof internal.indexes[name] === "undefined") {
                internal.indexes[name] = {
                  columns: {
                    [sql]: {
                      isExpression: true
                    }
                  }
                };
              } else {
                if (typeof internal.indexes[name]?.columns[sql] === "undefined") {
                  internal.indexes[name].columns[sql] = {
                    isExpression: true
                  };
                } else {
                  internal.indexes[name].columns[sql].isExpression = true;
                }
              }
              return sql;
            } else {
              return getColumnCasing(it, casing2);
            }
          });
          let where = void 0;
          if (value.config.where !== void 0) {
            if ((0, import_drizzle_orm2.is)(value.config.where, import_drizzle_orm2.SQL)) {
              where = dialect6.sqlToQuery(value.config.where).sql;
            }
          }
          indexesObject[name] = {
            name,
            columns: indexColumns,
            isUnique: value.config.unique ?? false,
            where
          };
        });
        uniqueConstraints?.map((unq) => {
          const columnNames = unq.columns.map((c5) => getColumnCasing(c5, casing2));
          const name = unq.name ?? (0, import_sqlite_core.uniqueKeyName)(table6, columnNames);
          const existingUnique = indexesObject[name];
          if (typeof existingUnique !== "undefined") {
            console.log(
              `
${withStyle.errorWarning(
                `We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
The unique constraint ${source_default.underline.blue(
                  name
                )} on the ${source_default.underline.blue(
                  columnNames.join(",")
                )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`
              )}`
            );
            process.exit(1);
          }
          indexesObject[name] = {
            name: unq.name,
            columns: columnNames,
            isUnique: true
          };
        });
        primaryKeys.forEach((it) => {
          if (it.columns.length > 1) {
            const originalColumnNames = it.columns.map((c5) => c5.name);
            const columnNames = it.columns.map((c5) => getColumnCasing(c5, casing2));
            let name = it.getName();
            if (casing2 !== void 0) {
              for (let i6 = 0; i6 < originalColumnNames.length; i6++) {
                name = name.replace(originalColumnNames[i6], columnNames[i6]);
              }
            }
            primaryKeysObject[name] = {
              columns: columnNames,
              name
            };
          } else {
            columnsObject[getColumnCasing(it.columns[0], casing2)].primaryKey = true;
          }
        });
        checks.forEach((check) => {
          const checkName = check.name;
          if (typeof checksInTable[tableName] !== "undefined") {
            if (checksInTable[tableName].includes(check.name)) {
              console.log(
                `
${withStyle.errorWarning(
                  `We've found duplicated check constraint name in ${source_default.underline.blue(
                    tableName
                  )}. Please rename your check constraint in the ${source_default.underline.blue(
                    tableName
                  )} table`
                )}`
              );
              process.exit(1);
            }
            checksInTable[tableName].push(checkName);
          } else {
            checksInTable[tableName] = [check.name];
          }
          checkConstraintObject[checkName] = {
            name: checkName,
            value: dialect6.sqlToQuery(check.value).sql
          };
        });
        result[tableName] = {
          name: tableName,
          columns: columnsObject,
          indexes: indexesObject,
          foreignKeys: foreignKeysObject,
          compositePrimaryKeys: primaryKeysObject,
          uniqueConstraints: uniqueConstraintObject,
          checkConstraints: checkConstraintObject
        };
      }
      for (const view5 of views) {
        const { name, isExisting, selectedFields, query, schema: schema6 } = (0, import_sqlite_core.getViewConfig)(view5);
        const columnsObject = {};
        const existingView = resultViews[name];
        if (typeof existingView !== "undefined") {
          console.log(
            `
${withStyle.errorWarning(
              `We've found duplicated view name across ${source_default.underline.blue(
                schema6 ?? "public"
              )} schema. Please rename your view`
            )}`
          );
          process.exit(1);
        }
        for (const key in selectedFields) {
          if ((0, import_drizzle_orm2.is)(selectedFields[key], import_sqlite_core.SQLiteColumn)) {
            const column6 = selectedFields[key];
            const notNull = column6.notNull;
            const primaryKey = column6.primary;
            const generated = column6.generated;
            const columnToSet = {
              name: column6.name,
              type: column6.getSQLType(),
              primaryKey,
              notNull,
              autoincrement: (0, import_drizzle_orm2.is)(column6, import_sqlite_core.SQLiteBaseInteger) ? column6.autoIncrement : false,
              generated: generated ? {
                as: (0, import_drizzle_orm2.is)(generated.as, import_drizzle_orm2.SQL) ? `(${dialect6.sqlToQuery(generated.as, "indexes").sql})` : typeof generated.as === "function" ? `(${dialect6.sqlToQuery(generated.as(), "indexes").sql})` : `(${generated.as})`,
                type: generated.mode ?? "virtual"
              } : void 0
            };
            if (column6.default !== void 0) {
              if ((0, import_drizzle_orm2.is)(column6.default, import_drizzle_orm2.SQL)) {
                columnToSet.default = sqlToStr(column6.default, casing2);
              } else {
                columnToSet.default = typeof column6.default === "string" ? `'${column6.default}'` : typeof column6.default === "object" || Array.isArray(column6.default) ? `'${JSON.stringify(column6.default)}'` : column6.default;
              }
            }
            columnsObject[column6.name] = columnToSet;
          }
        }
        resultViews[name] = {
          columns: columnsObject,
          name,
          isExisting,
          definition: isExisting ? void 0 : dialect6.sqlToQuery(query).sql
        };
      }
      return {
        version: "6",
        dialect: "sqlite",
        tables: result,
        views: resultViews,
        enums: {},
        _meta: {
          tables: {},
          columns: {}
        },
        internal
      };
    };
    fromDatabase2 = async (db, tablesFilter = (table6) => true, progressCallback) => {
      const result = {};
      const resultViews = {};
      const columns = await db.query(`SELECT 
		  m.name as "tableName",
		  p.name as "columnName",
		  p.type as "columnType",
		  p."notnull" as "notNull",
		  p.dflt_value as "defaultValue",
		  p.pk as pk,
		  p.hidden as hidden,
		  m.sql,
		  m.type as type
		FROM sqlite_master AS m
		JOIN pragma_table_xinfo(m.name) AS p
		WHERE (m.type = 'table' OR m.type = 'view') 
		  AND ${filterIgnoredTablesByField("m.tbl_name")};`);
      const tablesWithSeq = [];
      const seq = await db.query(`SELECT
		  *
		FROM sqlite_master
		WHERE sql GLOB '*[ *' || CHAR(9) || CHAR(10) || CHAR(13) || ']AUTOINCREMENT[^'']*'
    	  AND ${filterIgnoredTablesByField("tbl_name")};`);
      for (const s6 of seq) {
        tablesWithSeq.push(s6.name);
      }
      let columnsCount = 0;
      let tablesCount = /* @__PURE__ */ new Set();
      let indexesCount = 0;
      let foreignKeysCount = 0;
      let checksCount = 0;
      let viewsCount = 0;
      const tableToPk = {};
      let tableToGeneratedColumnsInfo = {};
      for (const column6 of columns) {
        if (!tablesFilter(column6.tableName)) continue;
        if (column6.type !== "view") {
          columnsCount += 1;
        }
        if (progressCallback) {
          progressCallback("columns", columnsCount, "fetching");
        }
        const tableName = column6.tableName;
        tablesCount.add(tableName);
        if (progressCallback) {
          progressCallback("tables", tablesCount.size, "fetching");
        }
        const columnName = column6.columnName;
        const isNotNull = column6.notNull === 1;
        const columnType = column6.columnType;
        const isPrimary = column6.pk !== 0;
        const columnDefault = column6.defaultValue;
        const isAutoincrement = isPrimary && tablesWithSeq.includes(tableName);
        if (isPrimary) {
          if (typeof tableToPk[tableName] === "undefined") {
            tableToPk[tableName] = [columnName];
          } else {
            tableToPk[tableName].push(columnName);
          }
        }
        const table6 = result[tableName];
        if (column6.hidden === 2 || column6.hidden === 3) {
          if (typeof tableToGeneratedColumnsInfo[column6.tableName] === "undefined") {
            tableToGeneratedColumnsInfo[column6.tableName] = extractGeneratedColumns(
              column6.sql
            );
          }
        }
        const newColumn = {
          default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) ? Number(columnDefault) : ["CURRENT_TIME", "CURRENT_DATE", "CURRENT_TIMESTAMP"].includes(
            columnDefault
          ) ? `(${columnDefault})` : columnDefault === "false" ? false : columnDefault === "true" ? true : columnDefault.startsWith("'") && columnDefault.endsWith("'") ? columnDefault : `(${columnDefault})`,
          autoincrement: isAutoincrement,
          name: columnName,
          type: mapSqlToSqliteType(columnType),
          primaryKey: false,
          notNull: isNotNull,
          generated: tableToGeneratedColumnsInfo[tableName] && tableToGeneratedColumnsInfo[tableName][columnName] ? {
            type: tableToGeneratedColumnsInfo[tableName][columnName].type,
            as: tableToGeneratedColumnsInfo[tableName][columnName].expression
          } : void 0
        };
        if (!table6) {
          result[tableName] = {
            name: tableName,
            columns: {
              [columnName]: newColumn
            },
            compositePrimaryKeys: {},
            indexes: {},
            foreignKeys: {},
            uniqueConstraints: {},
            checkConstraints: {}
          };
        } else {
          result[tableName].columns[columnName] = newColumn;
        }
      }
      for (const [key, value] of Object.entries(tableToPk)) {
        if (value.length > 1) {
          result[key].compositePrimaryKeys = {
            [`${key}_${value.join("_")}_pk`]: {
              columns: value,
              name: `${key}_${value.join("_")}_pk`
            }
          };
        } else if (value.length === 1) {
          result[key].columns[value[0]].primaryKey = true;
        } else {
        }
      }
      if (progressCallback) {
        progressCallback("columns", columnsCount, "done");
        progressCallback("tables", tablesCount.size, "done");
      }
      try {
        const fks = await db.query(`SELECT
			  m.name as "tableFrom",
			  f.id as "id",
			  f."table" as "tableTo",
			  f."from",
			  f."to",
			  f."on_update" as "onUpdate",
			  f."on_delete" as "onDelete",
			  f.seq as "seq"
      		FROM
			  sqlite_master m,
			  pragma_foreign_key_list(m.name) as f
      		WHERE ${filterIgnoredTablesByField("m.tbl_name")};`);
        const fkByTableName = {};
        for (const fkRow of fks) {
          foreignKeysCount += 1;
          if (progressCallback) {
            progressCallback("fks", foreignKeysCount, "fetching");
          }
          const tableName = fkRow.tableFrom;
          const columnName = fkRow.from;
          const refTableName = fkRow.tableTo;
          const refColumnName = fkRow.to;
          const updateRule = fkRow.onUpdate;
          const deleteRule = fkRow.onDelete;
          const sequence = fkRow.seq;
          const id = fkRow.id;
          const tableInResult = result[tableName];
          if (typeof tableInResult === "undefined") continue;
          if (typeof fkByTableName[`${tableName}_${id}`] !== "undefined") {
            fkByTableName[`${tableName}_${id}`].columnsFrom.push(columnName);
            fkByTableName[`${tableName}_${id}`].columnsTo.push(refColumnName);
          } else {
            fkByTableName[`${tableName}_${id}`] = {
              name: "",
              tableFrom: tableName,
              tableTo: refTableName,
              columnsFrom: [columnName],
              columnsTo: [refColumnName],
              onDelete: deleteRule?.toLowerCase(),
              onUpdate: updateRule?.toLowerCase()
            };
          }
          const columnsFrom = fkByTableName[`${tableName}_${id}`].columnsFrom;
          const columnsTo = fkByTableName[`${tableName}_${id}`].columnsTo;
          fkByTableName[`${tableName}_${id}`].name = `${tableName}_${columnsFrom.join(
            "_"
          )}_${refTableName}_${columnsTo.join("_")}_fk`;
        }
        for (const idx of Object.keys(fkByTableName)) {
          const value = fkByTableName[idx];
          result[value.tableFrom].foreignKeys[value.name] = value;
        }
      } catch (e6) {
      }
      if (progressCallback) {
        progressCallback("fks", foreignKeysCount, "done");
      }
      const idxs = await db.query(`SELECT 
    	  m.tbl_name as tableName,
    	  il.name as indexName,
    	  ii.name as columnName,
    	  il.[unique] as isUnique,
    	  il.seq as seq
		FROM 
		  sqlite_master AS m,
    	  pragma_index_list(m.name) AS il,
    	  pragma_index_info(il.name) AS ii
		WHERE 
		  m.type = 'table' 
    	  AND il.name NOT LIKE 'sqlite\\_autoindex\\_%' ESCAPE '\\'
    	  AND ${filterIgnoredTablesByField("m.tbl_name")};`);
      for (const idxRow of idxs) {
        const tableName = idxRow.tableName;
        const constraintName = idxRow.indexName;
        const columnName = idxRow.columnName;
        const isUnique = idxRow.isUnique === 1;
        const tableInResult = result[tableName];
        if (typeof tableInResult === "undefined") continue;
        indexesCount += 1;
        if (progressCallback) {
          progressCallback("indexes", indexesCount, "fetching");
        }
        if (typeof tableInResult.indexes[constraintName] !== "undefined" && columnName) {
          tableInResult.indexes[constraintName].columns.push(columnName);
        } else {
          tableInResult.indexes[constraintName] = {
            name: constraintName,
            columns: columnName ? [columnName] : [],
            isUnique
          };
        }
      }
      if (progressCallback) {
        progressCallback("indexes", indexesCount, "done");
        progressCallback("enums", 0, "done");
      }
      const views = await db.query(
        `SELECT name AS view_name, sql AS sql FROM sqlite_master WHERE type = 'view';`
      );
      viewsCount = views.length;
      if (progressCallback) {
        progressCallback("views", viewsCount, "fetching");
      }
      for (const view5 of views) {
        const viewName = view5["view_name"];
        const sql = view5["sql"];
        const regex = new RegExp(`\\bAS\\b\\s+(SELECT.+)$`, "i");
        const match2 = sql.match(regex);
        if (!match2) {
          console.log("Could not process view");
          process.exit(1);
        }
        const viewDefinition = match2[1];
        const columns2 = result[viewName].columns;
        delete result[viewName];
        resultViews[viewName] = {
          columns: columns2,
          isExisting: false,
          name: viewName,
          definition: viewDefinition
        };
      }
      if (progressCallback) {
        progressCallback("views", viewsCount, "done");
      }
      const namedCheckPattern = /CONSTRAINT\s*["']?(\w+)["']?\s*CHECK\s*\((.*?)\)/gi;
      const unnamedCheckPattern = /CHECK\s*\((.*?)\)/gi;
      let checkCounter = 0;
      const checkConstraints = {};
      const checks = await db.query(`SELECT
		  name as "tableName",
		  sql as "sql"
		FROM sqlite_master 
		WHERE type = 'table'
		  AND ${filterIgnoredTablesByField("tbl_name")};`);
      for (const check of checks) {
        if (!tablesFilter(check.tableName)) continue;
        const { tableName, sql } = check;
        let namedChecks = [...sql.matchAll(namedCheckPattern)];
        if (namedChecks.length > 0) {
          namedChecks.forEach(([_3, checkName, checkValue]) => {
            checkConstraints[checkName] = {
              name: checkName,
              value: checkValue.trim()
            };
          });
        } else {
          let unnamedChecks = [...sql.matchAll(unnamedCheckPattern)];
          unnamedChecks.forEach(([_3, checkValue]) => {
            let checkName = `${tableName}_check_${++checkCounter}`;
            checkConstraints[checkName] = {
              name: checkName,
              value: checkValue.trim()
            };
          });
        }
        checksCount += Object.values(checkConstraints).length;
        if (progressCallback) {
          progressCallback("checks", checksCount, "fetching");
        }
        const table6 = result[tableName];
        if (!table6) {
          result[tableName] = {
            name: tableName,
            columns: {},
            compositePrimaryKeys: {},
            indexes: {},
            foreignKeys: {},
            uniqueConstraints: {},
            checkConstraints
          };
        } else {
          result[tableName].checkConstraints = checkConstraints;
        }
      }
      if (progressCallback) {
        progressCallback("checks", checksCount, "done");
      }
      return {
        version: "6",
        dialect: "sqlite",
        tables: result,
        views: resultViews,
        enums: {},
        _meta: {
          tables: {},
          columns: {}
        }
      };
    };
  }
});

// src/extensions/getTablesFilterByExtensions.ts
var getTablesFilterByExtensions;
var init_getTablesFilterByExtensions = __esm({
  "src/extensions/getTablesFilterByExtensions.ts"() {
    "use strict";
    getTablesFilterByExtensions = ({
      extensionsFilters,
      dialect: dialect6
    }) => {
      if (extensionsFilters) {
        if (extensionsFilters.includes("postgis") && dialect6 === "postgresql") {
          return ["!geography_columns", "!geometry_columns", "!spatial_ref_sys"];
        }
      }
      return [];
    };
  }
});

// src/serializer/mysqlSerializer.ts
function clearDefaults(defaultValue, collate) {
  if (typeof collate === "undefined" || collate === null) {
    collate = `utf8mb4`;
  }
  let resultDefault = defaultValue;
  collate = `_${collate}`;
  if (defaultValue.startsWith(collate)) {
    resultDefault = resultDefault.substring(collate.length, defaultValue.length).replace(/\\/g, "");
    if (resultDefault.startsWith("'") && resultDefault.endsWith("'")) {
      return `('${escapeSingleQuotes(resultDefault.substring(1, resultDefault.length - 1))}')`;
    } else {
      return `'${escapeSingleQuotes(resultDefault.substring(1, resultDefault.length - 1))}'`;
    }
  } else {
    return `(${resultDefault})`;
  }
}
var import_drizzle_orm3, import_mysql_core, handleEnumType, generateMySqlSnapshot, fromDatabase3;
var init_mysqlSerializer = __esm({
  "src/serializer/mysqlSerializer.ts"() {
    "use strict";
    init_source();
    import_drizzle_orm3 = require("drizzle-orm");
    import_mysql_core = require("drizzle-orm/mysql-core");
    init_outputs();
    init_utils();
    init_utils2();
    handleEnumType = (type) => {
      let str = type.split("(")[1];
      str = str.substring(0, str.length - 1);
      const values = str.split(",").map((v6) => `'${escapeSingleQuotes(v6.substring(1, v6.length - 1))}'`);
      return `enum(${values.join(",")})`;
    };
    generateMySqlSnapshot = (tables, views, casing2) => {
      const dialect6 = new import_mysql_core.MySqlDialect({ casing: casing2 });
      const result = {};
      const resultViews = {};
      const internal = { tables: {}, indexes: {} };
      for (const table6 of tables) {
        const {
          name: tableName,
          columns,
          indexes,
          foreignKeys,
          schema: schema6,
          checks,
          primaryKeys,
          uniqueConstraints
        } = (0, import_mysql_core.getTableConfig)(table6);
        const columnsObject = {};
        const indexesObject = {};
        const foreignKeysObject = {};
        const primaryKeysObject = {};
        const uniqueConstraintObject = {};
        const checkConstraintObject = {};
        let checksInTable = {};
        columns.forEach((column6) => {
          const name = getColumnCasing(column6, casing2);
          const notNull = column6.notNull;
          const sqlType = column6.getSQLType();
          const sqlTypeLowered = sqlType.toLowerCase();
          const autoIncrement = typeof column6.autoIncrement === "undefined" ? false : column6.autoIncrement;
          const generated = column6.generated;
          const columnToSet = {
            name,
            type: sqlType.startsWith("enum") ? handleEnumType(sqlType) : sqlType,
            primaryKey: false,
            // If field is autoincrement it's notNull by default
            // notNull: autoIncrement ? true : notNull,
            notNull,
            autoincrement: autoIncrement,
            onUpdate: column6.hasOnUpdateNow,
            generated: generated ? {
              as: (0, import_drizzle_orm3.is)(generated.as, import_drizzle_orm3.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
              type: generated.mode ?? "stored"
            } : void 0
          };
          if (column6.primary) {
            primaryKeysObject[`${tableName}_${name}`] = {
              name: `${tableName}_${name}`,
              columns: [name]
            };
          }
          if (column6.isUnique) {
            const existingUnique = uniqueConstraintObject[column6.uniqueName];
            if (typeof existingUnique !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
          The unique constraint ${source_default.underline.blue(
                  column6.uniqueName
                )} on the ${source_default.underline.blue(
                  name
                )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`)}`
              );
              process.exit(1);
            }
            uniqueConstraintObject[column6.uniqueName] = {
              name: column6.uniqueName,
              columns: [columnToSet.name]
            };
          }
          if (column6.default !== void 0) {
            if ((0, import_drizzle_orm3.is)(column6.default, import_drizzle_orm3.SQL)) {
              columnToSet.default = sqlToStr(column6.default, casing2);
            } else {
              if (typeof column6.default === "string") {
                columnToSet.default = `'${escapeSingleQuotes(column6.default)}'`;
              } else {
                if (sqlTypeLowered === "json") {
                  columnToSet.default = `'${JSON.stringify(column6.default)}'`;
                } else if (column6.default instanceof Date) {
                  if (sqlTypeLowered === "date") {
                    columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`;
                  } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
                    columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                  }
                } else {
                  columnToSet.default = column6.default;
                }
              }
              if (["blob", "text", "json"].includes(column6.getSQLType())) {
                columnToSet.default = `(${columnToSet.default})`;
              }
            }
          }
          columnsObject[name] = columnToSet;
        });
        primaryKeys.map((pk) => {
          const originalColumnNames = pk.columns.map((c5) => c5.name);
          const columnNames = pk.columns.map((c5) => getColumnCasing(c5, casing2));
          let name = pk.getName();
          if (casing2 !== void 0) {
            for (let i6 = 0; i6 < originalColumnNames.length; i6++) {
              name = name.replace(originalColumnNames[i6], columnNames[i6]);
            }
          }
          primaryKeysObject[name] = {
            name,
            columns: columnNames
          };
          for (const column6 of pk.columns) {
            columnsObject[getColumnCasing(column6, casing2)].notNull = true;
          }
        });
        uniqueConstraints?.map((unq) => {
          const columnNames = unq.columns.map((c5) => getColumnCasing(c5, casing2));
          const name = unq.name ?? (0, import_mysql_core.uniqueKeyName)(table6, columnNames);
          const existingUnique = uniqueConstraintObject[name];
          if (typeof existingUnique !== "undefined") {
            console.log(
              `
${withStyle.errorWarning(
                `We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
The unique constraint ${source_default.underline.blue(
                  name
                )} on the ${source_default.underline.blue(
                  columnNames.join(",")
                )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`
              )}`
            );
            process.exit(1);
          }
          uniqueConstraintObject[name] = {
            name: unq.name,
            columns: columnNames
          };
        });
        const fks = foreignKeys.map((fk5) => {
          const tableFrom = tableName;
          const onDelete = fk5.onDelete ?? "no action";
          const onUpdate = fk5.onUpdate ?? "no action";
          const reference = fk5.reference();
          const referenceFT = reference.foreignTable;
          const tableTo = (0, import_drizzle_orm3.getTableName)(referenceFT);
          const originalColumnsFrom = reference.columns.map((it) => it.name);
          const columnsFrom = reference.columns.map((it) => getColumnCasing(it, casing2));
          const originalColumnsTo = reference.foreignColumns.map((it) => it.name);
          const columnsTo = reference.foreignColumns.map((it) => getColumnCasing(it, casing2));
          let name = fk5.getName();
          if (casing2 !== void 0) {
            for (let i6 = 0; i6 < originalColumnsFrom.length; i6++) {
              name = name.replace(originalColumnsFrom[i6], columnsFrom[i6]);
            }
            for (let i6 = 0; i6 < originalColumnsTo.length; i6++) {
              name = name.replace(originalColumnsTo[i6], columnsTo[i6]);
            }
          }
          return {
            name,
            tableFrom,
            tableTo,
            columnsFrom,
            columnsTo,
            onDelete,
            onUpdate
          };
        });
        fks.forEach((it) => {
          foreignKeysObject[it.name] = it;
        });
        indexes.forEach((value) => {
          const columns2 = value.config.columns;
          const name = value.config.name;
          let indexColumns = columns2.map((it) => {
            if ((0, import_drizzle_orm3.is)(it, import_drizzle_orm3.SQL)) {
              const sql = dialect6.sqlToQuery(it, "indexes").sql;
              if (typeof internal.indexes[name] === "undefined") {
                internal.indexes[name] = {
                  columns: {
                    [sql]: {
                      isExpression: true
                    }
                  }
                };
              } else {
                if (typeof internal.indexes[name]?.columns[sql] === "undefined") {
                  internal.indexes[name].columns[sql] = {
                    isExpression: true
                  };
                } else {
                  internal.indexes[name].columns[sql].isExpression = true;
                }
              }
              return sql;
            } else {
              return `${getColumnCasing(it, casing2)}`;
            }
          });
          if (value.config.unique) {
            if (typeof uniqueConstraintObject[name] !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(
                  `We've found duplicated unique constraint names in ${source_default.underline.blue(
                    tableName
                  )} table. 
The unique index ${source_default.underline.blue(
                    name
                  )} on the ${source_default.underline.blue(
                    indexColumns.join(",")
                  )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                    uniqueConstraintObject[name].columns.join(",")
                  )} columns
`
                )}`
              );
              process.exit(1);
            }
          } else {
            if (typeof foreignKeysObject[name] !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(
                  `In MySQL, when creating a foreign key, an index is automatically generated with the same name as the foreign key constraint.

We have encountered a collision between the index name on columns ${source_default.underline.blue(
                    indexColumns.join(",")
                  )} and the foreign key on columns ${source_default.underline.blue(
                    foreignKeysObject[name].columnsFrom.join(",")
                  )}. Please change either the index name or the foreign key name. For more information, please refer to https://dev.mysql.com/doc/refman/8.0/en/constraint-foreign-key.html

            `
                )}`
              );
              process.exit(1);
            }
          }
          indexesObject[name] = {
            name,
            columns: indexColumns,
            isUnique: value.config.unique ?? false,
            using: value.config.using,
            algorithm: value.config.algorithm,
            lock: value.config.lock
          };
        });
        checks.forEach((check) => {
          check;
          const checkName = check.name;
          if (typeof checksInTable[tableName] !== "undefined") {
            if (checksInTable[tableName].includes(check.name)) {
              console.log(
                `
${withStyle.errorWarning(
                  `We've found duplicated check constraint name in ${source_default.underline.blue(
                    tableName
                  )}. Please rename your check constraint in the ${source_default.underline.blue(
                    tableName
                  )} table`
                )}`
              );
              process.exit(1);
            }
            checksInTable[tableName].push(checkName);
          } else {
            checksInTable[tableName] = [check.name];
          }
          checkConstraintObject[checkName] = {
            name: checkName,
            value: dialect6.sqlToQuery(check.value).sql
          };
        });
        if (!schema6) {
          result[tableName] = {
            name: tableName,
            columns: columnsObject,
            indexes: indexesObject,
            foreignKeys: foreignKeysObject,
            compositePrimaryKeys: primaryKeysObject,
            uniqueConstraints: uniqueConstraintObject,
            checkConstraint: checkConstraintObject
          };
        }
      }
      for (const view5 of views) {
        const {
          isExisting,
          name,
          query,
          schema: schema6,
          selectedFields,
          algorithm,
          sqlSecurity,
          withCheckOption
        } = (0, import_mysql_core.getViewConfig)(view5);
        const columnsObject = {};
        const existingView = resultViews[name];
        if (typeof existingView !== "undefined") {
          console.log(
            `
${withStyle.errorWarning(
              `We've found duplicated view name across ${source_default.underline.blue(
                schema6 ?? "public"
              )} schema. Please rename your view`
            )}`
          );
          process.exit(1);
        }
        for (const key in selectedFields) {
          if ((0, import_drizzle_orm3.is)(selectedFields[key], import_mysql_core.MySqlColumn)) {
            const column6 = selectedFields[key];
            const notNull = column6.notNull;
            const sqlTypeLowered = column6.getSQLType().toLowerCase();
            const autoIncrement = typeof column6.autoIncrement === "undefined" ? false : column6.autoIncrement;
            const generated = column6.generated;
            const columnToSet = {
              name: column6.name,
              type: column6.getSQLType(),
              primaryKey: false,
              // If field is autoincrement it's notNull by default
              // notNull: autoIncrement ? true : notNull,
              notNull,
              autoincrement: autoIncrement,
              onUpdate: column6.hasOnUpdateNow,
              generated: generated ? {
                as: (0, import_drizzle_orm3.is)(generated.as, import_drizzle_orm3.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
                type: generated.mode ?? "stored"
              } : void 0
            };
            if (column6.default !== void 0) {
              if ((0, import_drizzle_orm3.is)(column6.default, import_drizzle_orm3.SQL)) {
                columnToSet.default = sqlToStr(column6.default, casing2);
              } else {
                if (typeof column6.default === "string") {
                  columnToSet.default = `'${column6.default}'`;
                } else {
                  if (sqlTypeLowered === "json") {
                    columnToSet.default = `'${JSON.stringify(column6.default)}'`;
                  } else if (column6.default instanceof Date) {
                    if (sqlTypeLowered === "date") {
                      columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`;
                    } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
                      columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                    }
                  } else {
                    columnToSet.default = column6.default;
                  }
                }
                if (["blob", "text", "json"].includes(column6.getSQLType())) {
                  columnToSet.default = `(${columnToSet.default})`;
                }
              }
            }
            columnsObject[column6.name] = columnToSet;
          }
        }
        resultViews[name] = {
          columns: columnsObject,
          name,
          isExisting,
          definition: isExisting ? void 0 : dialect6.sqlToQuery(query).sql,
          withCheckOption,
          algorithm: algorithm ?? "undefined",
          // set default values
          sqlSecurity: sqlSecurity ?? "definer"
          // set default values
        };
      }
      return {
        version: "5",
        dialect: "mysql",
        tables: result,
        views: resultViews,
        _meta: {
          tables: {},
          columns: {}
        },
        internal
      };
    };
    fromDatabase3 = async (db, inputSchema, tablesFilter = (table6) => true, progressCallback) => {
      const result = {};
      const internals = { tables: {}, indexes: {} };
      const columns = await db.query(`select * from information_schema.columns
	where table_schema = '${inputSchema}' and table_name != '__drizzle_migrations'
	order by table_name, ordinal_position;`);
      const response = columns;
      const schemas = [];
      let columnsCount = 0;
      let tablesCount = /* @__PURE__ */ new Set();
      let indexesCount = 0;
      let foreignKeysCount = 0;
      let checksCount = 0;
      let viewsCount = 0;
      const idxs = await db.query(
        `select * from INFORMATION_SCHEMA.STATISTICS
	WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = '${inputSchema}' and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';`
      );
      const idxRows = idxs;
      for (const column6 of response) {
        if (!tablesFilter(column6["TABLE_NAME"])) continue;
        columnsCount += 1;
        if (progressCallback) {
          progressCallback("columns", columnsCount, "fetching");
        }
        const schema6 = column6["TABLE_SCHEMA"];
        const tableName = column6["TABLE_NAME"];
        tablesCount.add(`${schema6}.${tableName}`);
        if (progressCallback) {
          progressCallback("columns", tablesCount.size, "fetching");
        }
        const columnName = column6["COLUMN_NAME"];
        const isNullable = column6["IS_NULLABLE"] === "YES";
        const dataType = column6["DATA_TYPE"];
        const columnType = column6["COLUMN_TYPE"];
        const isPrimary = column6["COLUMN_KEY"] === "PRI";
        const columnDefault = column6["COLUMN_DEFAULT"];
        const collation = column6["CHARACTER_SET_NAME"];
        const geenratedExpression = column6["GENERATION_EXPRESSION"];
        let columnExtra = column6["EXTRA"];
        let isAutoincrement = false;
        let isDefaultAnExpression = false;
        if (typeof column6["EXTRA"] !== "undefined") {
          columnExtra = column6["EXTRA"];
          isAutoincrement = column6["EXTRA"] === "auto_increment";
          isDefaultAnExpression = column6["EXTRA"].includes("DEFAULT_GENERATED");
        }
        if (schema6 !== inputSchema) {
          schemas.push(schema6);
        }
        const table6 = result[tableName];
        let changedType = columnType;
        if (columnType === "bigint unsigned" && !isNullable && isAutoincrement) {
          const uniqueIdx = idxRows.filter(
            (it) => it["COLUMN_NAME"] === columnName && it["TABLE_NAME"] === tableName && it["NON_UNIQUE"] === 0
          );
          if (uniqueIdx && uniqueIdx.length === 1) {
            changedType = columnType.replace("bigint unsigned", "serial");
          }
        }
        if (columnType.includes("decimal(10,0)")) {
          changedType = columnType.replace("decimal(10,0)", "decimal");
        }
        let onUpdate = void 0;
        if (columnType.startsWith("timestamp") && typeof columnExtra !== "undefined" && columnExtra.includes("on update CURRENT_TIMESTAMP")) {
          onUpdate = true;
        }
        const newColumn = {
          default: columnDefault === null || columnDefault === void 0 ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) && !["decimal", "char", "varchar"].some((type) => columnType.startsWith(type)) ? Number(columnDefault) : isDefaultAnExpression ? clearDefaults(columnDefault, collation) : `'${escapeSingleQuotes(columnDefault)}'`,
          autoincrement: isAutoincrement,
          name: columnName,
          type: changedType,
          primaryKey: false,
          notNull: !isNullable,
          onUpdate,
          generated: geenratedExpression ? {
            as: geenratedExpression,
            type: columnExtra === "VIRTUAL GENERATED" ? "virtual" : "stored"
          } : void 0
        };
        if (isDefaultAnExpression) {
          if (typeof internals.tables[tableName] === "undefined") {
            internals.tables[tableName] = {
              columns: {
                [columnName]: {
                  isDefaultAnExpression: true
                }
              }
            };
          } else {
            if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
              internals.tables[tableName].columns[columnName] = {
                isDefaultAnExpression: true
              };
            } else {
              internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
            }
          }
        }
        if (!table6) {
          result[tableName] = {
            name: tableName,
            columns: {
              [columnName]: newColumn
            },
            compositePrimaryKeys: {},
            indexes: {},
            foreignKeys: {},
            uniqueConstraints: {},
            checkConstraint: {}
          };
        } else {
          result[tableName].columns[columnName] = newColumn;
        }
      }
      const tablePks = await db.query(
        `SELECT table_name, column_name, ordinal_position
  FROM information_schema.table_constraints t
  LEFT JOIN information_schema.key_column_usage k
  USING(constraint_name,table_schema,table_name)
  WHERE t.constraint_type='PRIMARY KEY'
      and table_name != '__drizzle_migrations'
      AND t.table_schema = '${inputSchema}'
      ORDER BY ordinal_position`
      );
      const tableToPk = {};
      const tableToPkRows = tablePks;
      for (const tableToPkRow of tableToPkRows) {
        const tableName = tableToPkRow["TABLE_NAME"];
        const columnName = tableToPkRow["COLUMN_NAME"];
        const position = tableToPkRow["ordinal_position"];
        if (typeof result[tableName] === "undefined") {
          continue;
        }
        if (typeof tableToPk[tableName] === "undefined") {
          tableToPk[tableName] = [columnName];
        } else {
          tableToPk[tableName].push(columnName);
        }
      }
      for (const [key, value] of Object.entries(tableToPk)) {
        result[key].compositePrimaryKeys = {
          [`${key}_${value.join("_")}`]: {
            name: `${key}_${value.join("_")}`,
            columns: value
          }
        };
      }
      if (progressCallback) {
        progressCallback("columns", columnsCount, "done");
        progressCallback("tables", tablesCount.size, "done");
      }
      try {
        const fks = await db.query(
          `SELECT 
      kcu.TABLE_SCHEMA,
      kcu.TABLE_NAME,
      kcu.CONSTRAINT_NAME,
      kcu.COLUMN_NAME,
      kcu.REFERENCED_TABLE_SCHEMA,
      kcu.REFERENCED_TABLE_NAME,
      kcu.REFERENCED_COLUMN_NAME,
      rc.UPDATE_RULE,
      rc.DELETE_RULE
  FROM 
      INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
  LEFT JOIN 
      information_schema.referential_constraints rc 
      ON kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
  WHERE kcu.TABLE_SCHEMA = '${inputSchema}' AND kcu.CONSTRAINT_NAME != 'PRIMARY' 
      AND kcu.REFERENCED_TABLE_NAME IS NOT NULL;`
        );
        const fkRows = fks;
        for (const fkRow of fkRows) {
          foreignKeysCount += 1;
          if (progressCallback) {
            progressCallback("fks", foreignKeysCount, "fetching");
          }
          const tableSchema = fkRow["TABLE_SCHEMA"];
          const tableName = fkRow["TABLE_NAME"];
          const constraintName = fkRow["CONSTRAINT_NAME"];
          const columnName = fkRow["COLUMN_NAME"];
          const refTableSchema = fkRow["REFERENCED_TABLE_SCHEMA"];
          const refTableName = fkRow["REFERENCED_TABLE_NAME"];
          const refColumnName = fkRow["REFERENCED_COLUMN_NAME"];
          const updateRule = fkRow["UPDATE_RULE"];
          const deleteRule = fkRow["DELETE_RULE"];
          const tableInResult = result[tableName];
          if (typeof tableInResult === "undefined") continue;
          if (typeof tableInResult.foreignKeys[constraintName] !== "undefined") {
            tableInResult.foreignKeys[constraintName].columnsFrom.push(columnName);
            tableInResult.foreignKeys[constraintName].columnsTo.push(
              refColumnName
            );
          } else {
            tableInResult.foreignKeys[constraintName] = {
              name: constraintName,
              tableFrom: tableName,
              tableTo: refTableName,
              columnsFrom: [columnName],
              columnsTo: [refColumnName],
              onDelete: deleteRule?.toLowerCase(),
              onUpdate: updateRule?.toLowerCase()
            };
          }
          tableInResult.foreignKeys[constraintName].columnsFrom = [
            ...new Set(tableInResult.foreignKeys[constraintName].columnsFrom)
          ];
          tableInResult.foreignKeys[constraintName].columnsTo = [
            ...new Set(tableInResult.foreignKeys[constraintName].columnsTo)
          ];
        }
      } catch (e6) {
      }
      if (progressCallback) {
        progressCallback("fks", foreignKeysCount, "done");
      }
      for (const idxRow of idxRows) {
        const tableSchema = idxRow["TABLE_SCHEMA"];
        const tableName = idxRow["TABLE_NAME"];
        const constraintName = idxRow["INDEX_NAME"];
        const columnName = idxRow["COLUMN_NAME"];
        const isUnique = idxRow["NON_UNIQUE"] === 0;
        const tableInResult = result[tableName];
        if (typeof tableInResult === "undefined") continue;
        indexesCount += 1;
        if (progressCallback) {
          progressCallback("indexes", indexesCount, "fetching");
        }
        if (isUnique) {
          if (typeof tableInResult.uniqueConstraints[constraintName] !== "undefined") {
            tableInResult.uniqueConstraints[constraintName].columns.push(
              columnName
            );
          } else {
            tableInResult.uniqueConstraints[constraintName] = {
              name: constraintName,
              columns: [columnName]
            };
          }
        } else {
          if (typeof tableInResult.foreignKeys[constraintName] === "undefined") {
            if (typeof tableInResult.indexes[constraintName] !== "undefined") {
              tableInResult.indexes[constraintName].columns.push(columnName);
            } else {
              tableInResult.indexes[constraintName] = {
                name: constraintName,
                columns: [columnName],
                isUnique
              };
            }
          }
        }
      }
      const views = await db.query(
        `select * from INFORMATION_SCHEMA.VIEWS WHERE table_schema = '${inputSchema}';`
      );
      const resultViews = {};
      viewsCount = views.length;
      if (progressCallback) {
        progressCallback("views", viewsCount, "fetching");
      }
      for await (const view5 of views) {
        const viewName = view5["TABLE_NAME"];
        const definition = view5["VIEW_DEFINITION"];
        const withCheckOption = view5["CHECK_OPTION"] === "NONE" ? void 0 : view5["CHECK_OPTION"].toLowerCase();
        const sqlSecurity = view5["SECURITY_TYPE"].toLowerCase();
        const [createSqlStatement] = await db.query(`SHOW CREATE VIEW \`${viewName}\`;`);
        const algorithmMatch = createSqlStatement["Create View"].match(/ALGORITHM=([^ ]+)/);
        const algorithm = algorithmMatch ? algorithmMatch[1].toLowerCase() : void 0;
        const columns2 = result[viewName].columns;
        delete result[viewName];
        resultViews[viewName] = {
          columns: columns2,
          isExisting: false,
          name: viewName,
          algorithm,
          definition,
          sqlSecurity,
          withCheckOption
        };
      }
      if (progressCallback) {
        progressCallback("indexes", indexesCount, "done");
        progressCallback("enums", 0, "done");
        progressCallback("views", viewsCount, "done");
      }
      const checkConstraints = await db.query(
        `SELECT 
    tc.table_name, 
    tc.constraint_name, 
    cc.check_clause
FROM 
    information_schema.table_constraints tc
JOIN 
    information_schema.check_constraints cc 
    ON tc.constraint_name = cc.constraint_name
WHERE 
    tc.constraint_schema = '${inputSchema}'
AND 
    tc.constraint_type = 'CHECK';`
      );
      checksCount += checkConstraints.length;
      if (progressCallback) {
        progressCallback("checks", checksCount, "fetching");
      }
      for (const checkConstraintRow of checkConstraints) {
        const constraintName = checkConstraintRow["CONSTRAINT_NAME"];
        const constraintValue = checkConstraintRow["CHECK_CLAUSE"];
        const tableName = checkConstraintRow["TABLE_NAME"];
        const tableInResult = result[tableName];
        tableInResult.checkConstraint[constraintName] = {
          name: constraintName,
          value: constraintValue
        };
      }
      if (progressCallback) {
        progressCallback("checks", checksCount, "done");
      }
      return {
        version: "5",
        dialect: "mysql",
        tables: result,
        views: resultViews,
        _meta: {
          tables: {},
          columns: {}
        },
        internal: internals
      };
    };
  }
});

// src/cli/validations/cli.ts
var cliConfigGenerate, pushParams, pullParams, configCheck, cliConfigCheck;
var init_cli = __esm({
  "src/cli/validations/cli.ts"() {
    "use strict";
    init_esm();
    init_schemaValidator();
    init_common();
    cliConfigGenerate = objectType({
      dialect: dialect4.optional(),
      schema: unionType([stringType(), stringType().array()]).optional(),
      out: stringType().optional().default("./drizzle"),
      config: stringType().optional(),
      name: stringType().optional(),
      prefix: prefix.optional(),
      breakpoints: booleanType().optional().default(true),
      custom: booleanType().optional().default(false)
    }).strict();
    pushParams = objectType({
      dialect: dialect4,
      casing: casingType.optional(),
      schema: unionType([stringType(), stringType().array()]),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]),
      extensionsFilters: literalType("postgis").array().optional(),
      verbose: booleanType().optional(),
      strict: booleanType().optional(),
      entities: objectType({
        roles: booleanType().or(objectType({
          provider: stringType().optional(),
          include: stringType().array().optional(),
          exclude: stringType().array().optional()
        })).optional().default(false)
      }).optional()
    }).passthrough();
    pullParams = objectType({
      config: stringType().optional(),
      dialect: dialect4,
      out: stringType().optional().default("drizzle"),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]),
      extensionsFilters: literalType("postgis").array().optional(),
      casing,
      breakpoints: booleanType().optional().default(true),
      migrations: objectType({
        prefix: prefix.optional().default("index")
      }).optional(),
      entities: objectType({
        roles: booleanType().or(objectType({
          provider: stringType().optional(),
          include: stringType().array().optional(),
          exclude: stringType().array().optional()
        })).optional().default(false)
      }).optional()
    }).passthrough();
    configCheck = objectType({
      dialect: dialect4.optional(),
      out: stringType().optional()
    });
    cliConfigCheck = intersectionType(
      objectType({
        config: stringType().optional()
      }),
      configCheck
    );
  }
});

// src/cli/validations/gel.ts
var gelCredentials;
var init_gel = __esm({
  "src/cli/validations/gel.ts"() {
    "use strict";
    init_esm();
    init_views();
    init_common();
    gelCredentials = unionType([
      objectType({
        driver: undefinedType(),
        host: stringType().min(1),
        port: coerce.number().min(1).optional(),
        user: stringType().min(1).optional(),
        password: stringType().min(1).optional(),
        database: stringType().min(1),
        tlsSecurity: unionType([
          literalType("insecure"),
          literalType("no_host_verification"),
          literalType("strict"),
          literalType("default")
        ]).optional()
      }).transform((o5) => {
        delete o5.driver;
        return o5;
      }),
      objectType({
        driver: undefinedType(),
        url: stringType().min(1),
        tlsSecurity: unionType([
          literalType("insecure"),
          literalType("no_host_verification"),
          literalType("strict"),
          literalType("default")
        ]).optional()
      }).transform((o5) => {
        delete o5.driver;
        return o5;
      }),
      objectType({
        driver: undefinedType()
      }).transform((o5) => {
        return void 0;
      })
    ]);
  }
});

// src/cli/validations/libsql.ts
var libSQLCredentials;
var init_libsql = __esm({
  "src/cli/validations/libsql.ts"() {
    "use strict";
    init_esm();
    init_views();
    init_common();
    libSQLCredentials = objectType({
      url: stringType().min(1),
      authToken: stringType().min(1).optional()
    });
  }
});

// src/cli/validations/mysql.ts
var mysqlCredentials;
var init_mysql = __esm({
  "src/cli/validations/mysql.ts"() {
    "use strict";
    init_esm();
    init_views();
    init_common();
    init_outputs();
    mysqlCredentials = unionType([
      objectType({
        host: stringType().min(1),
        port: coerce.number().min(1).optional(),
        user: stringType().min(1).optional(),
        password: stringType().min(1).optional(),
        database: stringType().min(1),
        ssl: unionType([
          stringType(),
          objectType({
            pfx: stringType().optional(),
            key: stringType().optional(),
            passphrase: stringType().optional(),
            cert: stringType().optional(),
            ca: unionType([stringType(), stringType().array()]).optional(),
            crl: unionType([stringType(), stringType().array()]).optional(),
            ciphers: stringType().optional(),
            rejectUnauthorized: booleanType().optional()
          })
        ]).optional()
      }),
      objectType({
        url: stringType().min(1)
      })
    ]);
  }
});

// src/cli/validations/postgres.ts
var postgresCredentials;
var init_postgres = __esm({
  "src/cli/validations/postgres.ts"() {
    "use strict";
    init_esm();
    init_views();
    init_common();
    postgresCredentials = unionType([
      objectType({
        driver: undefinedType(),
        host: stringType().min(1),
        port: coerce.number().min(1).optional(),
        user: stringType().min(1).optional(),
        password: stringType().min(1).optional(),
        database: stringType().min(1),
        ssl: unionType([
          literalType("require"),
          literalType("allow"),
          literalType("prefer"),
          literalType("verify-full"),
          booleanType(),
          objectType({}).passthrough()
        ]).optional()
      }).transform((o5) => {
        delete o5.driver;
        return o5;
      }),
      objectType({
        driver: undefinedType(),
        url: stringType().min(1)
      }).transform((o5) => {
        delete o5.driver;
        return o5;
      }),
      objectType({
        driver: literalType("aws-data-api"),
        database: stringType().min(1),
        secretArn: stringType().min(1),
        resourceArn: stringType().min(1)
      }),
      objectType({
        driver: literalType("pglite"),
        url: stringType().min(1)
      })
    ]);
  }
});

// src/cli/validations/singlestore.ts
var singlestoreCredentials;
var init_singlestore = __esm({
  "src/cli/validations/singlestore.ts"() {
    "use strict";
    init_esm();
    init_views();
    init_common();
    init_outputs();
    singlestoreCredentials = unionType([
      objectType({
        host: stringType().min(1),
        port: coerce.number().min(1).optional(),
        user: stringType().min(1).optional(),
        password: stringType().min(1).optional(),
        database: stringType().min(1),
        ssl: unionType([
          stringType(),
          objectType({
            pfx: stringType().optional(),
            key: stringType().optional(),
            passphrase: stringType().optional(),
            cert: stringType().optional(),
            ca: unionType([stringType(), stringType().array()]).optional(),
            crl: unionType([stringType(), stringType().array()]).optional(),
            ciphers: stringType().optional(),
            rejectUnauthorized: booleanType().optional()
          })
        ]).optional()
      }),
      objectType({
        url: stringType().min(1)
      })
    ]);
  }
});

// src/cli/validations/sqlite.ts
var sqliteCredentials;
var init_sqlite = __esm({
  "src/cli/validations/sqlite.ts"() {
    "use strict";
    init_global();
    init_esm();
    init_views();
    init_common();
    sqliteCredentials = unionType([
      objectType({
        driver: literalType("turso"),
        url: stringType().min(1),
        authToken: stringType().min(1).optional()
      }),
      objectType({
        driver: literalType("d1-http"),
        accountId: stringType().min(1),
        databaseId: stringType().min(1),
        token: stringType().min(1)
      }),
      objectType({
        driver: undefinedType(),
        url: stringType().min(1)
      }).transform((o5) => {
        delete o5.driver;
        return o5;
      })
    ]);
  }
});

// src/cli/validations/studio.ts
var credentials, studioCliParams, studioConfig;
var init_studio = __esm({
  "src/cli/validations/studio.ts"() {
    "use strict";
    init_esm();
    init_schemaValidator();
    init_common();
    init_mysql();
    init_postgres();
    init_sqlite();
    credentials = intersectionType(
      postgresCredentials,
      mysqlCredentials,
      sqliteCredentials
    );
    studioCliParams = objectType({
      port: coerce.number().optional().default(4983),
      host: stringType().optional().default("127.0.0.1"),
      config: stringType().optional()
    });
    studioConfig = objectType({
      dialect: dialect4,
      schema: unionType([stringType(), stringType().array()]).optional(),
      casing: casingType.optional()
    });
  }
});

// src/cli/commands/_es5.ts
var es5_exports = {};
__export(es5_exports, {
  default: () => es5_default
});
var _, es5_default;
var init_es5 = __esm({
  "src/cli/commands/_es5.ts"() {
    "use strict";
    _ = "";
    es5_default = _;
  }
});

// src/cli/commands/utils.ts
var import_hanji7, assertES5, safeRegister, migrateConfig;
var init_utils3 = __esm({
  "src/cli/commands/utils.ts"() {
    "use strict";
    import_hanji7 = __toESM(require_hanji());
    init_esm();
    init_getTablesFilterByExtensions();
    init_global();
    init_schemaValidator();
    init_serializer();
    init_cli();
    init_common();
    init_gel();
    init_libsql();
    init_mysql();
    init_outputs();
    init_postgres();
    init_singlestore();
    init_sqlite();
    init_studio();
    init_views();
    assertES5 = async (unregister) => {
      try {
        init_es5();
      } catch (e6) {
        if ("errors" in e6 && Array.isArray(e6.errors) && e6.errors.length > 0) {
          const es5Error = e6.errors.filter((it) => it.text?.includes(`("es5") is not supported yet`)).length > 0;
          if (es5Error) {
            console.log(
              error(
                `Please change compilerOptions.target from 'es5' to 'es6' or above in your tsconfig.json`
              )
            );
            process.exit(1);
          }
        }
        console.error(e6);
        process.exit(1);
      }
    };
    safeRegister = async () => {
      const { register } = require("esbuild-register/dist/node");
      let res;
      try {
        res = register({
          format: "cjs",
          loader: "ts"
        });
      } catch {
        res = {
          unregister: () => {
          }
        };
      }
      await assertES5(res.unregister);
      return res;
    };
    migrateConfig = objectType({
      dialect: dialect4,
      out: stringType().optional().default("drizzle"),
      migrations: configMigrations
    });
  }
});

// src/serializer/pgImports.ts
var import_drizzle_orm4, import_pg_core2, import_relations, prepareFromExports;
var init_pgImports = __esm({
  "src/serializer/pgImports.ts"() {
    "use strict";
    import_drizzle_orm4 = require("drizzle-orm");
    import_pg_core2 = require("drizzle-orm/pg-core");
    import_relations = require("drizzle-orm/relations");
    init_utils3();
    prepareFromExports = (exports2) => {
      const tables = [];
      const enums = [];
      const schemas = [];
      const sequences = [];
      const roles = [];
      const policies = [];
      const views = [];
      const matViews = [];
      const relations = [];
      const i0values = Object.values(exports2);
      i0values.forEach((t6) => {
        if ((0, import_pg_core2.isPgEnum)(t6)) {
          enums.push(t6);
          return;
        }
        if ((0, import_drizzle_orm4.is)(t6, import_pg_core2.PgTable)) {
          tables.push(t6);
        }
        if ((0, import_drizzle_orm4.is)(t6, import_pg_core2.PgSchema)) {
          schemas.push(t6);
        }
        if ((0, import_pg_core2.isPgView)(t6)) {
          views.push(t6);
        }
        if ((0, import_pg_core2.isPgMaterializedView)(t6)) {
          matViews.push(t6);
        }
        if ((0, import_pg_core2.isPgSequence)(t6)) {
          sequences.push(t6);
        }
        if ((0, import_drizzle_orm4.is)(t6, import_pg_core2.PgRole)) {
          roles.push(t6);
        }
        if ((0, import_drizzle_orm4.is)(t6, import_pg_core2.PgPolicy)) {
          policies.push(t6);
        }
        if ((0, import_drizzle_orm4.is)(t6, import_relations.Relations)) {
          relations.push(t6);
        }
      });
      return { tables, enums, schemas, sequences, views, matViews, roles, policies, relations };
    };
  }
});

// src/serializer/singlestoreSerializer.ts
function clearDefaults2(defaultValue, collate) {
  if (typeof collate === "undefined" || collate === null) {
    collate = `utf8mb4`;
  }
  let resultDefault = defaultValue;
  collate = `_${collate}`;
  if (defaultValue.startsWith(collate)) {
    resultDefault = resultDefault.substring(collate.length, defaultValue.length).replace(/\\/g, "");
    if (resultDefault.startsWith("'") && resultDefault.endsWith("'")) {
      return `('${resultDefault.substring(1, resultDefault.length - 1)}')`;
    } else {
      return `'${resultDefault}'`;
    }
  } else {
    return `(${resultDefault})`;
  }
}
var import_drizzle_orm5, import_singlestore_core, dialect5, generateSingleStoreSnapshot, fromDatabase4;
var init_singlestoreSerializer = __esm({
  "src/serializer/singlestoreSerializer.ts"() {
    "use strict";
    init_source();
    import_drizzle_orm5 = require("drizzle-orm");
    import_singlestore_core = require("drizzle-orm/singlestore-core");
    init_outputs();
    init_utils2();
    dialect5 = new import_singlestore_core.SingleStoreDialect();
    generateSingleStoreSnapshot = (tables, casing2) => {
      const dialect6 = new import_singlestore_core.SingleStoreDialect({ casing: casing2 });
      const result = {};
      const internal = { tables: {}, indexes: {} };
      for (const table6 of tables) {
        const {
          name: tableName,
          columns,
          indexes,
          schema: schema6,
          primaryKeys,
          uniqueConstraints
        } = (0, import_singlestore_core.getTableConfig)(table6);
        const columnsObject = {};
        const indexesObject = {};
        const primaryKeysObject = {};
        const uniqueConstraintObject = {};
        columns.forEach((column6) => {
          const notNull = column6.notNull;
          const sqlTypeLowered = column6.getSQLType().toLowerCase();
          const autoIncrement = typeof column6.autoIncrement === "undefined" ? false : column6.autoIncrement;
          const generated = column6.generated;
          const columnToSet = {
            name: column6.name,
            type: column6.getSQLType(),
            primaryKey: false,
            // If field is autoincrement it's notNull by default
            // notNull: autoIncrement ? true : notNull,
            notNull,
            autoincrement: autoIncrement,
            onUpdate: column6.hasOnUpdateNow,
            generated: generated ? {
              as: (0, import_drizzle_orm5.is)(generated.as, import_drizzle_orm5.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
              type: generated.mode ?? "stored"
            } : void 0
          };
          if (column6.primary) {
            primaryKeysObject[`${tableName}_${column6.name}`] = {
              name: `${tableName}_${column6.name}`,
              columns: [column6.name]
            };
          }
          if (column6.isUnique) {
            const existingUnique = uniqueConstraintObject[column6.uniqueName];
            if (typeof existingUnique !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
          The unique constraint ${source_default.underline.blue(
                  column6.uniqueName
                )} on the ${source_default.underline.blue(
                  column6.name
                )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`)}`
              );
              process.exit(1);
            }
            uniqueConstraintObject[column6.uniqueName] = {
              name: column6.uniqueName,
              columns: [columnToSet.name]
            };
          }
          if (column6.default !== void 0) {
            if ((0, import_drizzle_orm5.is)(column6.default, import_drizzle_orm5.SQL)) {
              columnToSet.default = sqlToStr(column6.default, casing2);
            } else {
              if (typeof column6.default === "string") {
                columnToSet.default = `'${column6.default}'`;
              } else {
                if (sqlTypeLowered === "json" || Array.isArray(column6.default)) {
                  columnToSet.default = `'${JSON.stringify(column6.default)}'`;
                } else if (column6.default instanceof Date) {
                  if (sqlTypeLowered === "date") {
                    columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`;
                  } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
                    columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                  }
                } else {
                  columnToSet.default = column6.default;
                }
              }
            }
          }
          columnsObject[column6.name] = columnToSet;
        });
        primaryKeys.map((pk) => {
          const columnNames = pk.columns.map((c5) => c5.name);
          primaryKeysObject[pk.getName()] = {
            name: pk.getName(),
            columns: columnNames
          };
          for (const column6 of pk.columns) {
            columnsObject[column6.name].notNull = true;
          }
        });
        uniqueConstraints?.map((unq) => {
          const columnNames = unq.columns.map((c5) => c5.name);
          const name = unq.name ?? (0, import_singlestore_core.uniqueKeyName)(table6, columnNames);
          const existingUnique = uniqueConstraintObject[name];
          if (typeof existingUnique !== "undefined") {
            console.log(
              `
${withStyle.errorWarning(
                `We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
The unique constraint ${source_default.underline.blue(
                  name
                )} on the ${source_default.underline.blue(
                  columnNames.join(",")
                )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`
              )}`
            );
            process.exit(1);
          }
          uniqueConstraintObject[name] = {
            name: unq.name,
            columns: columnNames
          };
        });
        indexes.forEach((value) => {
          const columns2 = value.config.columns;
          const name = value.config.name;
          let indexColumns = columns2.map((it) => {
            if ((0, import_drizzle_orm5.is)(it, import_drizzle_orm5.SQL)) {
              const sql = dialect6.sqlToQuery(it, "indexes").sql;
              if (typeof internal.indexes[name] === "undefined") {
                internal.indexes[name] = {
                  columns: {
                    [sql]: {
                      isExpression: true
                    }
                  }
                };
              } else {
                if (typeof internal.indexes[name]?.columns[sql] === "undefined") {
                  internal.indexes[name].columns[sql] = {
                    isExpression: true
                  };
                } else {
                  internal.indexes[name].columns[sql].isExpression = true;
                }
              }
              return sql;
            } else {
              return `${it.name}`;
            }
          });
          if (value.config.unique) {
            if (typeof uniqueConstraintObject[name] !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(
                  `We've found duplicated unique constraint names in ${source_default.underline.blue(
                    tableName
                  )} table. 
The unique index ${source_default.underline.blue(
                    name
                  )} on the ${source_default.underline.blue(
                    indexColumns.join(",")
                  )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                    uniqueConstraintObject[name].columns.join(",")
                  )} columns
`
                )}`
              );
              process.exit(1);
            }
          }
          indexesObject[name] = {
            name,
            columns: indexColumns,
            isUnique: value.config.unique ?? false,
            using: value.config.using,
            algorithm: value.config.algorithm,
            lock: value.config.lock
          };
        });
        if (!schema6) {
          result[tableName] = {
            name: tableName,
            columns: columnsObject,
            indexes: indexesObject,
            compositePrimaryKeys: primaryKeysObject,
            uniqueConstraints: uniqueConstraintObject
          };
        }
      }
      return {
        version: "1",
        dialect: "singlestore",
        tables: result,
        /* views: resultViews, */
        _meta: {
          tables: {},
          columns: {}
        },
        internal
      };
    };
    fromDatabase4 = async (db, inputSchema, tablesFilter = (table6) => true, progressCallback) => {
      const result = {};
      const internals = { tables: {}, indexes: {} };
      const columns = await db.query(`select * from information_schema.columns
	where table_schema = '${inputSchema}' and table_name != '__drizzle_migrations'
	order by table_name, ordinal_position;`);
      const response = columns;
      const schemas = [];
      let columnsCount = 0;
      let tablesCount = /* @__PURE__ */ new Set();
      let indexesCount = 0;
      const idxs = await db.query(
        `select * from INFORMATION_SCHEMA.STATISTICS
	WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = '${inputSchema}' and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';`
      );
      const idxRows = idxs;
      for (const column6 of response) {
        if (!tablesFilter(column6["TABLE_NAME"])) continue;
        columnsCount += 1;
        if (progressCallback) {
          progressCallback("columns", columnsCount, "fetching");
        }
        const schema6 = column6["TABLE_SCHEMA"];
        const tableName = column6["TABLE_NAME"];
        tablesCount.add(`${schema6}.${tableName}`);
        if (progressCallback) {
          progressCallback("columns", tablesCount.size, "fetching");
        }
        const columnName = column6["COLUMN_NAME"];
        const isNullable = column6["IS_NULLABLE"] === "YES";
        const dataType = column6["DATA_TYPE"];
        const columnType = column6["COLUMN_TYPE"];
        const isPrimary = column6["COLUMN_KEY"] === "PRI";
        let columnDefault = column6["COLUMN_DEFAULT"];
        const collation = column6["CHARACTER_SET_NAME"];
        const geenratedExpression = column6["GENERATION_EXPRESSION"];
        let columnExtra = column6["EXTRA"];
        let isAutoincrement = false;
        let isDefaultAnExpression = false;
        if (typeof column6["EXTRA"] !== "undefined") {
          columnExtra = column6["EXTRA"];
          isAutoincrement = column6["EXTRA"] === "auto_increment";
          isDefaultAnExpression = column6["EXTRA"].includes("DEFAULT_GENERATED");
        }
        if (schema6 !== inputSchema) {
          schemas.push(schema6);
        }
        const table6 = result[tableName];
        let changedType = columnType;
        if (columnType === "bigint unsigned" && !isNullable && isAutoincrement) {
          const uniqueIdx = idxRows.filter(
            (it) => it["COLUMN_NAME"] === columnName && it["TABLE_NAME"] === tableName && it["NON_UNIQUE"] === 0
          );
          if (uniqueIdx && uniqueIdx.length === 1) {
            changedType = columnType.replace("bigint unsigned", "serial");
          }
        }
        if (columnType.startsWith("bigint(") || columnType.startsWith("tinyint(") || columnType.startsWith("date(") || columnType.startsWith("int(") || columnType.startsWith("mediumint(") || columnType.startsWith("smallint(") || columnType.startsWith("text(") || columnType.startsWith("time(") || columnType.startsWith("year(")) {
          changedType = columnType.replace(/\(\s*[^)]*\)$/, "");
        }
        if (columnType.includes("decimal(10,0)")) {
          changedType = columnType.replace("decimal(10,0)", "decimal");
        }
        if (columnDefault?.endsWith(".")) {
          columnDefault = columnDefault.slice(0, -1);
        }
        let onUpdate = void 0;
        if (columnType.startsWith("timestamp") && typeof columnExtra !== "undefined" && columnExtra.includes("on update CURRENT_TIMESTAMP")) {
          onUpdate = true;
        }
        const newColumn = {
          default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) && !["decimal", "char", "varchar"].some((type) => columnType.startsWith(type)) ? Number(columnDefault) : isDefaultAnExpression ? clearDefaults2(columnDefault, collation) : columnDefault.startsWith("CURRENT_TIMESTAMP") ? "CURRENT_TIMESTAMP" : `'${columnDefault}'`,
          autoincrement: isAutoincrement,
          name: columnName,
          type: changedType,
          primaryKey: false,
          notNull: !isNullable,
          onUpdate,
          generated: geenratedExpression ? {
            as: geenratedExpression,
            type: columnExtra === "VIRTUAL GENERATED" ? "virtual" : "stored"
          } : void 0
        };
        if (isDefaultAnExpression) {
          if (typeof internals.tables[tableName] === "undefined") {
            internals.tables[tableName] = {
              columns: {
                [columnName]: {
                  isDefaultAnExpression: true
                }
              }
            };
          } else {
            if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
              internals.tables[tableName].columns[columnName] = {
                isDefaultAnExpression: true
              };
            } else {
              internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
            }
          }
        }
        if (!table6) {
          result[tableName] = {
            name: tableName,
            columns: {
              [columnName]: newColumn
            },
            compositePrimaryKeys: {},
            indexes: {},
            uniqueConstraints: {}
          };
        } else {
          result[tableName].columns[columnName] = newColumn;
        }
      }
      const tablePks = await db.query(
        `SELECT table_name, column_name, ordinal_position
  FROM information_schema.table_constraints t
  LEFT JOIN information_schema.key_column_usage k
  USING(constraint_name,table_schema,table_name)
  WHERE t.constraint_type='UNIQUE'
      and table_name != '__drizzle_migrations'
      AND t.table_schema = '${inputSchema}'
      ORDER BY ordinal_position`
      );
      const tableToPk = {};
      const tableToPkRows = tablePks;
      for (const tableToPkRow of tableToPkRows) {
        const tableName = tableToPkRow["table_name"];
        const columnName = tableToPkRow["column_name"];
        const position = tableToPkRow["ordinal_position"];
        if (typeof result[tableName] === "undefined") {
          continue;
        }
        if (typeof tableToPk[tableName] === "undefined") {
          tableToPk[tableName] = [columnName];
        } else {
          tableToPk[tableName].push(columnName);
        }
      }
      for (const [key, value] of Object.entries(tableToPk)) {
        result[key].compositePrimaryKeys = {
          [`${key}_${value.join("_")}`]: {
            name: `${key}_${value.join("_")}`,
            columns: value
          }
        };
      }
      if (progressCallback) {
        progressCallback("columns", columnsCount, "done");
        progressCallback("tables", tablesCount.size, "done");
      }
      for (const idxRow of idxRows) {
        const tableSchema = idxRow["TABLE_SCHEMA"];
        const tableName = idxRow["TABLE_NAME"];
        const constraintName = idxRow["INDEX_NAME"];
        const columnName = idxRow["COLUMN_NAME"];
        const isUnique = idxRow["NON_UNIQUE"] === 0;
        const tableInResult = result[tableName];
        if (typeof tableInResult === "undefined") continue;
        indexesCount += 1;
        if (progressCallback) {
          progressCallback("indexes", indexesCount, "fetching");
        }
        if (isUnique) {
          if (typeof tableInResult.uniqueConstraints[constraintName] !== "undefined") {
            tableInResult.uniqueConstraints[constraintName].columns.push(
              columnName
            );
          } else {
            tableInResult.uniqueConstraints[constraintName] = {
              name: constraintName,
              columns: [columnName]
            };
          }
        }
      }
      if (progressCallback) {
        progressCallback("indexes", indexesCount, "done");
        progressCallback("enums", 0, "done");
      }
      return {
        version: "1",
        dialect: "singlestore",
        tables: result,
        /* views: resultViews, */
        _meta: {
          tables: {},
          columns: {}
        },
        internal: internals
      };
    };
  }
});

// ../node_modules/.pnpm/@hono+node-server@1.14.3_hono@4.7.10/node_modules/@hono/node-server/dist/index.mjs
function writeFromReadableStream(stream, writable) {
  if (stream.locked) {
    throw new TypeError("ReadableStream is locked.");
  } else if (writable.destroyed) {
    stream.cancel();
    return;
  }
  const reader = stream.getReader();
  writable.on("close", cancel);
  writable.on("error", cancel);
  reader.read().then(flow, cancel);
  return reader.closed.finally(() => {
    writable.off("close", cancel);
    writable.off("error", cancel);
  });
  function cancel(error2) {
    reader.cancel(error2).catch(() => {
    });
    if (error2) {
      writable.destroy(error2);
    }
  }
  function onDrain() {
    reader.read().then(flow, cancel);
  }
  function flow({ done, value }) {
    try {
      if (done) {
        writable.end();
      } else if (!writable.write(value)) {
        writable.once("drain", onDrain);
      } else {
        return reader.read().then(flow, cancel);
      }
    } catch (e6) {
      cancel(e6);
    }
  }
}
var import_http, import_http2, import_stream, import_crypto, RequestError, toRequestError, GlobalRequest, Request2, newRequestFromIncoming, getRequestCache, requestCache, incomingKey, urlKey, abortControllerKey, getAbortController, requestPrototype, newRequest, responseCache, getResponseCache, cacheKey, GlobalResponse, _body, _init, _a, Response2, buildOutgoingHttpHeaders, X_ALREADY_SENT, webFetch, regBuffer, regContentType, handleRequestError, handleFetchError, handleResponseError, responseViaCache, responseViaResponseObject, getRequestListener, createAdaptorServer, serve;
var init_dist = __esm({
  "../node_modules/.pnpm/@hono+node-server@1.14.3_hono@4.7.10/node_modules/@hono/node-server/dist/index.mjs"() {
    "use strict";
    import_http = require("http");
    import_http2 = require("http2");
    import_stream = require("stream");
    import_crypto = __toESM(require("crypto"), 1);
    RequestError = class extends Error {
      constructor(message, options) {
        super(message, options);
        this.name = "RequestError";
      }
    };
    toRequestError = (e6) => {
      if (e6 instanceof RequestError) {
        return e6;
      }
      return new RequestError(e6.message, { cause: e6 });
    };
    GlobalRequest = global.Request;
    Request2 = class extends GlobalRequest {
      constructor(input, options) {
        if (typeof input === "object" && getRequestCache in input) {
          input = input[getRequestCache]();
        }
        if (typeof options?.body?.getReader !== "undefined") {
          ;
          options.duplex ??= "half";
        }
        super(input, options);
      }
    };
    newRequestFromIncoming = (method, url, incoming, abortController) => {
      const headerRecord = [];
      const rawHeaders = incoming.rawHeaders;
      for (let i6 = 0; i6 < rawHeaders.length; i6 += 2) {
        const { [i6]: key, [i6 + 1]: value } = rawHeaders;
        if (key.charCodeAt(0) !== /*:*/
        58) {
          headerRecord.push([key, value]);
        }
      }
      const init2 = {
        method,
        headers: headerRecord,
        signal: abortController.signal
      };
      if (method === "TRACE") {
        init2.method = "GET";
        const req = new Request2(url, init2);
        Object.defineProperty(req, "method", {
          get() {
            return "TRACE";
          }
        });
        return req;
      }
      if (!(method === "GET" || method === "HEAD")) {
        if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
          init2.body = new ReadableStream({
            start(controller) {
              controller.enqueue(incoming.rawBody);
              controller.close();
            }
          });
        } else {
          init2.body = import_stream.Readable.toWeb(incoming);
        }
      }
      return new Request2(url, init2);
    };
    getRequestCache = Symbol("getRequestCache");
    requestCache = Symbol("requestCache");
    incomingKey = Symbol("incomingKey");
    urlKey = Symbol("urlKey");
    abortControllerKey = Symbol("abortControllerKey");
    getAbortController = Symbol("getAbortController");
    requestPrototype = {
      get method() {
        return this[incomingKey].method || "GET";
      },
      get url() {
        return this[urlKey];
      },
      [getAbortController]() {
        this[getRequestCache]();
        return this[abortControllerKey];
      },
      [getRequestCache]() {
        this[abortControllerKey] ||= new AbortController();
        return this[requestCache] ||= newRequestFromIncoming(
          this.method,
          this[urlKey],
          this[incomingKey],
          this[abortControllerKey]
        );
      }
    };
    [
      "body",
      "bodyUsed",
      "cache",
      "credentials",
      "destination",
      "headers",
      "integrity",
      "mode",
      "redirect",
      "referrer",
      "referrerPolicy",
      "signal",
      "keepalive"
    ].forEach((k5) => {
      Object.defineProperty(requestPrototype, k5, {
        get() {
          return this[getRequestCache]()[k5];
        }
      });
    });
    ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k5) => {
      Object.defineProperty(requestPrototype, k5, {
        value: function() {
          return this[getRequestCache]()[k5]();
        }
      });
    });
    Object.setPrototypeOf(requestPrototype, Request2.prototype);
    newRequest = (incoming, defaultHostname) => {
      const req = Object.create(requestPrototype);
      req[incomingKey] = incoming;
      const incomingUrl = incoming.url || "";
      if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
      (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
        if (incoming instanceof import_http2.Http2ServerRequest) {
          throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
        }
        try {
          const url2 = new URL(incomingUrl);
          req[urlKey] = url2.href;
        } catch (e6) {
          throw new RequestError("Invalid absolute URL", { cause: e6 });
        }
        return req;
      }
      const host = (incoming instanceof import_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
      if (!host) {
        throw new RequestError("Missing host header");
      }
      let scheme;
      if (incoming instanceof import_http2.Http2ServerRequest) {
        scheme = incoming.scheme;
        if (!(scheme === "http" || scheme === "https")) {
          throw new RequestError("Unsupported scheme");
        }
      } else {
        scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
      }
      const url = new URL(`${scheme}://${host}${incomingUrl}`);
      if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
        throw new RequestError("Invalid host header");
      }
      req[urlKey] = url.href;
      return req;
    };
    responseCache = Symbol("responseCache");
    getResponseCache = Symbol("getResponseCache");
    cacheKey = Symbol("cache");
    GlobalResponse = global.Response;
    Response2 = (_a = class {
      constructor(body, init2) {
        __privateAdd(this, _body);
        __privateAdd(this, _init);
        let headers;
        __privateSet(this, _body, body);
        if (init2 instanceof _a) {
          const cachedGlobalResponse = init2[responseCache];
          if (cachedGlobalResponse) {
            __privateSet(this, _init, cachedGlobalResponse);
            this[getResponseCache]();
            return;
          } else {
            __privateSet(this, _init, __privateGet(init2, _init));
            headers = new Headers(__privateGet(init2, _init).headers);
          }
        } else {
          __privateSet(this, _init, init2);
        }
        if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
          headers ||= init2?.headers || { "content-type": "text/plain; charset=UTF-8" };
          this[cacheKey] = [init2?.status || 200, body, headers];
        }
      }
      [getResponseCache]() {
        delete this[cacheKey];
        return this[responseCache] ||= new GlobalResponse(__privateGet(this, _body), __privateGet(this, _init));
      }
      get headers() {
        const cache5 = this[cacheKey];
        if (cache5) {
          if (!(cache5[2] instanceof Headers)) {
            cache5[2] = new Headers(cache5[2]);
          }
          return cache5[2];
        }
        return this[getResponseCache]().headers;
      }
      get status() {
        return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
      }
      get ok() {
        const status = this.status;
        return status >= 200 && status < 300;
      }
    }, _body = new WeakMap(), _init = new WeakMap(), _a);
    ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k5) => {
      Object.defineProperty(Response2.prototype, k5, {
        get() {
          return this[getResponseCache]()[k5];
        }
      });
    });
    ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k5) => {
      Object.defineProperty(Response2.prototype, k5, {
        value: function() {
          return this[getResponseCache]()[k5]();
        }
      });
    });
    Object.setPrototypeOf(Response2, GlobalResponse);
    Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
    buildOutgoingHttpHeaders = (headers) => {
      const res = {};
      if (!(headers instanceof Headers)) {
        headers = new Headers(headers ?? void 0);
      }
      const cookies = [];
      for (const [k5, v6] of headers) {
        if (k5 === "set-cookie") {
          cookies.push(v6);
        } else {
          res[k5] = v6;
        }
      }
      if (cookies.length > 0) {
        res["set-cookie"] = cookies;
      }
      res["content-type"] ??= "text/plain; charset=UTF-8";
      return res;
    };
    X_ALREADY_SENT = "x-hono-already-sent";
    webFetch = global.fetch;
    if (typeof global.crypto === "undefined") {
      global.crypto = import_crypto.default;
    }
    global.fetch = (info2, init2) => {
      init2 = {
        // Disable compression handling so people can return the result of a fetch
        // directly in the loader without messing with the Content-Encoding header.
        compress: false,
        ...init2
      };
      return webFetch(info2, init2);
    };
    regBuffer = /^no$/i;
    regContentType = /^(application\/json\b|text\/(?!event-stream\b))/i;
    handleRequestError = () => new Response(null, {
      status: 400
    });
    handleFetchError = (e6) => new Response(null, {
      status: e6 instanceof Error && (e6.name === "TimeoutError" || e6.constructor.name === "TimeoutError") ? 504 : 500
    });
    handleResponseError = (e6, outgoing) => {
      const err2 = e6 instanceof Error ? e6 : new Error("unknown error", { cause: e6 });
      if (err2.code === "ERR_STREAM_PREMATURE_CLOSE") {
        console.info("The user aborted a request.");
      } else {
        console.error(e6);
        if (!outgoing.headersSent) {
          outgoing.writeHead(500, { "Content-Type": "text/plain" });
        }
        outgoing.end(`Error: ${err2.message}`);
        outgoing.destroy(err2);
      }
    };
    responseViaCache = async (res, outgoing) => {
      let [status, body, header] = res[cacheKey];
      if (header instanceof Headers) {
        header = buildOutgoingHttpHeaders(header);
      }
      if (typeof body === "string") {
        header["Content-Length"] = Buffer.byteLength(body);
      } else if (body instanceof Uint8Array) {
        header["Content-Length"] = body.byteLength;
      } else if (body instanceof Blob) {
        header["Content-Length"] = body.size;
      }
      outgoing.writeHead(status, header);
      if (typeof body === "string" || body instanceof Uint8Array) {
        outgoing.end(body);
      } else if (body instanceof Blob) {
        outgoing.end(new Uint8Array(await body.arrayBuffer()));
      } else {
        return writeFromReadableStream(body, outgoing)?.catch(
          (e6) => handleResponseError(e6, outgoing)
        );
      }
    };
    responseViaResponseObject = async (res, outgoing, options = {}) => {
      if (res instanceof Promise) {
        if (options.errorHandler) {
          try {
            res = await res;
          } catch (err2) {
            const errRes = await options.errorHandler(err2);
            if (!errRes) {
              return;
            }
            res = errRes;
          }
        } else {
          res = await res.catch(handleFetchError);
        }
      }
      if (cacheKey in res) {
        return responseViaCache(res, outgoing);
      }
      const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
      if (res.body) {
        const {
          "transfer-encoding": transferEncoding,
          "content-encoding": contentEncoding,
          "content-length": contentLength,
          "x-accel-buffering": accelBuffering,
          "content-type": contentType
        } = resHeaderRecord;
        if (transferEncoding || contentEncoding || contentLength || // nginx buffering variant
        accelBuffering && regBuffer.test(accelBuffering) || !regContentType.test(contentType)) {
          outgoing.writeHead(res.status, resHeaderRecord);
          await writeFromReadableStream(res.body, outgoing);
        } else {
          const buffer = await res.arrayBuffer();
          resHeaderRecord["content-length"] = buffer.byteLength;
          outgoing.writeHead(res.status, resHeaderRecord);
          outgoing.end(new Uint8Array(buffer));
        }
      } else if (resHeaderRecord[X_ALREADY_SENT]) {
      } else {
        outgoing.writeHead(res.status, resHeaderRecord);
        outgoing.end();
      }
    };
    getRequestListener = (fetchCallback, options = {}) => {
      if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
        Object.defineProperty(global, "Request", {
          value: Request2
        });
        Object.defineProperty(global, "Response", {
          value: Response2
        });
      }
      return async (incoming, outgoing) => {
        let res, req;
        try {
          req = newRequest(incoming, options.hostname);
          outgoing.on("close", () => {
            const abortController = req[abortControllerKey];
            if (!abortController) {
              return;
            }
            if (incoming.errored) {
              req[abortControllerKey].abort(incoming.errored.toString());
            } else if (!outgoing.writableFinished) {
              req[abortControllerKey].abort("Client connection prematurely closed.");
            }
          });
          res = fetchCallback(req, { incoming, outgoing });
          if (cacheKey in res) {
            return responseViaCache(res, outgoing);
          }
        } catch (e6) {
          if (!res) {
            if (options.errorHandler) {
              res = await options.errorHandler(req ? e6 : toRequestError(e6));
              if (!res) {
                return;
              }
            } else if (!req) {
              res = handleRequestError();
            } else {
              res = handleFetchError(e6);
            }
          } else {
            return handleResponseError(e6, outgoing);
          }
        }
        try {
          return await responseViaResponseObject(res, outgoing, options);
        } catch (e6) {
          return handleResponseError(e6, outgoing);
        }
      };
    };
    createAdaptorServer = (options) => {
      const fetchCallback = options.fetch;
      const requestListener = getRequestListener(fetchCallback, {
        hostname: options.hostname,
        overrideGlobalObjects: options.overrideGlobalObjects
      });
      const createServer2 = options.createServer || import_http.createServer;
      const server = createServer2(options.serverOptions || {}, requestListener);
      return server;
    };
    serve = (options, listeningListener) => {
      const server = createAdaptorServer(options);
      server.listen(options?.port ?? 3e3, options.hostname, () => {
        const serverInfo = server.address();
        listeningListener && listeningListener(serverInfo);
      });
      return server;
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/url.js
var splitPath, splitRoutingPath, extractGroupsFromPath, replaceGroupMarks, patternCache, getPattern, tryDecode, tryDecodeURI, getPath, getPathNoStrict, mergePath, checkOptionalParameter, _decodeURI, _getQueryParam, getQueryParam, getQueryParams, decodeURIComponent_;
var init_url = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/url.js"() {
    "use strict";
    splitPath = (path3) => {
      const paths = path3.split("/");
      if (paths[0] === "") {
        paths.shift();
      }
      return paths;
    };
    splitRoutingPath = (routePath) => {
      const { groups, path: path3 } = extractGroupsFromPath(routePath);
      const paths = splitPath(path3);
      return replaceGroupMarks(paths, groups);
    };
    extractGroupsFromPath = (path3) => {
      const groups = [];
      path3 = path3.replace(/\{[^}]+\}/g, (match2, index6) => {
        const mark = `@${index6}`;
        groups.push([mark, match2]);
        return mark;
      });
      return { groups, path: path3 };
    };
    replaceGroupMarks = (paths, groups) => {
      for (let i6 = groups.length - 1; i6 >= 0; i6--) {
        const [mark] = groups[i6];
        for (let j5 = paths.length - 1; j5 >= 0; j5--) {
          if (paths[j5].includes(mark)) {
            paths[j5] = paths[j5].replace(mark, groups[i6][1]);
            break;
          }
        }
      }
      return paths;
    };
    patternCache = {};
    getPattern = (label, next) => {
      if (label === "*") {
        return "*";
      }
      const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
      if (match2) {
        const cacheKey2 = `${label}#${next}`;
        if (!patternCache[cacheKey2]) {
          if (match2[2]) {
            patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
          } else {
            patternCache[cacheKey2] = [label, match2[1], true];
          }
        }
        return patternCache[cacheKey2];
      }
      return null;
    };
    tryDecode = (str, decoder) => {
      try {
        return decoder(str);
      } catch {
        return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
          try {
            return decoder(match2);
          } catch {
            return match2;
          }
        });
      }
    };
    tryDecodeURI = (str) => tryDecode(str, decodeURI);
    getPath = (request2) => {
      const url = request2.url;
      const start = url.indexOf("/", 8);
      let i6 = start;
      for (; i6 < url.length; i6++) {
        const charCode = url.charCodeAt(i6);
        if (charCode === 37) {
          const queryIndex = url.indexOf("?", i6);
          const path3 = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
          return tryDecodeURI(path3.includes("%25") ? path3.replace(/%25/g, "%2525") : path3);
        } else if (charCode === 63) {
          break;
        }
      }
      return url.slice(start, i6);
    };
    getPathNoStrict = (request2) => {
      const result = getPath(request2);
      return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
    };
    mergePath = (base, sub, ...rest) => {
      if (rest.length) {
        sub = mergePath(sub, ...rest);
      }
      return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
    };
    checkOptionalParameter = (path3) => {
      if (path3.charCodeAt(path3.length - 1) !== 63 || !path3.includes(":")) {
        return null;
      }
      const segments = path3.split("/");
      const results = [];
      let basePath = "";
      segments.forEach((segment) => {
        if (segment !== "" && !/\:/.test(segment)) {
          basePath += "/" + segment;
        } else if (/\:/.test(segment)) {
          if (/\?/.test(segment)) {
            if (results.length === 0 && basePath === "") {
              results.push("/");
            } else {
              results.push(basePath);
            }
            const optionalSegment = segment.replace("?", "");
            basePath += "/" + optionalSegment;
            results.push(basePath);
          } else {
            basePath += "/" + segment;
          }
        }
      });
      return results.filter((v6, i6, a5) => a5.indexOf(v6) === i6);
    };
    _decodeURI = (value) => {
      if (!/[%+]/.test(value)) {
        return value;
      }
      if (value.indexOf("+") !== -1) {
        value = value.replace(/\+/g, " ");
      }
      return value.indexOf("%") !== -1 ? decodeURIComponent_(value) : value;
    };
    _getQueryParam = (url, key, multiple) => {
      let encoded;
      if (!multiple && key && !/[%+]/.test(key)) {
        let keyIndex2 = url.indexOf(`?${key}`, 8);
        if (keyIndex2 === -1) {
          keyIndex2 = url.indexOf(`&${key}`, 8);
        }
        while (keyIndex2 !== -1) {
          const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
          if (trailingKeyCode === 61) {
            const valueIndex = keyIndex2 + key.length + 2;
            const endIndex = url.indexOf("&", valueIndex);
            return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
          } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
            return "";
          }
          keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
        }
        encoded = /[%+]/.test(url);
        if (!encoded) {
          return void 0;
        }
      }
      const results = {};
      encoded ??= /[%+]/.test(url);
      let keyIndex = url.indexOf("?", 8);
      while (keyIndex !== -1) {
        const nextKeyIndex = url.indexOf("&", keyIndex + 1);
        let valueIndex = url.indexOf("=", keyIndex);
        if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
          valueIndex = -1;
        }
        let name = url.slice(
          keyIndex + 1,
          valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
        );
        if (encoded) {
          name = _decodeURI(name);
        }
        keyIndex = nextKeyIndex;
        if (name === "") {
          continue;
        }
        let value;
        if (valueIndex === -1) {
          value = "";
        } else {
          value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
          if (encoded) {
            value = _decodeURI(value);
          }
        }
        if (multiple) {
          if (!(results[name] && Array.isArray(results[name]))) {
            results[name] = [];
          }
          ;
          results[name].push(value);
        } else {
          results[name] ??= value;
        }
      }
      return key ? results[key] : results;
    };
    getQueryParam = _getQueryParam;
    getQueryParams = (url, key) => {
      return _getQueryParam(url, key, true);
    };
    decodeURIComponent_ = decodeURIComponent;
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/cookie.js
var validCookieNameRegEx, validCookieValueRegEx, parse2;
var init_cookie = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/cookie.js"() {
    "use strict";
    init_url();
    validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/;
    validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/;
    parse2 = (cookie, name) => {
      if (name && cookie.indexOf(name) === -1) {
        return {};
      }
      const pairs = cookie.trim().split(";");
      const parsedCookie = {};
      for (let pairStr of pairs) {
        pairStr = pairStr.trim();
        const valueStartPos = pairStr.indexOf("=");
        if (valueStartPos === -1) {
          continue;
        }
        const cookieName = pairStr.substring(0, valueStartPos).trim();
        if (name && name !== cookieName || !validCookieNameRegEx.test(cookieName)) {
          continue;
        }
        let cookieValue = pairStr.substring(valueStartPos + 1).trim();
        if (cookieValue.startsWith('"') && cookieValue.endsWith('"')) {
          cookieValue = cookieValue.slice(1, -1);
        }
        if (validCookieValueRegEx.test(cookieValue)) {
          parsedCookie[cookieName] = decodeURIComponent_(cookieValue);
          if (name) {
            break;
          }
        }
      }
      return parsedCookie;
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/helper/cookie/index.js
var getCookie;
var init_cookie2 = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/helper/cookie/index.js"() {
    "use strict";
    init_cookie();
    getCookie = (c5, key, prefix2) => {
      const cookie = c5.req.raw.headers.get("Cookie");
      if (typeof key === "string") {
        if (!cookie) {
          return void 0;
        }
        let finalKey = key;
        if (prefix2 === "secure") {
          finalKey = "__Secure-" + key;
        } else if (prefix2 === "host") {
          finalKey = "__Host-" + key;
        }
        const obj2 = parse2(cookie, finalKey);
        return obj2[finalKey];
      }
      if (!cookie) {
        return {};
      }
      const obj = parse2(cookie);
      return obj;
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/http-exception.js
var HTTPException;
var init_http_exception = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/http-exception.js"() {
    "use strict";
    HTTPException = class extends Error {
      constructor(status = 500, options) {
        super(options?.message, { cause: options?.cause });
        __publicField(this, "res");
        __publicField(this, "status");
        this.res = options?.res;
        this.status = status;
      }
      getResponse() {
        if (this.res) {
          const newResponse = new Response(this.res.body, {
            status: this.status,
            headers: this.res.headers
          });
          return newResponse;
        }
        return new Response(this.message, {
          status: this.status
        });
      }
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/crypto.js
var init_crypto = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/crypto.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/buffer.js
var bufferToFormData;
var init_buffer = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/buffer.js"() {
    "use strict";
    init_crypto();
    bufferToFormData = (arrayBuffer, contentType) => {
      const response = new Response(arrayBuffer, {
        headers: {
          "Content-Type": contentType
        }
      });
      return response.formData();
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/validator.js
var jsonRegex, multipartRegex, urlencodedRegex, validator;
var init_validator = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/validator.js"() {
    "use strict";
    init_cookie2();
    init_http_exception();
    init_buffer();
    jsonRegex = /^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/;
    multipartRegex = /^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/;
    urlencodedRegex = /^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/;
    validator = (target, validationFunc) => {
      return async (c5, next) => {
        let value = {};
        const contentType = c5.req.header("Content-Type");
        switch (target) {
          case "json":
            if (!contentType || !jsonRegex.test(contentType)) {
              break;
            }
            try {
              value = await c5.req.json();
            } catch {
              const message = "Malformed JSON in request body";
              throw new HTTPException(400, { message });
            }
            break;
          case "form": {
            if (!contentType || !(multipartRegex.test(contentType) || urlencodedRegex.test(contentType))) {
              break;
            }
            let formData;
            if (c5.req.bodyCache.formData) {
              formData = await c5.req.bodyCache.formData;
            } else {
              try {
                const arrayBuffer = await c5.req.arrayBuffer();
                formData = await bufferToFormData(arrayBuffer, contentType);
                c5.req.bodyCache.formData = formData;
              } catch (e6) {
                let message = "Malformed FormData request.";
                message += e6 instanceof Error ? ` ${e6.message}` : ` ${String(e6)}`;
                throw new HTTPException(400, { message });
              }
            }
            const form = {};
            formData.forEach((value2, key) => {
              if (key.endsWith("[]")) {
                ;
                (form[key] ??= []).push(value2);
              } else if (Array.isArray(form[key])) {
                ;
                form[key].push(value2);
              } else if (key in form) {
                form[key] = [form[key], value2];
              } else {
                form[key] = value2;
              }
            });
            value = form;
            break;
          }
          case "query":
            value = Object.fromEntries(
              Object.entries(c5.req.queries()).map(([k5, v6]) => {
                return v6.length === 1 ? [k5, v6[0]] : [k5, v6];
              })
            );
            break;
          case "param":
            value = c5.req.param();
            break;
          case "header":
            value = c5.req.header();
            break;
          case "cookie":
            value = getCookie(c5);
            break;
        }
        const res = await validationFunc(value, c5);
        if (res instanceof Response) {
          return res;
        }
        c5.req.addValidatedData(target, res);
        await next();
      };
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/index.js
var init_validator2 = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/index.js"() {
    "use strict";
    init_validator();
  }
});

// ../node_modules/.pnpm/@hono+zod-validator@0.2.2_hono@4.7.10_zod@3.25.42/node_modules/@hono/zod-validator/dist/esm/index.js
var zValidator;
var init_esm2 = __esm({
  "../node_modules/.pnpm/@hono+zod-validator@0.2.2_hono@4.7.10_zod@3.25.42/node_modules/@hono/zod-validator/dist/esm/index.js"() {
    "use strict";
    init_validator2();
    zValidator = (target, schema6, hook) => (
      // @ts-expect-error not typed well
      validator(target, async (value, c5) => {
        const result = await schema6.safeParseAsync(value);
        if (hook) {
          const hookResult = await hook({ data: value, ...result }, c5);
          if (hookResult) {
            if (hookResult instanceof Response) {
              return hookResult;
            }
            if ("response" in hookResult) {
              return hookResult.response;
            }
          }
        }
        if (!result.success) {
          return c5.json(result, 400);
        }
        return result.data;
      })
    );
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/compose.js
var compose;
var init_compose = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/compose.js"() {
    "use strict";
    compose = (middleware, onError, onNotFound) => {
      return (context, next) => {
        let index6 = -1;
        return dispatch(0);
        async function dispatch(i6) {
          if (i6 <= index6) {
            throw new Error("next() called multiple times");
          }
          index6 = i6;
          let res;
          let isError = false;
          let handler;
          if (middleware[i6]) {
            handler = middleware[i6][0][0];
            context.req.routeIndex = i6;
          } else {
            handler = i6 === middleware.length && next || void 0;
          }
          if (handler) {
            try {
              res = await handler(context, () => dispatch(i6 + 1));
            } catch (err2) {
              if (err2 instanceof Error && onError) {
                context.error = err2;
                res = await onError(err2, context);
                isError = true;
              } else {
                throw err2;
              }
            }
          } else {
            if (context.finalized === false && onNotFound) {
              res = await onNotFound(context);
            }
          }
          if (res && (context.finalized === false || isError)) {
            context.res = res;
          }
          return context;
        }
      };
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/body.js
async function parseFormData(request2, options) {
  const formData = await request2.formData();
  if (formData) {
    return convertFormDataToBodyData(formData, options);
  }
  return {};
}
function convertFormDataToBodyData(formData, options) {
  const form = /* @__PURE__ */ Object.create(null);
  formData.forEach((value, key) => {
    const shouldParseAllValues = options.all || key.endsWith("[]");
    if (!shouldParseAllValues) {
      form[key] = value;
    } else {
      handleParsingAllValues(form, key, value);
    }
  });
  if (options.dot) {
    Object.entries(form).forEach(([key, value]) => {
      const shouldParseDotValues = key.includes(".");
      if (shouldParseDotValues) {
        handleParsingNestedValues(form, key, value);
        delete form[key];
      }
    });
  }
  return form;
}
var parseBody, handleParsingAllValues, handleParsingNestedValues;
var init_body = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/body.js"() {
    "use strict";
    init_request();
    parseBody = async (request2, options = /* @__PURE__ */ Object.create(null)) => {
      const { all = false, dot = false } = options;
      const headers = request2 instanceof HonoRequest ? request2.raw.headers : request2.headers;
      const contentType = headers.get("Content-Type");
      if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
        return parseFormData(request2, { all, dot });
      }
      return {};
    };
    handleParsingAllValues = (form, key, value) => {
      if (form[key] !== void 0) {
        if (Array.isArray(form[key])) {
          ;
          form[key].push(value);
        } else {
          form[key] = [form[key], value];
        }
      } else {
        form[key] = value;
      }
    };
    handleParsingNestedValues = (form, key, value) => {
      let nestedForm = form;
      const keys = key.split(".");
      keys.forEach((key2, index6) => {
        if (index6 === keys.length - 1) {
          nestedForm[key2] = value;
        } else {
          if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
            nestedForm[key2] = /* @__PURE__ */ Object.create(null);
          }
          nestedForm = nestedForm[key2];
        }
      });
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/request.js
var tryDecodeURIComponent, _validatedData, _matchResult, _HonoRequest_instances, getDecodedParam_fn, getAllDecodedParams_fn, getParamValue_fn, _cachedBody, _a2, HonoRequest;
var init_request = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/request.js"() {
    "use strict";
    init_body();
    init_url();
    tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
    HonoRequest = (_a2 = class {
      constructor(request2, path3 = "/", matchResult = [[]]) {
        __privateAdd(this, _HonoRequest_instances);
        __publicField(this, "raw");
        __privateAdd(this, _validatedData);
        __privateAdd(this, _matchResult);
        __publicField(this, "routeIndex", 0);
        __publicField(this, "path");
        __publicField(this, "bodyCache", {});
        __privateAdd(this, _cachedBody, (key) => {
          const { bodyCache, raw: raw2 } = this;
          const cachedBody = bodyCache[key];
          if (cachedBody) {
            return cachedBody;
          }
          const anyCachedKey = Object.keys(bodyCache)[0];
          if (anyCachedKey) {
            return bodyCache[anyCachedKey].then((body) => {
              if (anyCachedKey === "json") {
                body = JSON.stringify(body);
              }
              return new Response(body)[key]();
            });
          }
          return bodyCache[key] = raw2[key]();
        });
        this.raw = request2;
        this.path = path3;
        __privateSet(this, _matchResult, matchResult);
        __privateSet(this, _validatedData, {});
      }
      param(key) {
        return key ? __privateMethod(this, _HonoRequest_instances, getDecodedParam_fn).call(this, key) : __privateMethod(this, _HonoRequest_instances, getAllDecodedParams_fn).call(this);
      }
      query(key) {
        return getQueryParam(this.url, key);
      }
      queries(key) {
        return getQueryParams(this.url, key);
      }
      header(name) {
        if (name) {
          return this.raw.headers.get(name) ?? void 0;
        }
        const headerData = {};
        this.raw.headers.forEach((value, key) => {
          headerData[key] = value;
        });
        return headerData;
      }
      async parseBody(options) {
        return this.bodyCache.parsedBody ??= await parseBody(this, options);
      }
      json() {
        return __privateGet(this, _cachedBody).call(this, "json");
      }
      text() {
        return __privateGet(this, _cachedBody).call(this, "text");
      }
      arrayBuffer() {
        return __privateGet(this, _cachedBody).call(this, "arrayBuffer");
      }
      blob() {
        return __privateGet(this, _cachedBody).call(this, "blob");
      }
      formData() {
        return __privateGet(this, _cachedBody).call(this, "formData");
      }
      addValidatedData(target, data) {
        __privateGet(this, _validatedData)[target] = data;
      }
      valid(target) {
        return __privateGet(this, _validatedData)[target];
      }
      get url() {
        return this.raw.url;
      }
      get method() {
        return this.raw.method;
      }
      get matchedRoutes() {
        return __privateGet(this, _matchResult)[0].map(([[, route]]) => route);
      }
      get routePath() {
        return __privateGet(this, _matchResult)[0].map(([[, route]]) => route)[this.routeIndex].path;
      }
    }, _validatedData = new WeakMap(), _matchResult = new WeakMap(), _HonoRequest_instances = new WeakSet(), getDecodedParam_fn = function(key) {
      const paramKey = __privateGet(this, _matchResult)[0][this.routeIndex][1][key];
      const param = __privateMethod(this, _HonoRequest_instances, getParamValue_fn).call(this, paramKey);
      return param ? /\%/.test(param) ? tryDecodeURIComponent(param) : param : void 0;
    }, getAllDecodedParams_fn = function() {
      const decoded = {};
      const keys = Object.keys(__privateGet(this, _matchResult)[0][this.routeIndex][1]);
      for (const key of keys) {
        const value = __privateMethod(this, _HonoRequest_instances, getParamValue_fn).call(this, __privateGet(this, _matchResult)[0][this.routeIndex][1][key]);
        if (value && typeof value === "string") {
          decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
        }
      }
      return decoded;
    }, getParamValue_fn = function(paramKey) {
      return __privateGet(this, _matchResult)[1] ? __privateGet(this, _matchResult)[1][paramKey] : paramKey;
    }, _cachedBody = new WeakMap(), _a2);
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/html.js
var HtmlEscapedCallbackPhase, raw, resolveCallback;
var init_html = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/html.js"() {
    "use strict";
    HtmlEscapedCallbackPhase = {
      Stringify: 1,
      BeforeStream: 2,
      Stream: 3
    };
    raw = (value, callbacks) => {
      const escapedString = new String(value);
      escapedString.isEscaped = true;
      escapedString.callbacks = callbacks;
      return escapedString;
    };
    resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
      if (typeof str === "object" && !(str instanceof String)) {
        if (!(str instanceof Promise)) {
          str = str.toString();
        }
        if (str instanceof Promise) {
          str = await str;
        }
      }
      const callbacks = str.callbacks;
      if (!callbacks?.length) {
        return Promise.resolve(str);
      }
      if (buffer) {
        buffer[0] += str;
      } else {
        buffer = [str];
      }
      const resStr = Promise.all(callbacks.map((c5) => c5({ phase, buffer, context }))).then(
        (res) => Promise.all(
          res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
        ).then(() => buffer[0])
      );
      if (preserveCallbacks) {
        return raw(await resStr, callbacks);
      } else {
        return resStr;
      }
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/context.js
var TEXT_PLAIN, setHeaders, _rawRequest, _req, _var, _status, _executionCtx, _headers, _preparedHeaders, _res, _isFresh, _layout, _renderer, _notFoundHandler, _matchResult2, _path, _Context_instances, newResponse_fn, _a3, Context;
var init_context = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/context.js"() {
    "use strict";
    init_request();
    init_html();
    TEXT_PLAIN = "text/plain; charset=UTF-8";
    setHeaders = (headers, map2 = {}) => {
      for (const key of Object.keys(map2)) {
        headers.set(key, map2[key]);
      }
      return headers;
    };
    Context = (_a3 = class {
      constructor(req, options) {
        __privateAdd(this, _Context_instances);
        __privateAdd(this, _rawRequest);
        __privateAdd(this, _req);
        __publicField(this, "env", {});
        __privateAdd(this, _var);
        __publicField(this, "finalized", false);
        __publicField(this, "error");
        __privateAdd(this, _status, 200);
        __privateAdd(this, _executionCtx);
        __privateAdd(this, _headers);
        __privateAdd(this, _preparedHeaders);
        __privateAdd(this, _res);
        __privateAdd(this, _isFresh, true);
        __privateAdd(this, _layout);
        __privateAdd(this, _renderer);
        __privateAdd(this, _notFoundHandler);
        __privateAdd(this, _matchResult2);
        __privateAdd(this, _path);
        __publicField(this, "render", (...args) => {
          __privateGet(this, _renderer) ?? __privateSet(this, _renderer, (content) => this.html(content));
          return __privateGet(this, _renderer).call(this, ...args);
        });
        __publicField(this, "setLayout", (layout) => __privateSet(this, _layout, layout));
        __publicField(this, "getLayout", () => __privateGet(this, _layout));
        __publicField(this, "setRenderer", (renderer) => {
          __privateSet(this, _renderer, renderer);
        });
        __publicField(this, "header", (name, value, options) => {
          if (this.finalized) {
            __privateSet(this, _res, new Response(__privateGet(this, _res).body, __privateGet(this, _res)));
          }
          if (value === void 0) {
            if (__privateGet(this, _headers)) {
              __privateGet(this, _headers).delete(name);
            } else if (__privateGet(this, _preparedHeaders)) {
              delete __privateGet(this, _preparedHeaders)[name.toLocaleLowerCase()];
            }
            if (this.finalized) {
              this.res.headers.delete(name);
            }
            return;
          }
          if (options?.append) {
            if (!__privateGet(this, _headers)) {
              __privateSet(this, _isFresh, false);
              __privateSet(this, _headers, new Headers(__privateGet(this, _preparedHeaders)));
              __privateSet(this, _preparedHeaders, {});
            }
            __privateGet(this, _headers).append(name, value);
          } else {
            if (__privateGet(this, _headers)) {
              __privateGet(this, _headers).set(name, value);
            } else {
              __privateGet(this, _preparedHeaders) ?? __privateSet(this, _preparedHeaders, {});
              __privateGet(this, _preparedHeaders)[name.toLowerCase()] = value;
            }
          }
          if (this.finalized) {
            if (options?.append) {
              this.res.headers.append(name, value);
            } else {
              this.res.headers.set(name, value);
            }
          }
        });
        __publicField(this, "status", (status) => {
          __privateSet(this, _isFresh, false);
          __privateSet(this, _status, status);
        });
        __publicField(this, "set", (key, value) => {
          __privateGet(this, _var) ?? __privateSet(this, _var, /* @__PURE__ */ new Map());
          __privateGet(this, _var).set(key, value);
        });
        __publicField(this, "get", (key) => {
          return __privateGet(this, _var) ? __privateGet(this, _var).get(key) : void 0;
        });
        __publicField(this, "newResponse", (...args) => __privateMethod(this, _Context_instances, newResponse_fn).call(this, ...args));
        __publicField(this, "body", (data, arg, headers) => {
          return typeof arg === "number" ? __privateMethod(this, _Context_instances, newResponse_fn).call(this, data, arg, headers) : __privateMethod(this, _Context_instances, newResponse_fn).call(this, data, arg);
        });
        __publicField(this, "text", (text, arg, headers) => {
          if (!__privateGet(this, _preparedHeaders)) {
            if (__privateGet(this, _isFresh) && !headers && !arg) {
              return new Response(text);
            }
            __privateSet(this, _preparedHeaders, {});
          }
          __privateGet(this, _preparedHeaders)["content-type"] = TEXT_PLAIN;
          if (typeof arg === "number") {
            return __privateMethod(this, _Context_instances, newResponse_fn).call(this, text, arg, headers);
          }
          return __privateMethod(this, _Context_instances, newResponse_fn).call(this, text, arg);
        });
        __publicField(this, "json", (object, arg, headers) => {
          const body = JSON.stringify(object);
          __privateGet(this, _preparedHeaders) ?? __privateSet(this, _preparedHeaders, {});
          __privateGet(this, _preparedHeaders)["content-type"] = "application/json";
          return typeof arg === "number" ? __privateMethod(this, _Context_instances, newResponse_fn).call(this, body, arg, headers) : __privateMethod(this, _Context_instances, newResponse_fn).call(this, body, arg);
        });
        __publicField(this, "html", (html, arg, headers) => {
          __privateGet(this, _preparedHeaders) ?? __privateSet(this, _preparedHeaders, {});
          __privateGet(this, _preparedHeaders)["content-type"] = "text/html; charset=UTF-8";
          if (typeof html === "object") {
            return resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then((html2) => {
              return typeof arg === "number" ? __privateMethod(this, _Context_instances, newResponse_fn).call(this, html2, arg, headers) : __privateMethod(this, _Context_instances, newResponse_fn).call(this, html2, arg);
            });
          }
          return typeof arg === "number" ? __privateMethod(this, _Context_instances, newResponse_fn).call(this, html, arg, headers) : __privateMethod(this, _Context_instances, newResponse_fn).call(this, html, arg);
        });
        __publicField(this, "redirect", (location, status) => {
          __privateGet(this, _headers) ?? __privateSet(this, _headers, new Headers());
          __privateGet(this, _headers).set("Location", String(location));
          return this.newResponse(null, status ?? 302);
        });
        __publicField(this, "notFound", () => {
          __privateGet(this, _notFoundHandler) ?? __privateSet(this, _notFoundHandler, () => new Response());
          return __privateGet(this, _notFoundHandler).call(this, this);
        });
        __privateSet(this, _rawRequest, req);
        if (options) {
          __privateSet(this, _executionCtx, options.executionCtx);
          this.env = options.env;
          __privateSet(this, _notFoundHandler, options.notFoundHandler);
          __privateSet(this, _path, options.path);
          __privateSet(this, _matchResult2, options.matchResult);
        }
      }
      get req() {
        __privateGet(this, _req) ?? __privateSet(this, _req, new HonoRequest(__privateGet(this, _rawRequest), __privateGet(this, _path), __privateGet(this, _matchResult2)));
        return __privateGet(this, _req);
      }
      get event() {
        if (__privateGet(this, _executionCtx) && "respondWith" in __privateGet(this, _executionCtx)) {
          return __privateGet(this, _executionCtx);
        } else {
          throw Error("This context has no FetchEvent");
        }
      }
      get executionCtx() {
        if (__privateGet(this, _executionCtx)) {
          return __privateGet(this, _executionCtx);
        } else {
          throw Error("This context has no ExecutionContext");
        }
      }
      get res() {
        __privateSet(this, _isFresh, false);
        return __privateGet(this, _res) || __privateSet(this, _res, new Response("404 Not Found", { status: 404 }));
      }
      set res(_res2) {
        __privateSet(this, _isFresh, false);
        if (__privateGet(this, _res) && _res2) {
          _res2 = new Response(_res2.body, _res2);
          for (const [k5, v6] of __privateGet(this, _res).headers.entries()) {
            if (k5 === "content-type") {
              continue;
            }
            if (k5 === "set-cookie") {
              const cookies = __privateGet(this, _res).headers.getSetCookie();
              _res2.headers.delete("set-cookie");
              for (const cookie of cookies) {
                _res2.headers.append("set-cookie", cookie);
              }
            } else {
              _res2.headers.set(k5, v6);
            }
          }
        }
        __privateSet(this, _res, _res2);
        this.finalized = true;
      }
      get var() {
        if (!__privateGet(this, _var)) {
          return {};
        }
        return Object.fromEntries(__privateGet(this, _var));
      }
    }, _rawRequest = new WeakMap(), _req = new WeakMap(), _var = new WeakMap(), _status = new WeakMap(), _executionCtx = new WeakMap(), _headers = new WeakMap(), _preparedHeaders = new WeakMap(), _res = new WeakMap(), _isFresh = new WeakMap(), _layout = new WeakMap(), _renderer = new WeakMap(), _notFoundHandler = new WeakMap(), _matchResult2 = new WeakMap(), _path = new WeakMap(), _Context_instances = new WeakSet(), newResponse_fn = function(data, arg, headers) {
      if (__privateGet(this, _isFresh) && !headers && !arg && __privateGet(this, _status) === 200) {
        return new Response(data, {
          headers: __privateGet(this, _preparedHeaders)
        });
      }
      if (arg && typeof arg !== "number") {
        const header = new Headers(arg.headers);
        if (__privateGet(this, _headers)) {
          __privateGet(this, _headers).forEach((v6, k5) => {
            if (k5 === "set-cookie") {
              header.append(k5, v6);
            } else {
              header.set(k5, v6);
            }
          });
        }
        const headers2 = setHeaders(header, __privateGet(this, _preparedHeaders));
        return new Response(data, {
          headers: headers2,
          status: arg.status ?? __privateGet(this, _status)
        });
      }
      const status = typeof arg === "number" ? arg : __privateGet(this, _status);
      __privateGet(this, _preparedHeaders) ?? __privateSet(this, _preparedHeaders, {});
      __privateGet(this, _headers) ?? __privateSet(this, _headers, new Headers());
      setHeaders(__privateGet(this, _headers), __privateGet(this, _preparedHeaders));
      if (__privateGet(this, _res)) {
        __privateGet(this, _res).headers.forEach((v6, k5) => {
          if (k5 === "set-cookie") {
            __privateGet(this, _headers)?.append(k5, v6);
          } else {
            __privateGet(this, _headers)?.set(k5, v6);
          }
        });
        setHeaders(__privateGet(this, _headers), __privateGet(this, _preparedHeaders));
      }
      headers ??= {};
      for (const [k5, v6] of Object.entries(headers)) {
        if (typeof v6 === "string") {
          __privateGet(this, _headers).set(k5, v6);
        } else {
          __privateGet(this, _headers).delete(k5);
          for (const v22 of v6) {
            __privateGet(this, _headers).append(k5, v22);
          }
        }
      }
      return new Response(data, {
        status,
        headers: __privateGet(this, _headers)
      });
    }, _a3);
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router.js
var METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE, METHODS, MESSAGE_MATCHER_IS_ALREADY_BUILT, UnsupportedPathError;
var init_router = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router.js"() {
    "use strict";
    METHOD_NAME_ALL = "ALL";
    METHOD_NAME_ALL_LOWERCASE = "all";
    METHODS = ["get", "post", "put", "delete", "options", "patch"];
    MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
    UnsupportedPathError = class extends Error {
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/constants.js
var COMPOSED_HANDLER;
var init_constants = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/constants.js"() {
    "use strict";
    COMPOSED_HANDLER = "__COMPOSED_HANDLER";
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono-base.js
var notFoundHandler, errorHandler, _path2, _Hono_instances, clone_fn, _notFoundHandler2, addRoute_fn, handleError_fn, dispatch_fn, _a4, Hono;
var init_hono_base = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono-base.js"() {
    "use strict";
    init_compose();
    init_context();
    init_router();
    init_constants();
    init_url();
    notFoundHandler = (c5) => {
      return c5.text("404 Not Found", 404);
    };
    errorHandler = (err2, c5) => {
      if ("getResponse" in err2) {
        return err2.getResponse();
      }
      console.error(err2);
      return c5.text("Internal Server Error", 500);
    };
    Hono = (_a4 = class {
      constructor(options = {}) {
        __privateAdd(this, _Hono_instances);
        __publicField(this, "get");
        __publicField(this, "post");
        __publicField(this, "put");
        __publicField(this, "delete");
        __publicField(this, "options");
        __publicField(this, "patch");
        __publicField(this, "all");
        __publicField(this, "on");
        __publicField(this, "use");
        __publicField(this, "router");
        __publicField(this, "getPath");
        __publicField(this, "_basePath", "/");
        __privateAdd(this, _path2, "/");
        __publicField(this, "routes", []);
        __privateAdd(this, _notFoundHandler2, notFoundHandler);
        __publicField(this, "errorHandler", errorHandler);
        __publicField(this, "onError", (handler) => {
          this.errorHandler = handler;
          return this;
        });
        __publicField(this, "notFound", (handler) => {
          __privateSet(this, _notFoundHandler2, handler);
          return this;
        });
        __publicField(this, "fetch", (request2, ...rest) => {
          return __privateMethod(this, _Hono_instances, dispatch_fn).call(this, request2, rest[1], rest[0], request2.method);
        });
        __publicField(this, "request", (input, requestInit, Env, executionCtx) => {
          if (input instanceof Request) {
            return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
          }
          input = input.toString();
          return this.fetch(
            new Request(
              /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
              requestInit
            ),
            Env,
            executionCtx
          );
        });
        __publicField(this, "fire", () => {
          addEventListener("fetch", (event) => {
            event.respondWith(__privateMethod(this, _Hono_instances, dispatch_fn).call(this, event.request, event, void 0, event.request.method));
          });
        });
        const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
        allMethods.forEach((method) => {
          this[method] = (args1, ...args) => {
            if (typeof args1 === "string") {
              __privateSet(this, _path2, args1);
            } else {
              __privateMethod(this, _Hono_instances, addRoute_fn).call(this, method, __privateGet(this, _path2), args1);
            }
            args.forEach((handler) => {
              __privateMethod(this, _Hono_instances, addRoute_fn).call(this, method, __privateGet(this, _path2), handler);
            });
            return this;
          };
        });
        this.on = (method, path3, ...handlers) => {
          for (const p5 of [path3].flat()) {
            __privateSet(this, _path2, p5);
            for (const m6 of [method].flat()) {
              handlers.map((handler) => {
                __privateMethod(this, _Hono_instances, addRoute_fn).call(this, m6.toUpperCase(), __privateGet(this, _path2), handler);
              });
            }
          }
          return this;
        };
        this.use = (arg1, ...handlers) => {
          if (typeof arg1 === "string") {
            __privateSet(this, _path2, arg1);
          } else {
            __privateSet(this, _path2, "*");
            handlers.unshift(arg1);
          }
          handlers.forEach((handler) => {
            __privateMethod(this, _Hono_instances, addRoute_fn).call(this, METHOD_NAME_ALL, __privateGet(this, _path2), handler);
          });
          return this;
        };
        const { strict, ...optionsWithoutStrict } = options;
        Object.assign(this, optionsWithoutStrict);
        this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
      }
      route(path3, app) {
        const subApp = this.basePath(path3);
        app.routes.map((r6) => {
          var _a15;
          let handler;
          if (app.errorHandler === errorHandler) {
            handler = r6.handler;
          } else {
            handler = async (c5, next) => (await compose([], app.errorHandler)(c5, () => r6.handler(c5, next))).res;
            handler[COMPOSED_HANDLER] = r6.handler;
          }
          __privateMethod(_a15 = subApp, _Hono_instances, addRoute_fn).call(_a15, r6.method, r6.path, handler);
        });
        return this;
      }
      basePath(path3) {
        const subApp = __privateMethod(this, _Hono_instances, clone_fn).call(this);
        subApp._basePath = mergePath(this._basePath, path3);
        return subApp;
      }
      mount(path3, applicationHandler, options) {
        let replaceRequest;
        let optionHandler;
        if (options) {
          if (typeof options === "function") {
            optionHandler = options;
          } else {
            optionHandler = options.optionHandler;
            if (options.replaceRequest === false) {
              replaceRequest = (request2) => request2;
            } else {
              replaceRequest = options.replaceRequest;
            }
          }
        }
        const getOptions = optionHandler ? (c5) => {
          const options2 = optionHandler(c5);
          return Array.isArray(options2) ? options2 : [options2];
        } : (c5) => {
          let executionContext = void 0;
          try {
            executionContext = c5.executionCtx;
          } catch {
          }
          return [c5.env, executionContext];
        };
        replaceRequest ||= (() => {
          const mergedPath = mergePath(this._basePath, path3);
          const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
          return (request2) => {
            const url = new URL(request2.url);
            url.pathname = url.pathname.slice(pathPrefixLength) || "/";
            return new Request(url, request2);
          };
        })();
        const handler = async (c5, next) => {
          const res = await applicationHandler(replaceRequest(c5.req.raw), ...getOptions(c5));
          if (res) {
            return res;
          }
          await next();
        };
        __privateMethod(this, _Hono_instances, addRoute_fn).call(this, METHOD_NAME_ALL, mergePath(path3, "*"), handler);
        return this;
      }
    }, _path2 = new WeakMap(), _Hono_instances = new WeakSet(), clone_fn = function() {
      const clone2 = new Hono({
        router: this.router,
        getPath: this.getPath
      });
      clone2.errorHandler = this.errorHandler;
      __privateSet(clone2, _notFoundHandler2, __privateGet(this, _notFoundHandler2));
      clone2.routes = this.routes;
      return clone2;
    }, _notFoundHandler2 = new WeakMap(), addRoute_fn = function(method, path3, handler) {
      method = method.toUpperCase();
      path3 = mergePath(this._basePath, path3);
      const r6 = { path: path3, method, handler };
      this.router.add(method, path3, [handler, r6]);
      this.routes.push(r6);
    }, handleError_fn = function(err2, c5) {
      if (err2 instanceof Error) {
        return this.errorHandler(err2, c5);
      }
      throw err2;
    }, dispatch_fn = function(request2, executionCtx, env4, method) {
      if (method === "HEAD") {
        return (async () => new Response(null, await __privateMethod(this, _Hono_instances, dispatch_fn).call(this, request2, executionCtx, env4, "GET")))();
      }
      const path3 = this.getPath(request2, { env: env4 });
      const matchResult = this.router.match(method, path3);
      const c5 = new Context(request2, {
        path: path3,
        matchResult,
        env: env4,
        executionCtx,
        notFoundHandler: __privateGet(this, _notFoundHandler2)
      });
      if (matchResult[0].length === 1) {
        let res;
        try {
          res = matchResult[0][0][0][0](c5, async () => {
            c5.res = await __privateGet(this, _notFoundHandler2).call(this, c5);
          });
        } catch (err2) {
          return __privateMethod(this, _Hono_instances, handleError_fn).call(this, err2, c5);
        }
        return res instanceof Promise ? res.then(
          (resolved) => resolved || (c5.finalized ? c5.res : __privateGet(this, _notFoundHandler2).call(this, c5))
        ).catch((err2) => __privateMethod(this, _Hono_instances, handleError_fn).call(this, err2, c5)) : res ?? __privateGet(this, _notFoundHandler2).call(this, c5);
      }
      const composed = compose(matchResult[0], this.errorHandler, __privateGet(this, _notFoundHandler2));
      return (async () => {
        try {
          const context = await composed(c5);
          if (!context.finalized) {
            throw new Error(
              "Context is not finalized. Did you forget to return a Response object or `await next()`?"
            );
          }
          return context.res;
        } catch (err2) {
          return __privateMethod(this, _Hono_instances, handleError_fn).call(this, err2, c5);
        }
      })();
    }, _a4);
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/node.js
function compareKey(a5, b5) {
  if (a5.length === 1) {
    return b5.length === 1 ? a5 < b5 ? -1 : 1 : -1;
  }
  if (b5.length === 1) {
    return 1;
  }
  if (a5 === ONLY_WILDCARD_REG_EXP_STR || a5 === TAIL_WILDCARD_REG_EXP_STR) {
    return 1;
  } else if (b5 === ONLY_WILDCARD_REG_EXP_STR || b5 === TAIL_WILDCARD_REG_EXP_STR) {
    return -1;
  }
  if (a5 === LABEL_REG_EXP_STR) {
    return 1;
  } else if (b5 === LABEL_REG_EXP_STR) {
    return -1;
  }
  return a5.length === b5.length ? a5 < b5 ? -1 : 1 : b5.length - a5.length;
}
var LABEL_REG_EXP_STR, ONLY_WILDCARD_REG_EXP_STR, TAIL_WILDCARD_REG_EXP_STR, PATH_ERROR, regExpMetaChars, _index, _varIndex, _children, _a5, Node;
var init_node = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/node.js"() {
    "use strict";
    LABEL_REG_EXP_STR = "[^/]+";
    ONLY_WILDCARD_REG_EXP_STR = ".*";
    TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
    PATH_ERROR = Symbol();
    regExpMetaChars = new Set(".\\+*[^]$()");
    Node = (_a5 = class {
      constructor() {
        __privateAdd(this, _index);
        __privateAdd(this, _varIndex);
        __privateAdd(this, _children, /* @__PURE__ */ Object.create(null));
      }
      insert(tokens, index6, paramMap, context, pathErrorCheckOnly) {
        if (tokens.length === 0) {
          if (__privateGet(this, _index) !== void 0) {
            throw PATH_ERROR;
          }
          if (pathErrorCheckOnly) {
            return;
          }
          __privateSet(this, _index, index6);
          return;
        }
        const [token, ...restTokens] = tokens;
        const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
        let node;
        if (pattern) {
          const name = pattern[1];
          let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
          if (name && pattern[2]) {
            regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
            if (/\((?!\?:)/.test(regexpStr)) {
              throw PATH_ERROR;
            }
          }
          node = __privateGet(this, _children)[regexpStr];
          if (!node) {
            if (Object.keys(__privateGet(this, _children)).some(
              (k5) => k5 !== ONLY_WILDCARD_REG_EXP_STR && k5 !== TAIL_WILDCARD_REG_EXP_STR
            )) {
              throw PATH_ERROR;
            }
            if (pathErrorCheckOnly) {
              return;
            }
            node = __privateGet(this, _children)[regexpStr] = new Node();
            if (name !== "") {
              __privateSet(node, _varIndex, context.varIndex++);
            }
          }
          if (!pathErrorCheckOnly && name !== "") {
            paramMap.push([name, __privateGet(node, _varIndex)]);
          }
        } else {
          node = __privateGet(this, _children)[token];
          if (!node) {
            if (Object.keys(__privateGet(this, _children)).some(
              (k5) => k5.length > 1 && k5 !== ONLY_WILDCARD_REG_EXP_STR && k5 !== TAIL_WILDCARD_REG_EXP_STR
            )) {
              throw PATH_ERROR;
            }
            if (pathErrorCheckOnly) {
              return;
            }
            node = __privateGet(this, _children)[token] = new Node();
          }
        }
        node.insert(restTokens, index6, paramMap, context, pathErrorCheckOnly);
      }
      buildRegExpStr() {
        const childKeys = Object.keys(__privateGet(this, _children)).sort(compareKey);
        const strList = childKeys.map((k5) => {
          const c5 = __privateGet(this, _children)[k5];
          return (typeof __privateGet(c5, _varIndex) === "number" ? `(${k5})@${__privateGet(c5, _varIndex)}` : regExpMetaChars.has(k5) ? `\\${k5}` : k5) + c5.buildRegExpStr();
        });
        if (typeof __privateGet(this, _index) === "number") {
          strList.unshift(`#${__privateGet(this, _index)}`);
        }
        if (strList.length === 0) {
          return "";
        }
        if (strList.length === 1) {
          return strList[0];
        }
        return "(?:" + strList.join("|") + ")";
      }
    }, _index = new WeakMap(), _varIndex = new WeakMap(), _children = new WeakMap(), _a5);
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/trie.js
var _context, _root, _a6, Trie;
var init_trie = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/trie.js"() {
    "use strict";
    init_node();
    Trie = (_a6 = class {
      constructor() {
        __privateAdd(this, _context, { varIndex: 0 });
        __privateAdd(this, _root, new Node());
      }
      insert(path3, index6, pathErrorCheckOnly) {
        const paramAssoc = [];
        const groups = [];
        for (let i6 = 0; ; ) {
          let replaced = false;
          path3 = path3.replace(/\{[^}]+\}/g, (m6) => {
            const mark = `@\\${i6}`;
            groups[i6] = [mark, m6];
            i6++;
            replaced = true;
            return mark;
          });
          if (!replaced) {
            break;
          }
        }
        const tokens = path3.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
        for (let i6 = groups.length - 1; i6 >= 0; i6--) {
          const [mark] = groups[i6];
          for (let j5 = tokens.length - 1; j5 >= 0; j5--) {
            if (tokens[j5].indexOf(mark) !== -1) {
              tokens[j5] = tokens[j5].replace(mark, groups[i6][1]);
              break;
            }
          }
        }
        __privateGet(this, _root).insert(tokens, index6, paramAssoc, __privateGet(this, _context), pathErrorCheckOnly);
        return paramAssoc;
      }
      buildRegExp() {
        let regexp = __privateGet(this, _root).buildRegExpStr();
        if (regexp === "") {
          return [/^$/, [], []];
        }
        let captureIndex = 0;
        const indexReplacementMap = [];
        const paramReplacementMap = [];
        regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_3, handlerIndex, paramIndex) => {
          if (handlerIndex !== void 0) {
            indexReplacementMap[++captureIndex] = Number(handlerIndex);
            return "$()";
          }
          if (paramIndex !== void 0) {
            paramReplacementMap[Number(paramIndex)] = ++captureIndex;
            return "";
          }
          return "";
        });
        return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
      }
    }, _context = new WeakMap(), _root = new WeakMap(), _a6);
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/router.js
function buildWildcardRegExp(path3) {
  return wildcardRegExpCache[path3] ??= new RegExp(
    path3 === "*" ? "" : `^${path3.replace(
      /\/\*$|([.\\+*[^\]$()])/g,
      (_3, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
    )}$`
  );
}
function clearWildcardRegExpCache() {
  wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
}
function buildMatcherFromPreprocessedRoutes(routes) {
  const trie = new Trie();
  const handlerData = [];
  if (routes.length === 0) {
    return nullMatcher;
  }
  const routesWithStaticPathFlag = routes.map(
    (route) => [!/\*|\/:/.test(route[0]), ...route]
  ).sort(
    ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
  );
  const staticMap = /* @__PURE__ */ Object.create(null);
  for (let i6 = 0, j5 = -1, len = routesWithStaticPathFlag.length; i6 < len; i6++) {
    const [pathErrorCheckOnly, path3, handlers] = routesWithStaticPathFlag[i6];
    if (pathErrorCheckOnly) {
      staticMap[path3] = [handlers.map(([h6]) => [h6, /* @__PURE__ */ Object.create(null)]), emptyParam];
    } else {
      j5++;
    }
    let paramAssoc;
    try {
      paramAssoc = trie.insert(path3, j5, pathErrorCheckOnly);
    } catch (e6) {
      throw e6 === PATH_ERROR ? new UnsupportedPathError(path3) : e6;
    }
    if (pathErrorCheckOnly) {
      continue;
    }
    handlerData[j5] = handlers.map(([h6, paramCount]) => {
      const paramIndexMap = /* @__PURE__ */ Object.create(null);
      paramCount -= 1;
      for (; paramCount >= 0; paramCount--) {
        const [key, value] = paramAssoc[paramCount];
        paramIndexMap[key] = value;
      }
      return [h6, paramIndexMap];
    });
  }
  const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
  for (let i6 = 0, len = handlerData.length; i6 < len; i6++) {
    for (let j5 = 0, len2 = handlerData[i6].length; j5 < len2; j5++) {
      const map2 = handlerData[i6][j5]?.[1];
      if (!map2) {
        continue;
      }
      const keys = Object.keys(map2);
      for (let k5 = 0, len3 = keys.length; k5 < len3; k5++) {
        map2[keys[k5]] = paramReplacementMap[map2[keys[k5]]];
      }
    }
  }
  const handlerMap = [];
  for (const i6 in indexReplacementMap) {
    handlerMap[i6] = handlerData[indexReplacementMap[i6]];
  }
  return [regexp, handlerMap, staticMap];
}
function findMiddleware(middleware, path3) {
  if (!middleware) {
    return void 0;
  }
  for (const k5 of Object.keys(middleware).sort((a5, b5) => b5.length - a5.length)) {
    if (buildWildcardRegExp(k5).test(path3)) {
      return [...middleware[k5]];
    }
  }
  return void 0;
}
var emptyParam, nullMatcher, wildcardRegExpCache, _middleware, _routes, _RegExpRouter_instances, buildAllMatchers_fn, buildMatcher_fn, _a7, RegExpRouter;
var init_router2 = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/router.js"() {
    "use strict";
    init_router();
    init_url();
    init_node();
    init_trie();
    emptyParam = [];
    nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
    wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
    RegExpRouter = (_a7 = class {
      constructor() {
        __privateAdd(this, _RegExpRouter_instances);
        __publicField(this, "name", "RegExpRouter");
        __privateAdd(this, _middleware);
        __privateAdd(this, _routes);
        __privateSet(this, _middleware, { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) });
        __privateSet(this, _routes, { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) });
      }
      add(method, path3, handler) {
        const middleware = __privateGet(this, _middleware);
        const routes = __privateGet(this, _routes);
        if (!middleware || !routes) {
          throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
        }
        if (!middleware[method]) {
          ;
          [middleware, routes].forEach((handlerMap) => {
            handlerMap[method] = /* @__PURE__ */ Object.create(null);
            Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p5) => {
              handlerMap[method][p5] = [...handlerMap[METHOD_NAME_ALL][p5]];
            });
          });
        }
        if (path3 === "/*") {
          path3 = "*";
        }
        const paramCount = (path3.match(/\/:/g) || []).length;
        if (/\*$/.test(path3)) {
          const re = buildWildcardRegExp(path3);
          if (method === METHOD_NAME_ALL) {
            Object.keys(middleware).forEach((m6) => {
              middleware[m6][path3] ||= findMiddleware(middleware[m6], path3) || findMiddleware(middleware[METHOD_NAME_ALL], path3) || [];
            });
          } else {
            middleware[method][path3] ||= findMiddleware(middleware[method], path3) || findMiddleware(middleware[METHOD_NAME_ALL], path3) || [];
          }
          Object.keys(middleware).forEach((m6) => {
            if (method === METHOD_NAME_ALL || method === m6) {
              Object.keys(middleware[m6]).forEach((p5) => {
                re.test(p5) && middleware[m6][p5].push([handler, paramCount]);
              });
            }
          });
          Object.keys(routes).forEach((m6) => {
            if (method === METHOD_NAME_ALL || method === m6) {
              Object.keys(routes[m6]).forEach(
                (p5) => re.test(p5) && routes[m6][p5].push([handler, paramCount])
              );
            }
          });
          return;
        }
        const paths = checkOptionalParameter(path3) || [path3];
        for (let i6 = 0, len = paths.length; i6 < len; i6++) {
          const path22 = paths[i6];
          Object.keys(routes).forEach((m6) => {
            if (method === METHOD_NAME_ALL || method === m6) {
              routes[m6][path22] ||= [
                ...findMiddleware(middleware[m6], path22) || findMiddleware(middleware[METHOD_NAME_ALL], path22) || []
              ];
              routes[m6][path22].push([handler, paramCount - len + i6 + 1]);
            }
          });
        }
      }
      match(method, path3) {
        clearWildcardRegExpCache();
        const matchers = __privateMethod(this, _RegExpRouter_instances, buildAllMatchers_fn).call(this);
        this.match = (method2, path22) => {
          const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
          const staticMatch = matcher[2][path22];
          if (staticMatch) {
            return staticMatch;
          }
          const match2 = path22.match(matcher[0]);
          if (!match2) {
            return [[], emptyParam];
          }
          const index6 = match2.indexOf("", 1);
          return [matcher[1][index6], match2];
        };
        return this.match(method, path3);
      }
    }, _middleware = new WeakMap(), _routes = new WeakMap(), _RegExpRouter_instances = new WeakSet(), buildAllMatchers_fn = function() {
      const matchers = /* @__PURE__ */ Object.create(null);
      Object.keys(__privateGet(this, _routes)).concat(Object.keys(__privateGet(this, _middleware))).forEach((method) => {
        matchers[method] ||= __privateMethod(this, _RegExpRouter_instances, buildMatcher_fn).call(this, method);
      });
      __privateSet(this, _middleware, __privateSet(this, _routes, void 0));
      return matchers;
    }, buildMatcher_fn = function(method) {
      const routes = [];
      let hasOwnRoute = method === METHOD_NAME_ALL;
      [__privateGet(this, _middleware), __privateGet(this, _routes)].forEach((r6) => {
        const ownRoute = r6[method] ? Object.keys(r6[method]).map((path3) => [path3, r6[method][path3]]) : [];
        if (ownRoute.length !== 0) {
          hasOwnRoute ||= true;
          routes.push(...ownRoute);
        } else if (method !== METHOD_NAME_ALL) {
          routes.push(
            ...Object.keys(r6[METHOD_NAME_ALL]).map((path3) => [path3, r6[METHOD_NAME_ALL][path3]])
          );
        }
      });
      if (!hasOwnRoute) {
        return null;
      } else {
        return buildMatcherFromPreprocessedRoutes(routes);
      }
    }, _a7);
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/index.js
var init_reg_exp_router = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/index.js"() {
    "use strict";
    init_router2();
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/router.js
var _routers, _routes2, _a8, SmartRouter;
var init_router3 = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/router.js"() {
    "use strict";
    init_router();
    SmartRouter = (_a8 = class {
      constructor(init2) {
        __publicField(this, "name", "SmartRouter");
        __privateAdd(this, _routers, []);
        __privateAdd(this, _routes2, []);
        __privateSet(this, _routers, init2.routers);
      }
      add(method, path3, handler) {
        if (!__privateGet(this, _routes2)) {
          throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
        }
        __privateGet(this, _routes2).push([method, path3, handler]);
      }
      match(method, path3) {
        if (!__privateGet(this, _routes2)) {
          throw new Error("Fatal error");
        }
        const routers = __privateGet(this, _routers);
        const routes = __privateGet(this, _routes2);
        const len = routers.length;
        let i6 = 0;
        let res;
        for (; i6 < len; i6++) {
          const router = routers[i6];
          try {
            for (let i22 = 0, len2 = routes.length; i22 < len2; i22++) {
              router.add(...routes[i22]);
            }
            res = router.match(method, path3);
          } catch (e6) {
            if (e6 instanceof UnsupportedPathError) {
              continue;
            }
            throw e6;
          }
          this.match = router.match.bind(router);
          __privateSet(this, _routers, [router]);
          __privateSet(this, _routes2, void 0);
          break;
        }
        if (i6 === len) {
          throw new Error("Fatal error");
        }
        this.name = `SmartRouter + ${this.activeRouter.name}`;
        return res;
      }
      get activeRouter() {
        if (__privateGet(this, _routes2) || __privateGet(this, _routers).length !== 1) {
          throw new Error("No active router has been determined yet.");
        }
        return __privateGet(this, _routers)[0];
      }
    }, _routers = new WeakMap(), _routes2 = new WeakMap(), _a8);
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/index.js
var init_smart_router = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/index.js"() {
    "use strict";
    init_router3();
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/node.js
var emptyParams, _methods, _children2, _patterns, _order, _params, _Node_instances, getHandlerSets_fn, _a9, Node2;
var init_node2 = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/node.js"() {
    "use strict";
    init_router();
    init_url();
    emptyParams = /* @__PURE__ */ Object.create(null);
    Node2 = (_a9 = class {
      constructor(method, handler, children) {
        __privateAdd(this, _Node_instances);
        __privateAdd(this, _methods);
        __privateAdd(this, _children2);
        __privateAdd(this, _patterns);
        __privateAdd(this, _order, 0);
        __privateAdd(this, _params, emptyParams);
        __privateSet(this, _children2, children || /* @__PURE__ */ Object.create(null));
        __privateSet(this, _methods, []);
        if (method && handler) {
          const m6 = /* @__PURE__ */ Object.create(null);
          m6[method] = { handler, possibleKeys: [], score: 0 };
          __privateSet(this, _methods, [m6]);
        }
        __privateSet(this, _patterns, []);
      }
      insert(method, path3, handler) {
        __privateSet(this, _order, ++__privateWrapper(this, _order)._);
        let curNode = this;
        const parts = splitRoutingPath(path3);
        const possibleKeys = [];
        for (let i6 = 0, len = parts.length; i6 < len; i6++) {
          const p5 = parts[i6];
          const nextP = parts[i6 + 1];
          const pattern = getPattern(p5, nextP);
          const key = Array.isArray(pattern) ? pattern[0] : p5;
          if (Object.keys(__privateGet(curNode, _children2)).includes(key)) {
            curNode = __privateGet(curNode, _children2)[key];
            const pattern2 = getPattern(p5, nextP);
            if (pattern2) {
              possibleKeys.push(pattern2[1]);
            }
            continue;
          }
          __privateGet(curNode, _children2)[key] = new Node2();
          if (pattern) {
            __privateGet(curNode, _patterns).push(pattern);
            possibleKeys.push(pattern[1]);
          }
          curNode = __privateGet(curNode, _children2)[key];
        }
        const m6 = /* @__PURE__ */ Object.create(null);
        const handlerSet = {
          handler,
          possibleKeys: possibleKeys.filter((v6, i6, a5) => a5.indexOf(v6) === i6),
          score: __privateGet(this, _order)
        };
        m6[method] = handlerSet;
        __privateGet(curNode, _methods).push(m6);
        return curNode;
      }
      search(method, path3) {
        const handlerSets = [];
        __privateSet(this, _params, emptyParams);
        const curNode = this;
        let curNodes = [curNode];
        const parts = splitPath(path3);
        const curNodesQueue = [];
        for (let i6 = 0, len = parts.length; i6 < len; i6++) {
          const part = parts[i6];
          const isLast = i6 === len - 1;
          const tempNodes = [];
          for (let j5 = 0, len2 = curNodes.length; j5 < len2; j5++) {
            const node = curNodes[j5];
            const nextNode = __privateGet(node, _children2)[part];
            if (nextNode) {
              __privateSet(nextNode, _params, __privateGet(node, _params));
              if (isLast) {
                if (__privateGet(nextNode, _children2)["*"]) {
                  handlerSets.push(
                    ...__privateMethod(this, _Node_instances, getHandlerSets_fn).call(this, __privateGet(nextNode, _children2)["*"], method, __privateGet(node, _params))
                  );
                }
                handlerSets.push(...__privateMethod(this, _Node_instances, getHandlerSets_fn).call(this, nextNode, method, __privateGet(node, _params)));
              } else {
                tempNodes.push(nextNode);
              }
            }
            for (let k5 = 0, len3 = __privateGet(node, _patterns).length; k5 < len3; k5++) {
              const pattern = __privateGet(node, _patterns)[k5];
              const params = __privateGet(node, _params) === emptyParams ? {} : { ...__privateGet(node, _params) };
              if (pattern === "*") {
                const astNode = __privateGet(node, _children2)["*"];
                if (astNode) {
                  handlerSets.push(...__privateMethod(this, _Node_instances, getHandlerSets_fn).call(this, astNode, method, __privateGet(node, _params)));
                  __privateSet(astNode, _params, params);
                  tempNodes.push(astNode);
                }
                continue;
              }
              if (part === "") {
                continue;
              }
              const [key, name, matcher] = pattern;
              const child = __privateGet(node, _children2)[key];
              const restPathString = parts.slice(i6).join("/");
              if (matcher instanceof RegExp) {
                const m6 = matcher.exec(restPathString);
                if (m6) {
                  params[name] = m6[0];
                  handlerSets.push(...__privateMethod(this, _Node_instances, getHandlerSets_fn).call(this, child, method, __privateGet(node, _params), params));
                  if (Object.keys(__privateGet(child, _children2)).length) {
                    __privateSet(child, _params, params);
                    const componentCount = m6[0].match(/\//)?.length ?? 0;
                    const targetCurNodes = curNodesQueue[componentCount] ||= [];
                    targetCurNodes.push(child);
                  }
                  continue;
                }
              }
              if (matcher === true || matcher.test(part)) {
                params[name] = part;
                if (isLast) {
                  handlerSets.push(...__privateMethod(this, _Node_instances, getHandlerSets_fn).call(this, child, method, params, __privateGet(node, _params)));
                  if (__privateGet(child, _children2)["*"]) {
                    handlerSets.push(
                      ...__privateMethod(this, _Node_instances, getHandlerSets_fn).call(this, __privateGet(child, _children2)["*"], method, params, __privateGet(node, _params))
                    );
                  }
                } else {
                  __privateSet(child, _params, params);
                  tempNodes.push(child);
                }
              }
            }
          }
          curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
        }
        if (handlerSets.length > 1) {
          handlerSets.sort((a5, b5) => {
            return a5.score - b5.score;
          });
        }
        return [handlerSets.map(({ handler, params }) => [handler, params])];
      }
    }, _methods = new WeakMap(), _children2 = new WeakMap(), _patterns = new WeakMap(), _order = new WeakMap(), _params = new WeakMap(), _Node_instances = new WeakSet(), getHandlerSets_fn = function(node, method, nodeParams, params) {
      const handlerSets = [];
      for (let i6 = 0, len = __privateGet(node, _methods).length; i6 < len; i6++) {
        const m6 = __privateGet(node, _methods)[i6];
        const handlerSet = m6[method] || m6[METHOD_NAME_ALL];
        const processedSet = {};
        if (handlerSet !== void 0) {
          handlerSet.params = /* @__PURE__ */ Object.create(null);
          handlerSets.push(handlerSet);
          if (nodeParams !== emptyParams || params && params !== emptyParams) {
            for (let i22 = 0, len2 = handlerSet.possibleKeys.length; i22 < len2; i22++) {
              const key = handlerSet.possibleKeys[i22];
              const processed = processedSet[handlerSet.score];
              handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
              processedSet[handlerSet.score] = true;
            }
          }
        }
      }
      return handlerSets;
    }, _a9);
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/router.js
var _node, _a10, TrieRouter;
var init_router4 = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/router.js"() {
    "use strict";
    init_url();
    init_node2();
    TrieRouter = (_a10 = class {
      constructor() {
        __publicField(this, "name", "TrieRouter");
        __privateAdd(this, _node);
        __privateSet(this, _node, new Node2());
      }
      add(method, path3, handler) {
        const results = checkOptionalParameter(path3);
        if (results) {
          for (let i6 = 0, len = results.length; i6 < len; i6++) {
            __privateGet(this, _node).insert(method, results[i6], handler);
          }
          return;
        }
        __privateGet(this, _node).insert(method, path3, handler);
      }
      match(method, path3) {
        return __privateGet(this, _node).search(method, path3);
      }
    }, _node = new WeakMap(), _a10);
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/index.js
var init_trie_router = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/index.js"() {
    "use strict";
    init_router4();
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono.js
var Hono2;
var init_hono = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono.js"() {
    "use strict";
    init_hono_base();
    init_reg_exp_router();
    init_smart_router();
    init_trie_router();
    Hono2 = class extends Hono {
      constructor(options = {}) {
        super(options);
        this.router = options.router ?? new SmartRouter({
          routers: [new RegExpRouter(), new TrieRouter()]
        });
      }
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/index.js
var init_dist2 = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/index.js"() {
    "use strict";
    init_hono();
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/compress.js
var COMPRESSIBLE_CONTENT_TYPE_REGEX;
var init_compress = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/compress.js"() {
    "use strict";
    COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/compress/index.js
var ENCODING_TYPES, cacheControlNoTransformRegExp, compress, shouldCompress, shouldTransform;
var init_compress2 = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/compress/index.js"() {
    "use strict";
    init_compress();
    ENCODING_TYPES = ["gzip", "deflate"];
    cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/i;
    compress = (options) => {
      const threshold = options?.threshold ?? 1024;
      return async function compress2(ctx, next) {
        await next();
        const contentLength = ctx.res.headers.get("Content-Length");
        if (ctx.res.headers.has("Content-Encoding") || ctx.res.headers.has("Transfer-Encoding") || ctx.req.method === "HEAD" || contentLength && Number(contentLength) < threshold || !shouldCompress(ctx.res) || !shouldTransform(ctx.res)) {
          return;
        }
        const accepted = ctx.req.header("Accept-Encoding");
        const encoding = options?.encoding ?? ENCODING_TYPES.find((encoding2) => accepted?.includes(encoding2));
        if (!encoding || !ctx.res.body) {
          return;
        }
        const stream = new CompressionStream(encoding);
        ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res);
        ctx.res.headers.delete("Content-Length");
        ctx.res.headers.set("Content-Encoding", encoding);
      };
    };
    shouldCompress = (res) => {
      const type = res.headers.get("Content-Type");
      return type && COMPRESSIBLE_CONTENT_TYPE_REGEX.test(type);
    };
    shouldTransform = (res) => {
      const cacheControl = res.headers.get("Cache-Control");
      return !cacheControl || !cacheControlNoTransformRegExp.test(cacheControl);
    };
  }
});

// ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/cors/index.js
var cors;
var init_cors = __esm({
  "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/cors/index.js"() {
    "use strict";
    cors = (options) => {
      const defaults2 = {
        origin: "*",
        allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
        allowHeaders: [],
        exposeHeaders: []
      };
      const opts = {
        ...defaults2,
        ...options
      };
      const findAllowOrigin = ((optsOrigin) => {
        if (typeof optsOrigin === "string") {
          if (optsOrigin === "*") {
            return () => optsOrigin;
          } else {
            return (origin) => optsOrigin === origin ? origin : null;
          }
        } else if (typeof optsOrigin === "function") {
          return optsOrigin;
        } else {
          return (origin) => optsOrigin.includes(origin) ? origin : null;
        }
      })(opts.origin);
      return async function cors2(c5, next) {
        function set(key, value) {
          c5.res.headers.set(key, value);
        }
        const allowOrigin = findAllowOrigin(c5.req.header("origin") || "", c5);
        if (allowOrigin) {
          set("Access-Control-Allow-Origin", allowOrigin);
        }
        if (opts.origin !== "*") {
          const existingVary = c5.req.header("Vary");
          if (existingVary) {
            set("Vary", existingVary);
          } else {
            set("Vary", "Origin");
          }
        }
        if (opts.credentials) {
          set("Access-Control-Allow-Credentials", "true");
        }
        if (opts.exposeHeaders?.length) {
          set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
        }
        if (c5.req.method === "OPTIONS") {
          if (opts.maxAge != null) {
            set("Access-Control-Max-Age", opts.maxAge.toString());
          }
          if (opts.allowMethods?.length) {
            set("Access-Control-Allow-Methods", opts.allowMethods.join(","));
          }
          let headers = opts.allowHeaders;
          if (!headers?.length) {
            const requestHeaders = c5.req.header("Access-Control-Request-Headers");
            if (requestHeaders) {
              headers = requestHeaders.split(/\s*,\s*/);
            }
          }
          if (headers?.length) {
            set("Access-Control-Allow-Headers", headers.join(","));
            c5.res.headers.append("Vary", "Access-Control-Request-Headers");
          }
          c5.res.headers.delete("Content-Length");
          c5.res.headers.delete("Content-Type");
          return new Response(null, {
            headers: c5.res.headers,
            status: 204,
            statusText: "No Content"
          });
        }
        await next();
      };
    };
  }
});

// ../node_modules/.pnpm/data-uri-to-buffer@4.0.1/node_modules/data-uri-to-buffer/dist/index.js
function dataUriToBuffer(uri) {
  if (!/^data:/i.test(uri)) {
    throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');
  }
  uri = uri.replace(/\r?\n/g, "");
  const firstComma = uri.indexOf(",");
  if (firstComma === -1 || firstComma <= 4) {
    throw new TypeError("malformed data: URI");
  }
  const meta = uri.substring(5, firstComma).split(";");
  let charset = "";
  let base64 = false;
  const type = meta[0] || "text/plain";
  let typeFull = type;
  for (let i6 = 1; i6 < meta.length; i6++) {
    if (meta[i6] === "base64") {
      base64 = true;
    } else if (meta[i6]) {
      typeFull += `;${meta[i6]}`;
      if (meta[i6].indexOf("charset=") === 0) {
        charset = meta[i6].substring(8);
      }
    }
  }
  if (!meta[0] && !charset.length) {
    typeFull += ";charset=US-ASCII";
    charset = "US-ASCII";
  }
  const encoding = base64 ? "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_dist3 = __esm({
  "../node_modules/.pnpm/data-uri-to-buffer@4.0.1/node_modules/data-uri-to-buffer/dist/index.js"() {
    "use strict";
    dist_default = dataUriToBuffer;
  }
});

// ../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js
var require_ponyfill_es2018 = __commonJS({
  "../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js"(exports2, module2) {
    "use strict";
    (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(x5) {
        return typeof x5 === "object" && x5 !== null || typeof x5 === "function";
      }
      const rethrowAssertionErrorRejection = noop2;
      function setFunctionName(fn, name) {
        try {
          Object.defineProperty(fn, "name", {
            value: name,
            configurable: true
          });
        } catch (_a16) {
        }
      }
      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((resolve) => resolve(value));
      }
      function promiseRejectedWith(reason) {
        return originalPromiseReject(reason);
      }
      function PerformPromiseThen(promise, onFulfilled, onRejected) {
        return originalPromiseThen.call(promise, onFulfilled, onRejected);
      }
      function uponPromise(promise, onFulfilled, onRejected) {
        PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), void 0, rethrowAssertionErrorRejection);
      }
      function uponFulfillment(promise, onFulfilled) {
        uponPromise(promise, onFulfilled);
      }
      function uponRejection(promise, onRejected) {
        uponPromise(promise, void 0, onRejected);
      }
      function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {
        return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);
      }
      function setPromiseIsHandledToTrue(promise) {
        PerformPromiseThen(promise, 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(F3, V, args) {
        if (typeof F3 !== "function") {
          throw new TypeError("Argument is not a function");
        }
        return Function.prototype.apply.call(F3, V, args);
      }
      function promiseCall(F3, V, args) {
        try {
          return promiseResolvedWith(reflectCall(F3, 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 i6 = this._cursor;
          let node = this._front;
          let elements = node._elements;
          while (i6 !== elements.length || node._next !== void 0) {
            if (i6 === elements.length) {
              node = node._next;
              elements = node._elements;
              i6 = 0;
              if (elements.length === 0) {
                break;
              }
            }
            callback(elements[i6]);
            ++i6;
          }
        }
        // Return the element that would be returned if shift() was called now,
        // without modifying the queue.
        peek() {
          const front = this._front;
          const cursor = this._cursor;
          return front._elements[cursor];
        }
      }
      const AbortSteps = Symbol("[[AbortSteps]]");
      const ErrorSteps = Symbol("[[ErrorSteps]]");
      const CancelSteps = Symbol("[[CancelSteps]]");
      const PullSteps = Symbol("[[PullSteps]]");
      const ReleaseSteps = Symbol("[[ReleaseSteps]]");
      function ReadableStreamReaderGenericInitialize(reader, 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((resolve, reject) => {
          reader._closedPromise_resolve = resolve;
          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(x5) {
        return typeof x5 === "number" && isFinite(x5);
      };
      const MathTrunc = Math.trunc || function(v6) {
        return v6 < 0 ? Math.ceil(v6) : Math.floor(v6);
      };
      function isDictionary(x5) {
        return typeof x5 === "object" || typeof x5 === "function";
      }
      function assertDictionary(obj, context) {
        if (obj !== void 0 && !isDictionary(obj)) {
          throw new TypeError(`${context} is not an object.`);
        }
      }
      function assertFunction(x5, context) {
        if (typeof x5 !== "function") {
          throw new TypeError(`${context} is not a function.`);
        }
      }
      function isObject(x5) {
        return typeof x5 === "object" && x5 !== null || typeof x5 === "function";
      }
      function assertObject(x5, context) {
        if (!isObject(x5)) {
          throw new TypeError(`${context} is not an object.`);
        }
      }
      function assertRequiredArgument(x5, position, context) {
        if (x5 === void 0) {
          throw new TypeError(`Parameter ${position} is required in '${context}'.`);
        }
      }
      function assertRequiredField(x5, field, context) {
        if (x5 === void 0) {
          throw new TypeError(`${field} is required in '${context}'.`);
        }
      }
      function convertUnrestrictedDouble(value) {
        return Number(value);
      }
      function censorNegativeZero(x5) {
        return x5 === 0 ? 0 : x5;
      }
      function integerPart(x5) {
        return censorNegativeZero(MathTrunc(x5));
      }
      function convertUnsignedLongLongWithEnforceRange(value, context) {
        const lowerBound = 0;
        const upperBound = Number.MAX_SAFE_INTEGER;
        let x5 = Number(value);
        x5 = censorNegativeZero(x5);
        if (!NumberIsFinite(x5)) {
          throw new TypeError(`${context} is not a finite number`);
        }
        x5 = integerPart(x5);
        if (x5 < lowerBound || x5 > upperBound) {
          throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);
        }
        if (!NumberIsFinite(x5) || x5 === 0) {
          return 0;
        }
        return x5;
      }
      function assertReadableStream(x5, context) {
        if (!IsReadableStream(x5)) {
          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 promise = newPromise((resolve, reject) => {
            resolvePromise = resolve;
            rejectPromise = reject;
          });
          const readRequest = {
            _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }),
            _closeSteps: () => resolvePromise({ value: void 0, done: true }),
            _errorSteps: (e6) => rejectPromise(e6)
          };
          ReadableStreamDefaultReaderRead(this, readRequest);
          return promise;
        }
        /**
         * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
         * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
         * from now on; otherwise, the reader will appear closed.
         *
         * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
         * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
         * do so will throw a `TypeError` and leave the reader locked to the stream.
         */
        releaseLock() {
          if (!IsReadableStreamDefaultReader(this)) {
            throw defaultReaderBrandCheckException("releaseLock");
          }
          if (this._ownerReadableStream === void 0) {
            return;
          }
          ReadableStreamDefaultReaderRelease(this);
        }
      }
      Object.defineProperties(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(x5) {
        if (!typeIsObject(x5)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x5, "_readRequests")) {
          return false;
        }
        return x5 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 e6 = new TypeError("Reader was released");
        ReadableStreamDefaultReaderErrorReadRequests(reader, e6);
      }
      function ReadableStreamDefaultReaderErrorReadRequests(reader, e6) {
        const readRequests = reader._readRequests;
        reader._readRequests = new SimpleQueue();
        readRequests.forEach((readRequest) => {
          readRequest._errorSteps(e6);
        });
      }
      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 promise = newPromise((resolve, reject) => {
            resolvePromise = resolve;
            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 promise;
        }
        _returnSteps(value) {
          if (this._isFinished) {
            return Promise.resolve({ value, done: true });
          }
          this._isFinished = true;
          const reader = this._reader;
          if (!this._preventCancel) {
            const result = ReadableStreamReaderGenericCancel(reader, value);
            ReadableStreamReaderGenericRelease(reader);
            return transformPromiseWith(result, () => ({ value, done: true }));
          }
          ReadableStreamReaderGenericRelease(reader);
          return promiseResolvedWith({ value, done: true });
        }
      }
      const ReadableStreamAsyncIteratorPrototype = {
        next() {
          if (!IsReadableStreamAsyncIterator(this)) {
            return promiseRejectedWith(streamAsyncIteratorBrandCheckException("next"));
          }
          return this._asyncIteratorImpl.next();
        },
        return(value) {
          if (!IsReadableStreamAsyncIterator(this)) {
            return promiseRejectedWith(streamAsyncIteratorBrandCheckException("return"));
          }
          return this._asyncIteratorImpl.return(value);
        }
      };
      Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);
      function AcquireReadableStreamAsyncIterator(stream, preventCancel) {
        const reader = AcquireReadableStreamDefaultReader(stream);
        const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);
        const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);
        iterator._asyncIteratorImpl = impl;
        return iterator;
      }
      function IsReadableStreamAsyncIterator(x5) {
        if (!typeIsObject(x5)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x5, "_asyncIteratorImpl")) {
          return false;
        }
        try {
          return x5._asyncIteratorImpl instanceof ReadableStreamAsyncIteratorImpl;
        } catch (_a16) {
          return false;
        }
      }
      function streamAsyncIteratorBrandCheckException(name) {
        return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);
      }
      const NumberIsNaN = Number.isNaN || function(x5) {
        return x5 !== x5;
      };
      var _a15, _b, _c;
      function CreateArrayFromList(elements) {
        return elements.slice();
      }
      function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n5) {
        new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n5), 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 = (_a15 = Symbol.asyncIterator) !== null && _a15 !== void 0 ? _a15 : (_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(v6) {
        if (typeof v6 !== "number") {
          return false;
        }
        if (NumberIsNaN(v6)) {
          return false;
        }
        if (v6 < 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(container) {
        const pair = container._queue.shift();
        container._queueTotalSize -= pair.size;
        if (container._queueTotalSize < 0) {
          container._queueTotalSize = 0;
        }
        return pair.value;
      }
      function EnqueueValueWithSize(container, value, size) {
        if (!IsNonNegativeNumber(size) || size === Infinity) {
          throw new RangeError("Size must be a finite, non-NaN, non-negative number.");
        }
        container._queue.push({ value, size });
        container._queueTotalSize += size;
      }
      function PeekQueueValue(container) {
        const pair = container._queue.peek();
        return pair.value;
      }
      function ResetQueue(container) {
        container._queue = new SimpleQueue();
        container._queueTotalSize = 0;
      }
      function isDataViewConstructor(ctor) {
        return ctor === DataView;
      }
      function isDataView(view5) {
        return isDataViewConstructor(view5.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(view5) {
          if (!IsReadableStreamBYOBRequest(this)) {
            throw byobRequestBrandCheckException("respondWithNewView");
          }
          assertRequiredArgument(view5, 1, "respondWithNewView");
          if (!ArrayBuffer.isView(view5)) {
            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(view5.buffer)) {
            throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");
          }
          ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view5);
        }
      }
      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 state2 = this._controlledReadableByteStream._state;
          if (state2 !== "readable") {
            throw new TypeError(`The stream (in ${state2} 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 state2 = this._controlledReadableByteStream._state;
          if (state2 !== "readable") {
            throw new TypeError(`The stream (in ${state2} 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(e6 = void 0) {
          if (!IsReadableByteStreamController(this)) {
            throw byteStreamControllerBrandCheckException("error");
          }
          ReadableByteStreamControllerError(this, e6);
        }
        /** @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(x5) {
        if (!typeIsObject(x5)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x5, "_controlledReadableByteStream")) {
          return false;
        }
        return x5 instanceof ReadableByteStreamController;
      }
      function IsReadableStreamBYOBRequest(x5) {
        if (!typeIsObject(x5)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x5, "_associatedReadableByteStreamController")) {
          return false;
        }
        return x5 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;
        }, (e6) => {
          ReadableByteStreamControllerError(controller, e6);
          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, view5, min, readIntoRequest) {
        const stream = controller._controlledReadableByteStream;
        const ctor = view5.constructor;
        const elementSize = arrayBufferViewElementSize(ctor);
        const { byteOffset, byteLength } = view5;
        const minimumFill = min * elementSize;
        let buffer;
        try {
          buffer = TransferArrayBuffer(view5.buffer);
        } catch (e6) {
          readIntoRequest._errorSteps(e6);
          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 e6 = new TypeError("Insufficient bytes to fill elements in the given buffer");
            ReadableByteStreamControllerError(controller, e6);
            readIntoRequest._errorSteps(e6);
            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 state2 = controller._controlledReadableByteStream._state;
        if (state2 === "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 e6 = new TypeError("Insufficient bytes to fill elements in the given buffer");
            ReadableByteStreamControllerError(controller, e6);
            throw e6;
          }
        }
        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, e6) {
        const stream = controller._controlledReadableByteStream;
        if (stream._state !== "readable") {
          return;
        }
        ReadableByteStreamControllerClearPendingPullIntos(controller);
        ResetQueue(controller);
        ReadableByteStreamControllerClearAlgorithms(controller);
        ReadableStreamError(stream, e6);
      }
      function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) {
        const entry = controller._queue.shift();
        controller._queueTotalSize -= entry.byteLength;
        ReadableByteStreamControllerHandleQueueDrain(controller);
        const view5 = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
        readRequest._chunkSteps(view5);
      }
      function ReadableByteStreamControllerGetBYOBRequest(controller) {
        if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {
          const firstDescriptor = controller._pendingPullIntos.peek();
          const view5 = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
          const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);
          SetUpReadableStreamBYOBRequest(byobRequest, controller, view5);
          controller._byobRequest = byobRequest;
        }
        return controller._byobRequest;
      }
      function ReadableByteStreamControllerGetDesiredSize(controller) {
        const state2 = controller._controlledReadableByteStream._state;
        if (state2 === "errored") {
          return null;
        }
        if (state2 === "closed") {
          return 0;
        }
        return controller._strategyHWM - controller._queueTotalSize;
      }
      function ReadableByteStreamControllerRespond(controller, bytesWritten) {
        const firstDescriptor = controller._pendingPullIntos.peek();
        const state2 = controller._controlledReadableByteStream._state;
        if (state2 === "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, view5) {
        const firstDescriptor = controller._pendingPullIntos.peek();
        const state2 = controller._controlledReadableByteStream._state;
        if (state2 === "closed") {
          if (view5.byteLength !== 0) {
            throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream");
          }
        } else {
          if (view5.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 !== view5.byteOffset) {
          throw new RangeError("The region specified by view does not match byobRequest");
        }
        if (firstDescriptor.bufferByteLength !== view5.buffer.byteLength) {
          throw new RangeError("The buffer of view has different capacity than byobRequest");
        }
        if (firstDescriptor.bytesFilled + view5.byteLength > firstDescriptor.byteLength) {
          throw new RangeError("The region specified by view is larger than byobRequest");
        }
        const viewByteLength = view5.byteLength;
        firstDescriptor.buffer = TransferArrayBuffer(view5.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;
        }, (r6) => {
          ReadableByteStreamControllerError(controller, r6);
          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(request2, controller, view5) {
        request2._associatedReadableByteStreamController = controller;
        request2._view = view5;
      }
      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 _a16;
        assertDictionary(options, context);
        const min = (_a16 = options === null || options === void 0 ? void 0 : options.min) !== null && _a16 !== void 0 ? _a16 : 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(view5, rawOptions = {}) {
          if (!IsReadableStreamBYOBReader(this)) {
            return promiseRejectedWith(byobReaderBrandCheckException("read"));
          }
          if (!ArrayBuffer.isView(view5)) {
            return promiseRejectedWith(new TypeError("view must be an array buffer view"));
          }
          if (view5.byteLength === 0) {
            return promiseRejectedWith(new TypeError("view must have non-zero byteLength"));
          }
          if (view5.buffer.byteLength === 0) {
            return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
          }
          if (IsDetachedBuffer(view5.buffer)) {
            return promiseRejectedWith(new TypeError("view's buffer has been detached"));
          }
          let options;
          try {
            options = convertByobReadOptions(rawOptions, "options");
          } catch (e6) {
            return promiseRejectedWith(e6);
          }
          const min = options.min;
          if (min === 0) {
            return promiseRejectedWith(new TypeError("options.min must be greater than 0"));
          }
          if (!isDataView(view5)) {
            if (min > view5.length) {
              return promiseRejectedWith(new RangeError("options.min must be less than or equal to view's length"));
            }
          } else if (min > view5.byteLength) {
            return promiseRejectedWith(new RangeError("options.min must be less than or equal to view's byteLength"));
          }
          if (this._ownerReadableStream === void 0) {
            return promiseRejectedWith(readerLockException("read from"));
          }
          let resolvePromise;
          let rejectPromise;
          const promise = newPromise((resolve, reject) => {
            resolvePromise = resolve;
            rejectPromise = reject;
          });
          const readIntoRequest = {
            _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }),
            _closeSteps: (chunk) => resolvePromise({ value: chunk, done: true }),
            _errorSteps: (e6) => rejectPromise(e6)
          };
          ReadableStreamBYOBReaderRead(this, view5, min, readIntoRequest);
          return promise;
        }
        /**
         * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
         * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
         * from now on; otherwise, the reader will appear closed.
         *
         * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
         * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
         * do so will throw a `TypeError` and leave the reader locked to the stream.
         */
        releaseLock() {
          if (!IsReadableStreamBYOBReader(this)) {
            throw byobReaderBrandCheckException("releaseLock");
          }
          if (this._ownerReadableStream === void 0) {
            return;
          }
          ReadableStreamBYOBReaderRelease(this);
        }
      }
      Object.defineProperties(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(x5) {
        if (!typeIsObject(x5)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x5, "_readIntoRequests")) {
          return false;
        }
        return x5 instanceof ReadableStreamBYOBReader;
      }
      function ReadableStreamBYOBReaderRead(reader, view5, min, readIntoRequest) {
        const stream = reader._ownerReadableStream;
        stream._disturbed = true;
        if (stream._state === "errored") {
          readIntoRequest._errorSteps(stream._storedError);
        } else {
          ReadableByteStreamControllerPullInto(stream._readableStreamController, view5, min, readIntoRequest);
        }
      }
      function ReadableStreamBYOBReaderRelease(reader) {
        ReadableStreamReaderGenericRelease(reader);
        const e6 = new TypeError("Reader was released");
        ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e6);
      }
      function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e6) {
        const readIntoRequests = reader._readIntoRequests;
        reader._readIntoRequests = new SimpleQueue();
        readIntoRequests.forEach((readIntoRequest) => {
          readIntoRequest._errorSteps(e6);
        });
      }
      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(init2, context) {
        assertDictionary(init2, context);
        const highWaterMark = init2 === null || init2 === void 0 ? void 0 : init2.highWaterMark;
        const size = init2 === null || init2 === void 0 ? void 0 : init2.size;
        return {
          highWaterMark: highWaterMark === void 0 ? void 0 : convertUnrestrictedDouble(highWaterMark),
          size: size === void 0 ? void 0 : convertQueuingStrategySize(size, `${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(x5, context) {
        if (!IsWritableStream(x5)) {
          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 (_a16) {
          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(x5) {
        if (!typeIsObject(x5)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x5, "_writableStreamController")) {
          return false;
        }
        return x5 instanceof WritableStream;
      }
      function IsWritableStreamLocked(stream) {
        if (stream._writer === void 0) {
          return false;
        }
        return true;
      }
      function WritableStreamAbort(stream, reason) {
        var _a16;
        if (stream._state === "closed" || stream._state === "errored") {
          return promiseResolvedWith(void 0);
        }
        stream._writableStreamController._abortReason = reason;
        (_a16 = stream._writableStreamController._abortController) === null || _a16 === void 0 ? void 0 : _a16.abort(reason);
        const state2 = stream._state;
        if (state2 === "closed" || state2 === "errored") {
          return promiseResolvedWith(void 0);
        }
        if (stream._pendingAbortRequest !== void 0) {
          return stream._pendingAbortRequest._promise;
        }
        let wasAlreadyErroring = false;
        if (state2 === "erroring") {
          wasAlreadyErroring = true;
          reason = void 0;
        }
        const promise = newPromise((resolve, reject) => {
          stream._pendingAbortRequest = {
            _promise: void 0,
            _resolve: resolve,
            _reject: reject,
            _reason: reason,
            _wasAlreadyErroring: wasAlreadyErroring
          };
        });
        stream._pendingAbortRequest._promise = promise;
        if (!wasAlreadyErroring) {
          WritableStreamStartErroring(stream, reason);
        }
        return promise;
      }
      function WritableStreamClose(stream) {
        const state2 = stream._state;
        if (state2 === "closed" || state2 === "errored") {
          return promiseRejectedWith(new TypeError(`The stream (in ${state2} state) is not in the writable state and cannot be closed`));
        }
        const promise = newPromise((resolve, reject) => {
          const closeRequest = {
            _resolve: resolve,
            _reject: reject
          };
          stream._closeRequest = closeRequest;
        });
        const writer = stream._writer;
        if (writer !== void 0 && stream._backpressure && state2 === "writable") {
          defaultWriterReadyPromiseResolve(writer);
        }
        WritableStreamDefaultControllerClose(stream._writableStreamController);
        return promise;
      }
      function WritableStreamAddWriteRequest(stream) {
        const promise = newPromise((resolve, reject) => {
          const writeRequest = {
            _resolve: resolve,
            _reject: reject
          };
          stream._writeRequests.push(writeRequest);
        });
        return promise;
      }
      function WritableStreamDealWithRejection(stream, error2) {
        const state2 = stream._state;
        if (state2 === "writable") {
          WritableStreamStartErroring(stream, error2);
          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 promise = stream._writableStreamController[AbortSteps](abortRequest._reason);
        uponPromise(promise, () => {
          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, error2) {
        stream._inFlightWriteRequest._reject(error2);
        stream._inFlightWriteRequest = void 0;
        WritableStreamDealWithRejection(stream, error2);
      }
      function WritableStreamFinishInFlightClose(stream) {
        stream._inFlightCloseRequest._resolve(void 0);
        stream._inFlightCloseRequest = void 0;
        const state2 = stream._state;
        if (state2 === "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, error2) {
        stream._inFlightCloseRequest._reject(error2);
        stream._inFlightCloseRequest = void 0;
        if (stream._pendingAbortRequest !== void 0) {
          stream._pendingAbortRequest._reject(error2);
          stream._pendingAbortRequest = void 0;
        }
        WritableStreamDealWithRejection(stream, error2);
      }
      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 state2 = stream._state;
          if (state2 === "writable") {
            if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {
              defaultWriterReadyPromiseInitialize(this);
            } else {
              defaultWriterReadyPromiseInitializeAsResolved(this);
            }
            defaultWriterClosedPromiseInitialize(this);
          } else if (state2 === "erroring") {
            defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);
            defaultWriterClosedPromiseInitialize(this);
          } else if (state2 === "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(x5) {
        if (!typeIsObject(x5)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x5, "_ownerWritableStream")) {
          return false;
        }
        return x5 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 state2 = stream._state;
        if (WritableStreamCloseQueuedOrInFlight(stream) || state2 === "closed") {
          return promiseResolvedWith(void 0);
        }
        if (state2 === "errored") {
          return promiseRejectedWith(stream._storedError);
        }
        return WritableStreamDefaultWriterClose(writer);
      }
      function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error2) {
        if (writer._closedPromiseState === "pending") {
          defaultWriterClosedPromiseReject(writer, error2);
        } else {
          defaultWriterClosedPromiseResetToRejected(writer, error2);
        }
      }
      function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error2) {
        if (writer._readyPromiseState === "pending") {
          defaultWriterReadyPromiseReject(writer, error2);
        } else {
          defaultWriterReadyPromiseResetToRejected(writer, error2);
        }
      }
      function WritableStreamDefaultWriterGetDesiredSize(writer) {
        const stream = writer._ownerWritableStream;
        const state2 = stream._state;
        if (state2 === "errored" || state2 === "erroring") {
          return null;
        }
        if (state2 === "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 state2 = stream._state;
        if (state2 === "errored") {
          return promiseRejectedWith(stream._storedError);
        }
        if (WritableStreamCloseQueuedOrInFlight(stream) || state2 === "closed") {
          return promiseRejectedWith(new TypeError("The stream is closing or closed and cannot be written to"));
        }
        if (state2 === "erroring") {
          return promiseRejectedWith(stream._storedError);
        }
        const promise = WritableStreamAddWriteRequest(stream);
        WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);
        return promise;
      }
      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(e6 = void 0) {
          if (!IsWritableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$2("error");
          }
          const state2 = this._controlledWritableStream._state;
          if (state2 !== "writable") {
            return;
          }
          WritableStreamDefaultControllerError(this, e6);
        }
        /** @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(x5) {
        if (!typeIsObject(x5)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x5, "_controlledWritableStream")) {
          return false;
        }
        return x5 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;
        }, (r6) => {
          controller._started = true;
          WritableStreamDealWithRejection(stream, r6);
          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 state2 = stream._state;
        if (state2 === "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, error2) {
        if (controller._controlledWritableStream._state === "writable") {
          WritableStreamDefaultControllerError(controller, error2);
        }
      }
      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 state2 = stream._state;
          DequeueValue(controller);
          if (!WritableStreamCloseQueuedOrInFlight(stream) && state2 === "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, error2) {
        const stream = controller._controlledWritableStream;
        WritableStreamDefaultControllerClearAlgorithms(controller);
        WritableStreamStartErroring(stream, error2);
      }
      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((resolve, reject) => {
          writer._closedPromise_resolve = resolve;
          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((resolve, reject) => {
          writer._readyPromise_resolve = resolve;
          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 (_a16) {
          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 DOMException3(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 DOMException2 = 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((resolve, reject) => {
          let abortAlgorithm;
          if (signal !== void 0) {
            abortAlgorithm = () => {
              const error2 = signal.reason !== void 0 ? signal.reason : new DOMException2("Aborted", "AbortError");
              const actions = [];
              if (!preventAbort) {
                actions.push(() => {
                  if (dest._state === "writable") {
                    return WritableStreamAbort(dest, error2);
                  }
                  return promiseResolvedWith(void 0);
                });
              }
              if (!preventCancel) {
                actions.push(() => {
                  if (source._state === "readable") {
                    return ReadableStreamCancel(source, error2);
                  }
                  return promiseResolvedWith(void 0);
                });
              }
              shutdownWithAction(() => Promise.all(actions.map((action) => action())), true, error2);
            };
            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, promise, action) {
            if (stream._state === "errored") {
              action(stream._storedError);
            } else {
              uponRejection(promise, action);
            }
          }
          function isOrBecomesClosed(stream, promise, action) {
            if (stream._state === "closed") {
              action();
            } else {
              uponFulfillment(promise, 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(), () => finalize(originalIsError, originalError), (newError) => finalize(true, newError));
              return null;
            }
          }
          function shutdown(isError, error2) {
            if (shuttingDown) {
              return;
            }
            shuttingDown = true;
            if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) {
              uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error2));
            } else {
              finalize(isError, error2);
            }
          }
          function finalize(isError, error2) {
            WritableStreamDefaultWriterRelease(writer);
            ReadableStreamReaderGenericRelease(reader);
            if (signal !== void 0) {
              signal.removeEventListener("abort", abortAlgorithm);
            }
            if (isError) {
              reject(error2);
            } else {
              resolve(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(e6 = void 0) {
          if (!IsReadableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$1("error");
          }
          ReadableStreamDefaultControllerError(this, e6);
        }
        /** @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(x5) {
        if (!typeIsObject(x5)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x5, "_controlledReadableStream")) {
          return false;
        }
        return x5 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;
        }, (e6) => {
          ReadableStreamDefaultControllerError(controller, e6);
          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, e6) {
        const stream = controller._controlledReadableStream;
        if (stream._state !== "readable") {
          return;
        }
        ResetQueue(controller);
        ReadableStreamDefaultControllerClearAlgorithms(controller);
        ReadableStreamError(stream, e6);
      }
      function ReadableStreamDefaultControllerGetDesiredSize(controller) {
        const state2 = controller._controlledReadableStream._state;
        if (state2 === "errored") {
          return null;
        }
        if (state2 === "closed") {
          return 0;
        }
        return controller._strategyHWM - controller._queueTotalSize;
      }
      function ReadableStreamDefaultControllerHasBackpressure(controller) {
        if (ReadableStreamDefaultControllerShouldCallPull(controller)) {
          return false;
        }
        return true;
      }
      function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {
        const state2 = controller._controlledReadableStream._state;
        if (!controller._closeRequested && state2 === "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;
        }, (r6) => {
          ReadableStreamDefaultControllerError(controller, r6);
          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((resolve) => {
          resolveCancelPromise = resolve;
        });
        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, (r6) => {
          ReadableStreamDefaultControllerError(branch1._readableStreamController, r6);
          ReadableStreamDefaultControllerError(branch2._readableStreamController, r6);
          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((resolve) => {
          resolveCancelPromise = resolve;
        });
        function forwardReaderError(thisReader) {
          uponRejection(thisReader._closedPromise, (r6) => {
            if (thisReader !== reader) {
              return null;
            }
            ReadableByteStreamControllerError(branch1._readableStreamController, r6);
            ReadableByteStreamControllerError(branch2._readableStreamController, r6);
            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(view5, 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, view5, 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 (e6) {
            return promiseRejectedWith(e6);
          }
          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 (e6) {
            return promiseRejectedWith(e6);
          }
          if (returnMethod === void 0) {
            return promiseResolvedWith(void 0);
          }
          let returnResult;
          try {
            returnResult = reflectCall(returnMethod, iterator, [reason]);
          } catch (e6) {
            return promiseRejectedWith(e6);
          }
          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 (e6) {
            return promiseRejectedWith(e6);
          }
          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 (e6) {
            return promiseRejectedWith(e6);
          }
        }
        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 transform = 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(transform.writable)) {
            throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");
          }
          const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
          setPromiseIsHandledToTrue(promise);
          return transform.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 (e6) {
            return promiseRejectedWith(e6);
          }
          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(x5) {
        if (!typeIsObject(x5)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x5, "_readableStreamController")) {
          return false;
        }
        return x5 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, e6) {
        stream._state = "errored";
        stream._storedError = e6;
        const reader = stream._reader;
        if (reader === void 0) {
          return;
        }
        defaultReaderClosedPromiseReject(reader, e6);
        if (IsReadableStreamDefaultReader(reader)) {
          ReadableStreamDefaultReaderErrorReadRequests(reader, e6);
        } else {
          ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e6);
        }
      }
      function streamBrandCheckException$1(name) {
        return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);
      }
      function convertQueuingStrategyInit(init2, context) {
        assertDictionary(init2, context);
        const highWaterMark = init2 === null || init2 === void 0 ? void 0 : init2.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(x5) {
        if (!typeIsObject(x5)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x5, "_byteLengthQueuingStrategyHighWaterMark")) {
          return false;
        }
        return x5 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(x5) {
        if (!typeIsObject(x5)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x5, "_countQueuingStrategyHighWaterMark")) {
          return false;
        }
        return x5 instanceof CountQueuingStrategy;
      }
      function convertTransformer(original, context) {
        assertDictionary(original, context);
        const cancel = original === null || original === void 0 ? void 0 : original.cancel;
        const flush2 = 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 transform = 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: flush2 === void 0 ? void 0 : convertTransformerFlushCallback(flush2, original, `${context} has member 'flush' that`),
          readableType,
          start: start === void 0 ? void 0 : convertTransformerStartCallback(start, original, `${context} has member 'start' that`),
          transform: transform === void 0 ? void 0 : convertTransformerTransformCallback(transform, 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 TransformStream2 {
        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((resolve) => {
            startPromise_resolve = resolve;
          });
          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(TransformStream2.prototype, {
        readable: { enumerable: true },
        writable: { enumerable: true }
      });
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(TransformStream2.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(x5) {
        if (!typeIsObject(x5)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x5, "_transformStreamController")) {
          return false;
        }
        return x5 instanceof TransformStream2;
      }
      function TransformStreamError(stream, e6) {
        ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e6);
        TransformStreamErrorWritableAndUnblockWrite(stream, e6);
      }
      function TransformStreamErrorWritableAndUnblockWrite(stream, e6) {
        TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
        WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e6);
        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((resolve) => {
          stream._backpressureChangePromise_resolve = resolve;
        });
        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(x5) {
        if (!typeIsObject(x5)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x5, "_controlledTransformStream")) {
          return false;
        }
        return x5 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 (e6) {
          TransformStreamErrorWritableAndUnblockWrite(stream, e6);
          throw stream._readable._storedError;
        }
        const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);
        if (backpressure !== stream._backpressure) {
          TransformStreamSetBackpressure(stream, true);
        }
      }
      function TransformStreamDefaultControllerError(controller, e6) {
        TransformStreamError(controller._controlledTransformStream, e6);
      }
      function TransformStreamDefaultControllerPerformTransform(controller, chunk) {
        const transformPromise = controller._transformAlgorithm(chunk);
        return transformPromiseWith(transformPromise, void 0, (r6) => {
          TransformStreamError(controller._controlledTransformStream, r6);
          throw r6;
        });
      }
      function TransformStreamDefaultControllerTerminate(controller) {
        const stream = controller._controlledTransformStream;
        const readableController = stream._readable._readableStreamController;
        ReadableStreamDefaultControllerClose(readableController);
        const error2 = new TypeError("TransformStream terminated");
        TransformStreamErrorWritableAndUnblockWrite(stream, error2);
      }
      function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {
        const controller = stream._transformStreamController;
        if (stream._backpressure) {
          const backpressureChangePromise = stream._backpressureChangePromise;
          return transformPromiseWith(backpressureChangePromise, () => {
            const writable = stream._writable;
            const state2 = writable._state;
            if (state2 === "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((resolve, reject) => {
          controller._finishPromise_resolve = resolve;
          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;
        }, (r6) => {
          ReadableStreamDefaultControllerError(readable._readableStreamController, r6);
          defaultControllerFinishPromiseReject(controller, r6);
          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((resolve, reject) => {
          controller._finishPromise_resolve = resolve;
          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;
        }, (r6) => {
          ReadableStreamDefaultControllerError(readable._readableStreamController, r6);
          defaultControllerFinishPromiseReject(controller, r6);
          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((resolve, reject) => {
          controller._finishPromise_resolve = resolve;
          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;
        }, (r6) => {
          WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r6);
          TransformStreamUnblockWrite(stream);
          defaultControllerFinishPromiseReject(controller, r6);
          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 = TransformStream2;
      exports3.TransformStreamDefaultController = TransformStreamDefaultController;
      exports3.WritableStream = WritableStream;
      exports3.WritableStreamDefaultController = WritableStreamDefaultController;
      exports3.WritableStreamDefaultWriter = WritableStreamDefaultWriter;
    });
  }
});

// ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/streams.cjs
var require_streams = __commonJS({
  "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/streams.cjs"() {
    "use strict";
    var POOL_SIZE2 = 65536;
    if (!globalThis.ReadableStream) {
      try {
        const process4 = require("process");
        const { emitWarning } = process4;
        try {
          process4.emitWarning = () => {
          };
          Object.assign(globalThis, require("stream/web"));
          process4.emitWarning = emitWarning;
        } catch (error2) {
          process4.emitWarning = emitWarning;
          throw error2;
        }
      } catch (error2) {
        Object.assign(globalThis, require_ponyfill_es2018());
      }
    }
    try {
      const { Blob: Blob3 } = require("buffer");
      if (Blob3 && !Blob3.prototype.stream) {
        Blob3.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 (error2) {
    }
  }
});

// ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/index.js
async function* toIterator(parts, clone2 = true) {
  for (const part of parts) {
    if ("stream" in part) {
      yield* (
        /** @type {AsyncIterableIterator<Uint8Array>} */
        part.stream()
      );
    } else if (ArrayBuffer.isView(part)) {
      if (clone2) {
        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, b5 = (
        /** @type {Blob} */
        part
      );
      while (position !== b5.size) {
        const chunk = b5.slice(position, Math.min(b5.size, position + POOL_SIZE));
        const buffer = await chunk.arrayBuffer();
        position += buffer.byteLength;
        yield new Uint8Array(buffer);
      }
    }
  }
}
var import_streams, POOL_SIZE, _parts, _type, _size, _endings, _a11, _Blob, Blob2, fetch_blob_default;
var init_fetch_blob = __esm({
  "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/index.js"() {
    "use strict";
    import_streams = __toESM(require_streams(), 1);
    POOL_SIZE = 65536;
    _Blob = (_a11 = class {
      /**
       * 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 = {}) {
        /** @type {Array.<(Blob|Uint8Array)>} */
        __privateAdd(this, _parts, []);
        __privateAdd(this, _type, "");
        __privateAdd(this, _size, 0);
        __privateAdd(this, _endings, "transparent");
        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 _a11) {
            part = element;
          } else {
            part = encoder.encode(`${element}`);
          }
          __privateSet(this, _size, __privateGet(this, _size) + (ArrayBuffer.isView(part) ? part.byteLength : part.size));
          __privateGet(this, _parts).push(part);
        }
        __privateSet(this, _endings, `${options.endings === void 0 ? "transparent" : options.endings}`);
        const type = options.type === void 0 ? "" : String(options.type);
        __privateSet(this, _type, /^[\x20-\x7E]*$/.test(type) ? type : "");
      }
      /**
       * The Blob interface's size property returns the
       * size of the Blob in bytes.
       */
      get size() {
        return __privateGet(this, _size);
      }
      /**
       * The type property of a Blob object returns the MIME type of the file.
       */
      get type() {
        return __privateGet(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(__privateGet(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(__privateGet(this, _parts), false)) {
          data.set(chunk, offset);
          offset += chunk.length;
        }
        return data.buffer;
      }
      stream() {
        const it = toIterator(__privateGet(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 = __privateGet(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 _a11([], { type: String(type).toLowerCase() });
        __privateSet(blob, _size, span);
        __privateSet(blob, _parts, blobParts);
        return blob;
      }
      get [Symbol.toStringTag]() {
        return "Blob";
      }
      static [Symbol.hasInstance](object) {
        return object && typeof object === "object" && typeof object.constructor === "function" && (typeof object.stream === "function" || typeof object.arrayBuffer === "function") && /^(Blob|File)$/.test(object[Symbol.toStringTag]);
      }
    }, _parts = new WeakMap(), _type = new WeakMap(), _size = new WeakMap(), _endings = new WeakMap(), _a11);
    Object.defineProperties(_Blob.prototype, {
      size: { enumerable: true },
      type: { enumerable: true },
      slice: { enumerable: true }
    });
    Blob2 = _Blob;
    fetch_blob_default = Blob2;
  }
});

// ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/file.js
var _lastModified, _name, _a12, _File, File2, file_default;
var init_file = __esm({
  "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/file.js"() {
    "use strict";
    init_fetch_blob();
    _File = (_a12 = class extends fetch_blob_default {
      /**
       * @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);
        __privateAdd(this, _lastModified, 0);
        __privateAdd(this, _name, "");
        if (options === null) options = {};
        const lastModified = options.lastModified === void 0 ? Date.now() : Number(options.lastModified);
        if (!Number.isNaN(lastModified)) {
          __privateSet(this, _lastModified, lastModified);
        }
        __privateSet(this, _name, String(fileName));
      }
      get name() {
        return __privateGet(this, _name);
      }
      get lastModified() {
        return __privateGet(this, _lastModified);
      }
      get [Symbol.toStringTag]() {
        return "File";
      }
      static [Symbol.hasInstance](object) {
        return !!object && object instanceof fetch_blob_default && /^(File)$/.test(object[Symbol.toStringTag]);
      }
    }, _lastModified = new WeakMap(), _name = new WeakMap(), _a12);
    File2 = _File;
    file_default = File2;
  }
});

// ../node_modules/.pnpm/formdata-polyfill@4.0.10/node_modules/formdata-polyfill/esm.min.js
function formDataToBlob(F3, B2 = fetch_blob_default) {
  var b5 = `${r()}${r()}`.replace(/\./g, "").slice(-28).padStart(32, "-"), c5 = [], p5 = `--${b5}\r
Content-Disposition: form-data; name="`;
  F3.forEach((v6, n5) => typeof v6 == "string" ? c5.push(p5 + e(n5) + `"\r
\r
${v6.replace(/\r(?!\n)|(?<!\r)\n/g, "\r\n")}\r
`) : c5.push(p5 + e(n5) + `"; filename="${e(v6.name, 1)}"\r
Content-Type: ${v6.type || "application/octet-stream"}\r
\r
`, v6, "\r\n"));
  c5.push(`--${b5}--`);
  return new B2(c5, { type: "multipart/form-data; boundary=" + b5 });
}
var t, i, h, r, m, f, e, x, _d, _a13, FormData;
var init_esm_min = __esm({
  "../node_modules/.pnpm/formdata-polyfill@4.0.10/node_modules/formdata-polyfill/esm.min.js"() {
    "use strict";
    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 = (a5, b5, c5) => (a5 += "", /^(Blob|File)$/.test(b5 && b5[t]) ? [(c5 = c5 !== void 0 ? c5 + "" : b5[t] == "File" ? b5.name : "blob", a5), b5.name !== c5 || b5[t] == "blob" ? new file_default([b5], c5, b5) : b5] : [a5, b5 + ""]);
    e = (c5, f7) => (f7 ? c5 : c5.replace(/\r?\n|\r/g, "\r\n")).replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22");
    x = (n5, a5, e6) => {
      if (a5.length < e6) {
        throw new TypeError(`Failed to execute '${n5}' on 'FormData': ${e6} arguments required, but only ${a5.length} present.`);
      }
    };
    FormData = (_a13 = class {
      constructor(...a5) {
        __privateAdd(this, _d, []);
        if (a5.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](o5) {
        return o5 && typeof o5 === "object" && o5[t] === "FormData" && !m.some((m6) => typeof o5[m6] != "function");
      }
      append(...a5) {
        x("append", arguments, 2);
        __privateGet(this, _d).push(f(...a5));
      }
      delete(a5) {
        x("delete", arguments, 1);
        a5 += "";
        __privateSet(this, _d, __privateGet(this, _d).filter(([b5]) => b5 !== a5));
      }
      get(a5) {
        x("get", arguments, 1);
        a5 += "";
        for (var b5 = __privateGet(this, _d), l5 = b5.length, c5 = 0; c5 < l5; c5++) if (b5[c5][0] === a5) return b5[c5][1];
        return null;
      }
      getAll(a5, b5) {
        x("getAll", arguments, 1);
        b5 = [];
        a5 += "";
        __privateGet(this, _d).forEach((c5) => c5[0] === a5 && b5.push(c5[1]));
        return b5;
      }
      has(a5) {
        x("has", arguments, 1);
        a5 += "";
        return __privateGet(this, _d).some((b5) => b5[0] === a5);
      }
      forEach(a5, b5) {
        x("forEach", arguments, 1);
        for (var [c5, d5] of this) a5.call(b5, d5, c5, this);
      }
      set(...a5) {
        x("set", arguments, 2);
        var b5 = [], c5 = true;
        a5 = f(...a5);
        __privateGet(this, _d).forEach((d5) => {
          d5[0] === a5[0] ? c5 && (c5 = !b5.push(a5)) : b5.push(d5);
        });
        c5 && b5.push(a5);
        __privateSet(this, _d, b5);
      }
      *entries() {
        yield* __privateGet(this, _d);
      }
      *keys() {
        for (var [a5] of this) yield a5;
      }
      *values() {
        for (var [, a5] of this) yield a5;
      }
    }, _d = new WeakMap(), _a13);
  }
});

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/base.js
var FetchBaseError;
var init_base = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/base.js"() {
    "use strict";
    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/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/fetch-error.js
var FetchError;
var init_fetch_error = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/fetch-error.js"() {
    "use strict";
    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/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is.js
var NAME, isURLSearchParameters, isBlob, isAbortSignal, isDomainOrSubdomain, isSameProtocol;
var init_is = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is.js"() {
    "use strict";
    NAME = Symbol.toStringTag;
    isURLSearchParameters = (object) => {
      return typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && typeof object.sort === "function" && object[NAME] === "URLSearchParams";
    };
    isBlob = (object) => {
      return object && typeof object === "object" && typeof object.arrayBuffer === "function" && typeof object.type === "string" && typeof object.stream === "function" && typeof object.constructor === "function" && /^(Blob|File)$/.test(object[NAME]);
    };
    isAbortSignal = (object) => {
      return typeof object === "object" && (object[NAME] === "AbortSignal" || object[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/.pnpm/node-domexception@1.0.0/node_modules/node-domexception/index.js
var require_node_domexception = __commonJS({
  "../node_modules/.pnpm/node-domexception@1.0.0/node_modules/node-domexception/index.js"(exports2, module2) {
    "use strict";
    if (!globalThis.DOMException) {
      try {
        const { MessageChannel } = require("worker_threads"), port = new MessageChannel().port1, ab = new ArrayBuffer();
        port.postMessage(ab, [ab, ab]);
      } catch (err2) {
        err2.constructor.name === "DOMException" && (globalThis.DOMException = err2.constructor);
      }
    }
    module2.exports = globalThis.DOMException;
  }
});

// ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/from.js
var import_node_fs, import_node_path2, import_node_domexception, stat;
var init_from = __esm({
  "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/from.js"() {
    "use strict";
    import_node_fs = require("fs");
    import_node_path2 = require("path");
    import_node_domexception = __toESM(require_node_domexception(), 1);
    init_file();
    init_fetch_blob();
    ({ stat } = import_node_fs.promises);
  }
});

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/multipart-parser.js
var multipart_parser_exports = {};
__export(multipart_parser_exports, {
  toFormData: () => toFormData
});
function _fileName(headerValue) {
  const m6 = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);
  if (!m6) {
    return;
  }
  const match2 = m6[2] || m6[3] || "";
  let filename = match2.slice(match2.lastIndexOf("\\") + 1);
  filename = filename.replace(/%22/g, '"');
  filename = filename.replace(/&#(\d{4});/g, (m7, code) => {
    return String.fromCharCode(code);
  });
  return filename;
}
async function toFormData(Body2, ct) {
  if (!/multipart/i.test(ct)) {
    throw new TypeError("Failed to fetch");
  }
  const m6 = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i);
  if (!m6) {
    throw new TypeError("no or bad content-type header, no multipart boundary");
  }
  const parser = new MultipartParser(m6[1] || m6[2]);
  let headerField;
  let headerValue;
  let entryValue;
  let entryName;
  let contentType;
  let filename;
  const entryChunks = [];
  const formData = new FormData();
  const onPartData = (ui8a) => {
    entryValue += decoder.decode(ui8a, { stream: true });
  };
  const appendToFile = (ui8a) => {
    entryChunks.push(ui8a);
  };
  const appendFileToFormData = () => {
    const file = new file_default(entryChunks, filename, { type: contentType });
    formData.append(entryName, file);
  };
  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 m7 = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);
      if (m7) {
        entryName = m7[2] || m7[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/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/multipart-parser.js"() {
    "use strict";
    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 = (c5) => c5 | 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 i6 = 0; i6 < boundary.length; i6++) {
          ui8a[i6] = boundary.charCodeAt(i6);
          this.boundaryChars[ui8a[i6]] = true;
        }
        this.boundary = ui8a;
        this.lookbehind = new Uint8Array(this.boundary.length + 8);
        this.state = S.START_BOUNDARY;
      }
      /**
       * @param {Uint8Array} data
       */
      write(data) {
        let i6 = 0;
        const length_ = data.length;
        let previousIndex = this.index;
        let { lookbehind, boundary, boundaryChars, index: index6, state: state2, flags } = this;
        const boundaryLength = this.boundary.length;
        const boundaryEnd = boundaryLength - 1;
        const bufferLength = data.length;
        let c5;
        let cl;
        const mark = (name) => {
          this[name + "Mark"] = i6;
        };
        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], i6, data);
            delete this[markSymbol];
          } else {
            callback(name, this[markSymbol], data.length, data);
            this[markSymbol] = 0;
          }
        };
        for (i6 = 0; i6 < length_; i6++) {
          c5 = data[i6];
          switch (state2) {
            case S.START_BOUNDARY:
              if (index6 === boundary.length - 2) {
                if (c5 === HYPHEN) {
                  flags |= F.LAST_BOUNDARY;
                } else if (c5 !== CR) {
                  return;
                }
                index6++;
                break;
              } else if (index6 - 1 === boundary.length - 2) {
                if (flags & F.LAST_BOUNDARY && c5 === HYPHEN) {
                  state2 = S.END;
                  flags = 0;
                } else if (!(flags & F.LAST_BOUNDARY) && c5 === LF) {
                  index6 = 0;
                  callback("onPartBegin");
                  state2 = S.HEADER_FIELD_START;
                } else {
                  return;
                }
                break;
              }
              if (c5 !== boundary[index6 + 2]) {
                index6 = -2;
              }
              if (c5 === boundary[index6 + 2]) {
                index6++;
              }
              break;
            case S.HEADER_FIELD_START:
              state2 = S.HEADER_FIELD;
              mark("onHeaderField");
              index6 = 0;
            // falls through
            case S.HEADER_FIELD:
              if (c5 === CR) {
                clear("onHeaderField");
                state2 = S.HEADERS_ALMOST_DONE;
                break;
              }
              index6++;
              if (c5 === HYPHEN) {
                break;
              }
              if (c5 === COLON) {
                if (index6 === 1) {
                  return;
                }
                dataCallback("onHeaderField", true);
                state2 = S.HEADER_VALUE_START;
                break;
              }
              cl = lower(c5);
              if (cl < A || cl > Z) {
                return;
              }
              break;
            case S.HEADER_VALUE_START:
              if (c5 === SPACE) {
                break;
              }
              mark("onHeaderValue");
              state2 = S.HEADER_VALUE;
            // falls through
            case S.HEADER_VALUE:
              if (c5 === CR) {
                dataCallback("onHeaderValue", true);
                callback("onHeaderEnd");
                state2 = S.HEADER_VALUE_ALMOST_DONE;
              }
              break;
            case S.HEADER_VALUE_ALMOST_DONE:
              if (c5 !== LF) {
                return;
              }
              state2 = S.HEADER_FIELD_START;
              break;
            case S.HEADERS_ALMOST_DONE:
              if (c5 !== LF) {
                return;
              }
              callback("onHeadersEnd");
              state2 = S.PART_DATA_START;
              break;
            case S.PART_DATA_START:
              state2 = S.PART_DATA;
              mark("onPartData");
            // falls through
            case S.PART_DATA:
              previousIndex = index6;
              if (index6 === 0) {
                i6 += boundaryEnd;
                while (i6 < bufferLength && !(data[i6] in boundaryChars)) {
                  i6 += boundaryLength;
                }
                i6 -= boundaryEnd;
                c5 = data[i6];
              }
              if (index6 < boundary.length) {
                if (boundary[index6] === c5) {
                  if (index6 === 0) {
                    dataCallback("onPartData", true);
                  }
                  index6++;
                } else {
                  index6 = 0;
                }
              } else if (index6 === boundary.length) {
                index6++;
                if (c5 === CR) {
                  flags |= F.PART_BOUNDARY;
                } else if (c5 === HYPHEN) {
                  flags |= F.LAST_BOUNDARY;
                } else {
                  index6 = 0;
                }
              } else if (index6 - 1 === boundary.length) {
                if (flags & F.PART_BOUNDARY) {
                  index6 = 0;
                  if (c5 === LF) {
                    flags &= ~F.PART_BOUNDARY;
                    callback("onPartEnd");
                    callback("onPartBegin");
                    state2 = S.HEADER_FIELD_START;
                    break;
                  }
                } else if (flags & F.LAST_BOUNDARY) {
                  if (c5 === HYPHEN) {
                    callback("onPartEnd");
                    state2 = S.END;
                    flags = 0;
                  } else {
                    index6 = 0;
                  }
                } else {
                  index6 = 0;
                }
              }
              if (index6 > 0) {
                lookbehind[index6 - 1] = c5;
              } else if (previousIndex > 0) {
                const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength);
                callback("onPartData", 0, previousIndex, _lookbehind);
                previousIndex = 0;
                mark("onPartData");
                i6--;
              }
              break;
            case S.END:
              break;
            default:
              throw new Error(`Unexpected state entered: ${state2}`);
          }
        }
        dataCallback("onHeaderField");
        dataCallback("onHeaderValue");
        dataCallback("onPartData");
        this.index = index6;
        this.state = state2;
        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/.pnpm/node-fetch@3.3.2/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 error2 = new FetchError(`content size at ${data.url} over limit: ${data.size}`, "max-size");
        body.destroy(error2);
        throw error2;
      }
      accumBytes += chunk.length;
      accum.push(chunk);
    }
  } catch (error2) {
    const error_ = error2 instanceof FetchBaseError ? error2 : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error2.message}`, "system", error2);
    throw error_;
  }
  if (body.readableEnded === true || body._readableState.ended === true) {
    try {
      if (accum.every((c5) => typeof c5 === "string")) {
        return import_node_buffer.Buffer.from(accum.join(""));
      }
      return import_node_buffer.Buffer.concat(accum, accumBytes);
    } catch (error2) {
      throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error2.message}`, "system", error2);
    }
  } else {
    throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`);
  }
}
var import_node_stream, import_node_util, import_node_buffer, pipeline, INTERNALS, Body, clone, getNonSpecFormDataBoundary, extractContentType, getTotalBytes, writeToStream;
var init_body2 = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/body.js"() {
    "use strict";
    import_node_stream = __toESM(require("stream"), 1);
    import_node_util = require("util");
    import_node_buffer = require("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 = 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 FormData) {
          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 error2 = error_ instanceof FetchBaseError ? error_ : new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, "system", error_);
            this[INTERNALS].error = error2;
          });
        }
      }
      get body() {
        return this[INTERNALS].stream;
      }
      get bodyUsed() {
        return this[INTERNALS].disturbed;
      }
      /**
       * Decode response as ArrayBuffer
       *
       * @return  Promise
       */
      async arrayBuffer() {
        const { buffer, byteOffset, byteLength } = await consumeBody(this);
        return buffer.slice(byteOffset, byteOffset + byteLength);
      }
      async formData() {
        const ct = this.headers.get("content-type");
        if (ct.startsWith("application/x-www-form-urlencoded")) {
          const formData = new FormData();
          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)"
      ) }
    });
    clone = (instance, highWaterMark) => {
      let p1;
      let p22;
      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 });
        p22 = new import_node_stream.PassThrough({ highWaterMark });
        body.pipe(p1);
        body.pipe(p22);
        instance[INTERNALS].stream = p1;
        body = p22;
      }
      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, request2) => {
      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 FormData) {
        return `multipart/form-data; boundary=${request2[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 = (request2) => {
      const { body } = request2[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/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js
function fromRawHeaders(headers = []) {
  return new Headers2(
    headers.reduce((result, value, index6, array2) => {
      if (index6 % 2 === 0) {
        result.push(array2.slice(index6, index6 + 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/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js"() {
    "use strict";
    import_node_util2 = require("util");
    import_node_http = __toESM(require("http"), 1);
    validateHeaderName = typeof import_node_http.default.validateHeaderName === "function" ? import_node_http.default.validateHeaderName : (name) => {
      if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) {
        const error2 = new TypeError(`Header name must be a valid HTTP token [${name}]`);
        Object.defineProperty(error2, "code", { value: "ERR_INVALID_HTTP_TOKEN" });
        throw error2;
      }
    };
    validateHeaderValue = typeof import_node_http.default.validateHeaderValue === "function" ? import_node_http.default.validateHeaderValue : (name, value) => {
      if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) {
        const error2 = new TypeError(`Invalid character in header content ["${name}"]`);
        Object.defineProperty(error2, "code", { value: "ERR_INVALID_CHAR" });
        throw error2;
      }
    };
    Headers2 = class _Headers extends URLSearchParams {
      /**
       * Headers class
       *
       * @constructor
       * @param {HeadersInit} [init] - Response headers
       */
      constructor(init2) {
        let result = [];
        if (init2 instanceof _Headers) {
          const raw2 = init2.raw();
          for (const [name, values] of Object.entries(raw2)) {
            result.push(...values.map((value) => [name, value]));
          }
        } else if (init2 == null) {
        } else if (typeof init2 === "object" && !import_node_util2.types.isBoxedPrimitive(init2)) {
          const method = init2[Symbol.iterator];
          if (method == null) {
            result.push(...Object.entries(init2));
          } else {
            if (typeof method !== "function") {
              throw new TypeError("Header pairs must be iterable");
            }
            result = [...init2].map((pair) => {
              if (typeof pair !== "object" || 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, p5, receiver) {
            switch (p5) {
              case "append":
              case "set":
                return (name, value) => {
                  validateHeaderName(name);
                  validateHeaderValue(name, String(value));
                  return URLSearchParams.prototype[p5].call(
                    target,
                    String(name).toLowerCase(),
                    String(value)
                  );
                };
              case "delete":
              case "has":
              case "getAll":
                return (name) => {
                  validateHeaderName(name);
                  return URLSearchParams.prototype[p5].call(
                    target,
                    String(name).toLowerCase()
                  );
                };
              case "keys":
                return () => {
                  target.sort();
                  return new Set(URLSearchParams.prototype.keys.call(target)).keys();
                };
              default:
                return Reflect.get(target, p5, 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
       */
      [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/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is-redirect.js
var redirectStatus, isRedirect;
var init_is_redirect = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is-redirect.js"() {
    "use strict";
    redirectStatus = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
    isRedirect = (code) => {
      return redirectStatus.has(code);
    };
  }
});

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/response.js
var INTERNALS2, Response3;
var init_response = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/response.js"() {
    "use strict";
    init_headers();
    init_body2();
    init_is_redirect();
    INTERNALS2 = Symbol("Response internals");
    Response3 = 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(clone(this, this.highWaterMark), {
          type: this.type,
          url: this.url,
          status: this.status,
          statusText: this.statusText,
          headers: this.headers,
          ok: this.ok,
          redirected: this.redirected,
          size: this.size,
          highWaterMark: this.highWaterMark
        });
      }
      /**
       * @param {string} url    The URL that the new response is to originate from.
       * @param {number} status An optional status code for the response (e.g., 302.)
       * @returns {Response}    A Response object.
       */
      static redirect(url, 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(url).toString()
          },
          status
        });
      }
      static error() {
        const response = new _Response(null, { status: 0, statusText: "" });
        response[INTERNALS2].type = "error";
        return response;
      }
      static json(data = void 0, init2 = {}) {
        const body = JSON.stringify(data);
        if (body === void 0) {
          throw new TypeError("data is not JSON serializable");
        }
        const headers = new Headers2(init2 && init2.headers);
        if (!headers.has("content-type")) {
          headers.set("content-type", "application/json");
        }
        return new _Response(body, {
          ...init2,
          headers
        });
      }
      get [Symbol.toStringTag]() {
        return "Response";
      }
    };
    Object.defineProperties(Response3.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/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/get-search.js
var getSearch;
var init_get_search = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/get-search.js"() {
    "use strict";
    getSearch = (parsedURL) => {
      if (parsedURL.search) {
        return parsedURL.search;
      }
      const lastOffset = parsedURL.href.length - 1;
      const hash = parsedURL.hash || (parsedURL.href[lastOffset] === "#" ? "#" : "");
      return parsedURL.href[lastOffset - hash.length] === "?" ? "?" : "";
    };
  }
});

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/referrer.js
function stripURLForUseAsAReferrer(url, originOnly = false) {
  if (url == null) {
    return "no-referrer";
  }
  url = new URL(url);
  if (/^(about|blob|data):$/.test(url.protocol)) {
    return "no-referrer";
  }
  url.username = "";
  url.password = "";
  url.hash = "";
  if (originOnly) {
    url.pathname = "";
    url.search = "";
  }
  return url;
}
function validateReferrerPolicy(referrerPolicy) {
  if (!ReferrerPolicy.has(referrerPolicy)) {
    throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);
  }
  return referrerPolicy;
}
function isOriginPotentiallyTrustworthy(url) {
  if (/^(http|ws)s:$/.test(url.protocol)) {
    return true;
  }
  const hostIp = url.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 (url.host === "localhost" || url.host.endsWith(".localhost")) {
    return false;
  }
  if (url.protocol === "file:") {
    return true;
  }
  return false;
}
function isUrlPotentiallyTrustworthy(url) {
  if (/^about:(blank|srcdoc)$/.test(url)) {
    return true;
  }
  if (url.protocol === "data:") {
    return true;
  }
  if (/^(blob|filesystem):$/.test(url.protocol)) {
    return true;
  }
  return isOriginPotentiallyTrustworthy(url);
}
function determineRequestsReferrer(request2, { referrerURLCallback, referrerOriginCallback } = {}) {
  if (request2.referrer === "no-referrer" || request2.referrerPolicy === "") {
    return null;
  }
  const policy5 = request2.referrerPolicy;
  if (request2.referrer === "about:client") {
    return "no-referrer";
  }
  const referrerSource = request2.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(request2.url);
  switch (policy5) {
    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: ${policy5}`);
  }
}
function parseReferrerPolicyFromHeader(headers) {
  const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/);
  let policy5 = "";
  for (const token of policyTokens) {
    if (token && ReferrerPolicy.has(token)) {
      policy5 = token;
    }
  }
  return policy5;
}
var import_node_net, ReferrerPolicy, DEFAULT_REFERRER_POLICY;
var init_referrer = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/referrer.js"() {
    "use strict";
    import_node_net = require("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/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/request.js
var import_node_url, import_node_util3, INTERNALS3, isRequest, doBadDataWarn, Request3, getNodeRequestOptions;
var init_request2 = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/request.js"() {
    "use strict";
    import_node_url = require("url");
    import_node_util3 = require("util");
    init_headers();
    init_body2();
    init_is();
    init_get_search();
    init_referrer();
    INTERNALS3 = Symbol("Request internals");
    isRequest = (object) => {
      return typeof object === "object" && typeof object[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)"
    );
    Request3 = class _Request extends Body {
      constructor(input, init2 = {}) {
        let parsedURL;
        if (isRequest(input)) {
          parsedURL = new URL(input.url);
        } else {
          parsedURL = new URL(input);
          input = {};
        }
        if (parsedURL.username !== "" || parsedURL.password !== "") {
          throw new TypeError(`${parsedURL} is an url with embedded credentials.`);
        }
        let method = init2.method || input.method || "GET";
        if (/^(delete|get|head|options|post|put)$/i.test(method)) {
          method = method.toUpperCase();
        }
        if (!isRequest(init2) && "data" in init2) {
          doBadDataWarn();
        }
        if ((init2.body != null || isRequest(input) && input.body !== null) && (method === "GET" || method === "HEAD")) {
          throw new TypeError("Request with GET/HEAD method cannot have body");
        }
        const inputBody = init2.body ? init2.body : isRequest(input) && input.body !== null ? clone(input) : null;
        super(inputBody, {
          size: init2.size || input.size || 0
        });
        const headers = new Headers2(init2.headers || input.headers || {});
        if (inputBody !== null && !headers.has("Content-Type")) {
          const contentType = extractContentType(inputBody, this);
          if (contentType) {
            headers.set("Content-Type", contentType);
          }
        }
        let signal = isRequest(input) ? input.signal : null;
        if ("signal" in init2) {
          signal = init2.signal;
        }
        if (signal != null && !isAbortSignal(signal)) {
          throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");
        }
        let referrer = init2.referrer == null ? input.referrer : init2.referrer;
        if (referrer === "") {
          referrer = "no-referrer";
        } else if (referrer) {
          const parsedReferrer = new URL(referrer);
          referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? "client" : parsedReferrer;
        } else {
          referrer = void 0;
        }
        this[INTERNALS3] = {
          method,
          redirect: init2.redirect || input.redirect || "follow",
          headers,
          parsedURL,
          signal,
          referrer
        };
        this.follow = init2.follow === void 0 ? input.follow === void 0 ? 20 : input.follow : init2.follow;
        this.compress = init2.compress === void 0 ? input.compress === void 0 ? true : input.compress : init2.compress;
        this.counter = init2.counter || input.counter || 0;
        this.agent = init2.agent || input.agent;
        this.highWaterMark = init2.highWaterMark || input.highWaterMark || 16384;
        this.insecureHTTPParser = init2.insecureHTTPParser || input.insecureHTTPParser || false;
        this.referrerPolicy = init2.referrerPolicy || input.referrerPolicy || "";
      }
      /** @returns {string} */
      get method() {
        return this[INTERNALS3].method;
      }
      /** @returns {string} */
      get url() {
        return (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(Request3.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 = (request2) => {
      const { parsedURL } = request2[INTERNALS3];
      const headers = new Headers2(request2[INTERNALS3].headers);
      if (!headers.has("Accept")) {
        headers.set("Accept", "*/*");
      }
      let contentLengthValue = null;
      if (request2.body === null && /^(post|put)$/i.test(request2.method)) {
        contentLengthValue = "0";
      }
      if (request2.body !== null) {
        const totalBytes = getTotalBytes(request2);
        if (typeof totalBytes === "number" && !Number.isNaN(totalBytes)) {
          contentLengthValue = String(totalBytes);
        }
      }
      if (contentLengthValue) {
        headers.set("Content-Length", contentLengthValue);
      }
      if (request2.referrerPolicy === "") {
        request2.referrerPolicy = DEFAULT_REFERRER_POLICY;
      }
      if (request2.referrer && request2.referrer !== "no-referrer") {
        request2[INTERNALS3].referrer = determineRequestsReferrer(request2);
      } else {
        request2[INTERNALS3].referrer = "no-referrer";
      }
      if (request2[INTERNALS3].referrer instanceof URL) {
        headers.set("Referer", request2.referrer);
      }
      if (!headers.has("User-Agent")) {
        headers.set("User-Agent", "node-fetch");
      }
      if (request2.compress && !headers.has("Accept-Encoding")) {
        headers.set("Accept-Encoding", "gzip, deflate, br");
      }
      let { agent } = request2;
      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: request2.method,
        headers: headers[Symbol.for("nodejs.util.inspect.custom")](),
        insecureHTTPParser: request2.insecureHTTPParser,
        agent
      };
      return {
        /** @type {URL} */
        parsedURL,
        options
      };
    };
  }
});

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

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/index.js
async function fetch2(url, options_) {
  return new Promise((resolve, reject) => {
    const request2 = new Request3(url, options_);
    const { parsedURL, options } = getNodeRequestOptions(request2);
    if (!supportedSchemas.has(parsedURL.protocol)) {
      throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/, "")}" is not supported.`);
    }
    if (parsedURL.protocol === "data:") {
      const data = dist_default(request2.url);
      const response2 = new Response3(data, { headers: { "Content-Type": data.typeFull } });
      resolve(response2);
      return;
    }
    const send = (parsedURL.protocol === "https:" ? import_node_https.default : import_node_http2.default).request;
    const { signal } = request2;
    let response = null;
    const abort = () => {
      const error2 = new AbortError("The operation was aborted.");
      reject(error2);
      if (request2.body && request2.body instanceof import_node_stream2.default.Readable) {
        request2.body.destroy(error2);
      }
      if (!response || !response.body) {
        return;
      }
      response.body.emit("error", error2);
    };
    if (signal && signal.aborted) {
      abort();
      return;
    }
    const abortAndFinalize = () => {
      abort();
      finalize();
    };
    const request_ = send(parsedURL.toString(), options);
    if (signal) {
      signal.addEventListener("abort", abortAndFinalize);
    }
    const finalize = () => {
      request_.abort();
      if (signal) {
        signal.removeEventListener("abort", abortAndFinalize);
      }
    };
    request_.on("error", (error2) => {
      reject(new FetchError(`request to ${request2.url} failed, reason: ${error2.message}`, "system", error2));
      finalize();
    });
    fixResponseChunkedTransferBadEnding(request_, (error2) => {
      if (response && response.body) {
        response.body.destroy(error2);
      }
    });
    if (process.version < "v14") {
      request_.on("socket", (s6) => {
        let endedWithEventsCount;
        s6.prependListener("end", () => {
          endedWithEventsCount = s6._eventsCount;
        });
        s6.prependListener("close", (hadError) => {
          if (response && endedWithEventsCount < s6._eventsCount && !hadError) {
            const error2 = new Error("Premature close");
            error2.code = "ERR_STREAM_PREMATURE_CLOSE";
            response.body.emit("error", error2);
          }
        });
      });
    }
    request_.on("response", (response_) => {
      request_.setTimeout(0);
      const headers = fromRawHeaders(response_.rawHeaders);
      if (isRedirect(response_.statusCode)) {
        const location = headers.get("Location");
        let locationURL = null;
        try {
          locationURL = location === null ? null : new URL(location, request2.url);
        } catch {
          if (request2.redirect !== "manual") {
            reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, "invalid-redirect"));
            finalize();
            return;
          }
        }
        switch (request2.redirect) {
          case "error":
            reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request2.url}`, "no-redirect"));
            finalize();
            return;
          case "manual":
            break;
          case "follow": {
            if (locationURL === null) {
              break;
            }
            if (request2.counter >= request2.follow) {
              reject(new FetchError(`maximum redirect reached at: ${request2.url}`, "max-redirect"));
              finalize();
              return;
            }
            const requestOptions = {
              headers: new Headers2(request2.headers),
              follow: request2.follow,
              counter: request2.counter + 1,
              agent: request2.agent,
              compress: request2.compress,
              method: request2.method,
              body: clone(request2),
              signal: request2.signal,
              size: request2.size,
              referrer: request2.referrer,
              referrerPolicy: request2.referrerPolicy
            };
            if (!isDomainOrSubdomain(request2.url, locationURL) || !isSameProtocol(request2.url, locationURL)) {
              for (const name of ["authorization", "www-authenticate", "cookie", "cookie2"]) {
                requestOptions.headers.delete(name);
              }
            }
            if (response_.statusCode !== 303 && request2.body && options_.body instanceof import_node_stream2.default.Readable) {
              reject(new FetchError("Cannot follow redirect with body being a readable stream", "unsupported-redirect"));
              finalize();
              return;
            }
            if (response_.statusCode === 303 || (response_.statusCode === 301 || response_.statusCode === 302) && request2.method === "POST") {
              requestOptions.method = "GET";
              requestOptions.body = void 0;
              requestOptions.headers.delete("content-length");
            }
            const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers);
            if (responseReferrerPolicy) {
              requestOptions.referrerPolicy = responseReferrerPolicy;
            }
            resolve(fetch2(new Request3(locationURL, requestOptions)));
            finalize();
            return;
          }
          default:
            return reject(new TypeError(`Redirect option '${request2.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(), (error2) => {
        if (error2) {
          reject(error2);
        }
      });
      if (process.version < "v12.10") {
        response_.on("aborted", abortAndFinalize);
      }
      const responseOptions = {
        url: request2.url,
        status: response_.statusCode,
        statusText: response_.statusMessage,
        headers,
        size: request2.size,
        counter: request2.counter,
        highWaterMark: request2.highWaterMark
      };
      const codings = headers.get("Content-Encoding");
      if (!request2.compress || request2.method === "HEAD" || codings === null || response_.statusCode === 204 || response_.statusCode === 304) {
        response = new Response3(body, responseOptions);
        resolve(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), (error2) => {
          if (error2) {
            reject(error2);
          }
        });
        response = new Response3(body, responseOptions);
        resolve(response);
        return;
      }
      if (codings === "deflate" || codings === "x-deflate") {
        const raw2 = (0, import_node_stream2.pipeline)(response_, new import_node_stream2.PassThrough(), (error2) => {
          if (error2) {
            reject(error2);
          }
        });
        raw2.once("data", (chunk) => {
          if ((chunk[0] & 15) === 8) {
            body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createInflate(), (error2) => {
              if (error2) {
                reject(error2);
              }
            });
          } else {
            body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createInflateRaw(), (error2) => {
              if (error2) {
                reject(error2);
              }
            });
          }
          response = new Response3(body, responseOptions);
          resolve(response);
        });
        raw2.once("end", () => {
          if (!response) {
            response = new Response3(body, responseOptions);
            resolve(response);
          }
        });
        return;
      }
      if (codings === "br") {
        body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createBrotliDecompress(), (error2) => {
          if (error2) {
            reject(error2);
          }
        });
        response = new Response3(body, responseOptions);
        resolve(response);
        return;
      }
      response = new Response3(body, responseOptions);
      resolve(response);
    });
    writeToStream(request_, request2).catch(reject);
  });
}
function fixResponseChunkedTransferBadEnding(request2, errorCallback) {
  const LAST_CHUNK = import_node_buffer2.Buffer.from("0\r\n\r\n");
  let isChunkedTransfer = false;
  let properLastChunkReceived = false;
  let previousChunk;
  request2.on("response", (response) => {
    const { headers } = response;
    isChunkedTransfer = headers["transfer-encoding"] === "chunked" && !headers["content-length"];
  });
  request2.on("socket", (socket) => {
    const onSocketClose = () => {
      if (isChunkedTransfer && !properLastChunkReceived) {
        const error2 = new Error("Premature close");
        error2.code = "ERR_STREAM_PREMATURE_CLOSE";
        errorCallback(error2);
      }
    };
    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);
    request2.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/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/index.js"() {
    "use strict";
    import_node_http2 = __toESM(require("http"), 1);
    import_node_https = __toESM(require("https"), 1);
    import_node_zlib = __toESM(require("zlib"), 1);
    import_node_stream2 = __toESM(require("stream"), 1);
    import_node_buffer2 = require("buffer");
    init_dist3();
    init_body2();
    init_response();
    init_headers();
    init_request2();
    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/.pnpm/ws@8.18.2/node_modules/ws/lib/constants.js
var require_constants = __commonJS({
  "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/constants.js"(exports2, module2) {
    "use strict";
    var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
    var hasBlob = typeof Blob !== "undefined";
    if (hasBlob) BINARY_TYPES.push("blob");
    module2.exports = {
      BINARY_TYPES,
      EMPTY_BUFFER: Buffer.alloc(0),
      GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
      hasBlob,
      kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
      kListener: Symbol("kListener"),
      kStatusCode: Symbol("status-code"),
      kWebSocket: Symbol("websocket"),
      NOOP: () => {
      }
    };
  }
});

// ../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js
var require_node_gyp_build = __commonJS({
  "../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js"(exports2, module2) {
    "use strict";
    var fs5 = require("fs");
    var path3 = require("path");
    var os3 = require("os");
    var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
    var vars = process.config && process.config.variables || {};
    var prebuildsOnly = !!process.env.PREBUILDS_ONLY;
    var abi = process.versions.modules;
    var runtime = isElectron() ? "electron" : isNwjs() ? "node-webkit" : "node";
    var arch = process.env.npm_config_arch || os3.arch();
    var platform2 = process.env.npm_config_platform || os3.platform();
    var libc = process.env.LIBC || (isAlpine(platform2) ? "musl" : "glibc");
    var armv = process.env.ARM_VERSION || (arch === "arm64" ? "8" : vars.arm_version) || "";
    var uv = (process.versions.uv || "").split(".")[0];
    module2.exports = load;
    function load(dir) {
      return runtimeRequire(load.resolve(dir));
    }
    load.resolve = load.path = function(dir) {
      dir = path3.resolve(dir || ".");
      try {
        var name = runtimeRequire(path3.join(dir, "package.json")).name.toUpperCase().replace(/-/g, "_");
        if (process.env[name + "_PREBUILD"]) dir = process.env[name + "_PREBUILD"];
      } catch (err2) {
      }
      if (!prebuildsOnly) {
        var release2 = getFirst(path3.join(dir, "build/Release"), matchBuild);
        if (release2) return release2;
        var debug = getFirst(path3.join(dir, "build/Debug"), matchBuild);
        if (debug) return debug;
      }
      var prebuild = resolve(dir);
      if (prebuild) return prebuild;
      var nearby = resolve(path3.dirname(process.execPath));
      if (nearby) return nearby;
      var target = [
        "platform=" + platform2,
        "arch=" + arch,
        "runtime=" + runtime,
        "abi=" + abi,
        "uv=" + uv,
        armv ? "armv=" + armv : "",
        "libc=" + libc,
        "node=" + process.versions.node,
        process.versions.electron ? "electron=" + process.versions.electron : "",
        typeof __webpack_require__ === "function" ? "webpack=true" : ""
        // eslint-disable-line
      ].filter(Boolean).join(" ");
      throw new Error("No native build was found for " + target + "\n    loaded from: " + dir + "\n");
      function resolve(dir2) {
        var tuples = readdirSync(path3.join(dir2, "prebuilds")).map(parseTuple);
        var tuple = tuples.filter(matchTuple(platform2, arch)).sort(compareTuples)[0];
        if (!tuple) return;
        var prebuilds = path3.join(dir2, "prebuilds", tuple.name);
        var parsed = readdirSync(prebuilds).map(parseTags);
        var candidates = parsed.filter(matchTags(runtime, abi));
        var winner = candidates.sort(compareTags(runtime))[0];
        if (winner) return path3.join(prebuilds, winner.file);
      }
    };
    function readdirSync(dir) {
      try {
        return fs5.readdirSync(dir);
      } catch (err2) {
        return [];
      }
    }
    function getFirst(dir, filter2) {
      var files = readdirSync(dir).filter(filter2);
      return files[0] && path3.join(dir, files[0]);
    }
    function matchBuild(name) {
      return /\.node$/.test(name);
    }
    function parseTuple(name) {
      var arr = name.split("-");
      if (arr.length !== 2) return;
      var platform3 = arr[0];
      var architectures = arr[1].split("+");
      if (!platform3) return;
      if (!architectures.length) return;
      if (!architectures.every(Boolean)) return;
      return { name, platform: platform3, architectures };
    }
    function matchTuple(platform3, arch2) {
      return function(tuple) {
        if (tuple == null) return false;
        if (tuple.platform !== platform3) return false;
        return tuple.architectures.includes(arch2);
      };
    }
    function compareTuples(a5, b5) {
      return a5.architectures.length - b5.architectures.length;
    }
    function parseTags(file) {
      var arr = file.split(".");
      var extension = arr.pop();
      var tags = { file, specificity: 0 };
      if (extension !== "node") return;
      for (var i6 = 0; i6 < arr.length; i6++) {
        var tag = arr[i6];
        if (tag === "node" || tag === "electron" || tag === "node-webkit") {
          tags.runtime = tag;
        } else if (tag === "napi") {
          tags.napi = true;
        } else if (tag.slice(0, 3) === "abi") {
          tags.abi = tag.slice(3);
        } else if (tag.slice(0, 2) === "uv") {
          tags.uv = tag.slice(2);
        } else if (tag.slice(0, 4) === "armv") {
          tags.armv = tag.slice(4);
        } else if (tag === "glibc" || tag === "musl") {
          tags.libc = tag;
        } else {
          continue;
        }
        tags.specificity++;
      }
      return tags;
    }
    function matchTags(runtime2, abi2) {
      return function(tags) {
        if (tags == null) return false;
        if (tags.runtime && tags.runtime !== runtime2 && !runtimeAgnostic(tags)) return false;
        if (tags.abi && tags.abi !== abi2 && !tags.napi) return false;
        if (tags.uv && tags.uv !== uv) return false;
        if (tags.armv && tags.armv !== armv) return false;
        if (tags.libc && tags.libc !== libc) return false;
        return true;
      };
    }
    function runtimeAgnostic(tags) {
      return tags.runtime === "node" && tags.napi;
    }
    function compareTags(runtime2) {
      return function(a5, b5) {
        if (a5.runtime !== b5.runtime) {
          return a5.runtime === runtime2 ? -1 : 1;
        } else if (a5.abi !== b5.abi) {
          return a5.abi ? -1 : 1;
        } else if (a5.specificity !== b5.specificity) {
          return a5.specificity > b5.specificity ? -1 : 1;
        } else {
          return 0;
        }
      };
    }
    function isNwjs() {
      return !!(process.versions && process.versions.nw);
    }
    function isElectron() {
      if (process.versions && process.versions.electron) return true;
      if (process.env.ELECTRON_RUN_AS_NODE) return true;
      return typeof window !== "undefined" && window.process && window.process.type === "renderer";
    }
    function isAlpine(platform3) {
      return platform3 === "linux" && fs5.existsSync("/etc/alpine-release");
    }
    load.parseTags = parseTags;
    load.matchTags = matchTags;
    load.compareTags = compareTags;
    load.parseTuple = parseTuple;
    load.matchTuple = matchTuple;
    load.compareTuples = compareTuples;
  }
});

// ../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js
var require_node_gyp_build2 = __commonJS({
  "../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js"(exports2, module2) {
    "use strict";
    var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
    if (typeof runtimeRequire.addon === "function") {
      module2.exports = runtimeRequire.addon.bind(runtimeRequire);
    } else {
      module2.exports = require_node_gyp_build();
    }
  }
});

// ../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/fallback.js
var require_fallback = __commonJS({
  "../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/fallback.js"(exports2, module2) {
    "use strict";
    var mask = (source, mask2, output, offset, length) => {
      for (var i6 = 0; i6 < length; i6++) {
        output[offset + i6] = source[i6] ^ mask2[i6 & 3];
      }
    };
    var unmask = (buffer, mask2) => {
      const length = buffer.length;
      for (var i6 = 0; i6 < length; i6++) {
        buffer[i6] ^= mask2[i6 & 3];
      }
    };
    module2.exports = { mask, unmask };
  }
});

// ../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/index.js
var require_bufferutil = __commonJS({
  "../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/index.js"(exports2, module2) {
    "use strict";
    try {
      module2.exports = require_node_gyp_build2()(__dirname);
    } catch (e6) {
      module2.exports = require_fallback();
    }
  }
});

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

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

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

// ../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/fallback.js
var require_fallback2 = __commonJS({
  "../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/fallback.js"(exports2, module2) {
    "use strict";
    function isValidUTF8(buf) {
      const len = buf.length;
      let i6 = 0;
      while (i6 < len) {
        if ((buf[i6] & 128) === 0) {
          i6++;
        } else if ((buf[i6] & 224) === 192) {
          if (i6 + 1 === len || (buf[i6 + 1] & 192) !== 128 || (buf[i6] & 254) === 192) {
            return false;
          }
          i6 += 2;
        } else if ((buf[i6] & 240) === 224) {
          if (i6 + 2 >= len || (buf[i6 + 1] & 192) !== 128 || (buf[i6 + 2] & 192) !== 128 || buf[i6] === 224 && (buf[i6 + 1] & 224) === 128 || // overlong
          buf[i6] === 237 && (buf[i6 + 1] & 224) === 160) {
            return false;
          }
          i6 += 3;
        } else if ((buf[i6] & 248) === 240) {
          if (i6 + 3 >= len || (buf[i6 + 1] & 192) !== 128 || (buf[i6 + 2] & 192) !== 128 || (buf[i6 + 3] & 192) !== 128 || buf[i6] === 240 && (buf[i6 + 1] & 240) === 128 || // overlong
          buf[i6] === 244 && buf[i6 + 1] > 143 || buf[i6] > 244) {
            return false;
          }
          i6 += 4;
        } else {
          return false;
        }
      }
      return true;
    }
    module2.exports = isValidUTF8;
  }
});

// ../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/index.js
var require_utf_8_validate = __commonJS({
  "../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/index.js"(exports2, module2) {
    "use strict";
    try {
      module2.exports = require_node_gyp_build2()(__dirname);
    } catch (e6) {
      module2.exports = require_fallback2();
    }
  }
});

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

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

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

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

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

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

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

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

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

// ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/wrapper.mjs
var import_stream2, import_receiver, import_sender, import_websocket, import_websocket_server, wrapper_default;
var init_wrapper = __esm({
  "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/wrapper.mjs"() {
    "use strict";
    import_stream2 = __toESM(require_stream(), 1);
    import_receiver = __toESM(require_receiver(), 1);
    import_sender = __toESM(require_sender(), 1);
    import_websocket = __toESM(require_websocket(), 1);
    import_websocket_server = __toESM(require_websocket_server(), 1);
    wrapper_default = import_websocket.default;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/constants.js
var require_constants2 = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/constants.js"(exports2, module2) {
    "use strict";
    var SEMVER_SPEC_VERSION = "2.0.0";
    var MAX_LENGTH = 256;
    var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */
    9007199254740991;
    var MAX_SAFE_COMPONENT_LENGTH = 16;
    var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
    var RELEASE_TYPES = [
      "major",
      "premajor",
      "minor",
      "preminor",
      "patch",
      "prepatch",
      "prerelease"
    ];
    module2.exports = {
      MAX_LENGTH,
      MAX_SAFE_COMPONENT_LENGTH,
      MAX_SAFE_BUILD_LENGTH,
      MAX_SAFE_INTEGER,
      RELEASE_TYPES,
      SEMVER_SPEC_VERSION,
      FLAG_INCLUDE_PRERELEASE: 1,
      FLAG_LOOSE: 2
    };
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.js
var require_debug = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.js"(exports2, module2) {
    "use strict";
    var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {
    };
    module2.exports = debug;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.js
var require_re = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.js"(exports2, module2) {
    "use strict";
    var {
      MAX_SAFE_COMPONENT_LENGTH,
      MAX_SAFE_BUILD_LENGTH,
      MAX_LENGTH
    } = require_constants2();
    var debug = require_debug();
    exports2 = module2.exports = {};
    var re = exports2.re = [];
    var safeRe = exports2.safeRe = [];
    var src = exports2.src = [];
    var safeSrc = exports2.safeSrc = [];
    var t6 = exports2.t = {};
    var R = 0;
    var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
    var safeRegexReplacements = [
      ["\\s", 1],
      ["\\d", MAX_LENGTH],
      [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
    ];
    var makeSafeRegex = (value) => {
      for (const [token, max] of safeRegexReplacements) {
        value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);
      }
      return value;
    };
    var createToken = (name, value, isGlobal) => {
      const safe = makeSafeRegex(value);
      const index6 = R++;
      debug(name, index6, value);
      t6[name] = index6;
      src[index6] = value;
      safeSrc[index6] = safe;
      re[index6] = new RegExp(value, isGlobal ? "g" : void 0);
      safeRe[index6] = new RegExp(safe, isGlobal ? "g" : void 0);
    };
    createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
    createToken("NUMERICIDENTIFIERLOOSE", "\\d+");
    createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
    createToken("MAINVERSION", `(${src[t6.NUMERICIDENTIFIER]})\\.(${src[t6.NUMERICIDENTIFIER]})\\.(${src[t6.NUMERICIDENTIFIER]})`);
    createToken("MAINVERSIONLOOSE", `(${src[t6.NUMERICIDENTIFIERLOOSE]})\\.(${src[t6.NUMERICIDENTIFIERLOOSE]})\\.(${src[t6.NUMERICIDENTIFIERLOOSE]})`);
    createToken("PRERELEASEIDENTIFIER", `(?:${src[t6.NONNUMERICIDENTIFIER]}|${src[t6.NUMERICIDENTIFIER]})`);
    createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t6.NONNUMERICIDENTIFIER]}|${src[t6.NUMERICIDENTIFIERLOOSE]})`);
    createToken("PRERELEASE", `(?:-(${src[t6.PRERELEASEIDENTIFIER]}(?:\\.${src[t6.PRERELEASEIDENTIFIER]})*))`);
    createToken("PRERELEASELOOSE", `(?:-?(${src[t6.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t6.PRERELEASEIDENTIFIERLOOSE]})*))`);
    createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
    createToken("BUILD", `(?:\\+(${src[t6.BUILDIDENTIFIER]}(?:\\.${src[t6.BUILDIDENTIFIER]})*))`);
    createToken("FULLPLAIN", `v?${src[t6.MAINVERSION]}${src[t6.PRERELEASE]}?${src[t6.BUILD]}?`);
    createToken("FULL", `^${src[t6.FULLPLAIN]}$`);
    createToken("LOOSEPLAIN", `[v=\\s]*${src[t6.MAINVERSIONLOOSE]}${src[t6.PRERELEASELOOSE]}?${src[t6.BUILD]}?`);
    createToken("LOOSE", `^${src[t6.LOOSEPLAIN]}$`);
    createToken("GTLT", "((?:<|>)?=?)");
    createToken("XRANGEIDENTIFIERLOOSE", `${src[t6.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
    createToken("XRANGEIDENTIFIER", `${src[t6.NUMERICIDENTIFIER]}|x|X|\\*`);
    createToken("XRANGEPLAIN", `[v=\\s]*(${src[t6.XRANGEIDENTIFIER]})(?:\\.(${src[t6.XRANGEIDENTIFIER]})(?:\\.(${src[t6.XRANGEIDENTIFIER]})(?:${src[t6.PRERELEASE]})?${src[t6.BUILD]}?)?)?`);
    createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t6.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t6.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t6.XRANGEIDENTIFIERLOOSE]})(?:${src[t6.PRERELEASELOOSE]})?${src[t6.BUILD]}?)?)?`);
    createToken("XRANGE", `^${src[t6.GTLT]}\\s*${src[t6.XRANGEPLAIN]}$`);
    createToken("XRANGELOOSE", `^${src[t6.GTLT]}\\s*${src[t6.XRANGEPLAINLOOSE]}$`);
    createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
    createToken("COERCE", `${src[t6.COERCEPLAIN]}(?:$|[^\\d])`);
    createToken("COERCEFULL", src[t6.COERCEPLAIN] + `(?:${src[t6.PRERELEASE]})?(?:${src[t6.BUILD]})?(?:$|[^\\d])`);
    createToken("COERCERTL", src[t6.COERCE], true);
    createToken("COERCERTLFULL", src[t6.COERCEFULL], true);
    createToken("LONETILDE", "(?:~>?)");
    createToken("TILDETRIM", `(\\s*)${src[t6.LONETILDE]}\\s+`, true);
    exports2.tildeTrimReplace = "$1~";
    createToken("TILDE", `^${src[t6.LONETILDE]}${src[t6.XRANGEPLAIN]}$`);
    createToken("TILDELOOSE", `^${src[t6.LONETILDE]}${src[t6.XRANGEPLAINLOOSE]}$`);
    createToken("LONECARET", "(?:\\^)");
    createToken("CARETTRIM", `(\\s*)${src[t6.LONECARET]}\\s+`, true);
    exports2.caretTrimReplace = "$1^";
    createToken("CARET", `^${src[t6.LONECARET]}${src[t6.XRANGEPLAIN]}$`);
    createToken("CARETLOOSE", `^${src[t6.LONECARET]}${src[t6.XRANGEPLAINLOOSE]}$`);
    createToken("COMPARATORLOOSE", `^${src[t6.GTLT]}\\s*(${src[t6.LOOSEPLAIN]})$|^$`);
    createToken("COMPARATOR", `^${src[t6.GTLT]}\\s*(${src[t6.FULLPLAIN]})$|^$`);
    createToken("COMPARATORTRIM", `(\\s*)${src[t6.GTLT]}\\s*(${src[t6.LOOSEPLAIN]}|${src[t6.XRANGEPLAIN]})`, true);
    exports2.comparatorTrimReplace = "$1$2$3";
    createToken("HYPHENRANGE", `^\\s*(${src[t6.XRANGEPLAIN]})\\s+-\\s+(${src[t6.XRANGEPLAIN]})\\s*$`);
    createToken("HYPHENRANGELOOSE", `^\\s*(${src[t6.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t6.XRANGEPLAINLOOSE]})\\s*$`);
    createToken("STAR", "(<|>)?=?\\s*\\*");
    createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");
    createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.js
var require_parse_options = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.js"(exports2, module2) {
    "use strict";
    var looseOption = Object.freeze({ loose: true });
    var emptyOpts = Object.freeze({});
    var parseOptions = (options) => {
      if (!options) {
        return emptyOpts;
      }
      if (typeof options !== "object") {
        return looseOption;
      }
      return options;
    };
    module2.exports = parseOptions;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.js
var require_identifiers = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.js"(exports2, module2) {
    "use strict";
    var numeric = /^[0-9]+$/;
    var compareIdentifiers = (a5, b5) => {
      const anum = numeric.test(a5);
      const bnum = numeric.test(b5);
      if (anum && bnum) {
        a5 = +a5;
        b5 = +b5;
      }
      return a5 === b5 ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a5 < b5 ? -1 : 1;
    };
    var rcompareIdentifiers = (a5, b5) => compareIdentifiers(b5, a5);
    module2.exports = {
      compareIdentifiers,
      rcompareIdentifiers
    };
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.js
var require_semver = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.js"(exports2, module2) {
    "use strict";
    var debug = require_debug();
    var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants2();
    var { safeRe: re, t: t6 } = require_re();
    var parseOptions = require_parse_options();
    var { compareIdentifiers } = require_identifiers();
    var SemVer = class _SemVer {
      constructor(version, options) {
        options = parseOptions(options);
        if (version instanceof _SemVer) {
          if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
            return version;
          } else {
            version = version.version;
          }
        } else if (typeof version !== "string") {
          throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`);
        }
        if (version.length > MAX_LENGTH) {
          throw new TypeError(
            `version is longer than ${MAX_LENGTH} characters`
          );
        }
        debug("SemVer", version, options);
        this.options = options;
        this.loose = !!options.loose;
        this.includePrerelease = !!options.includePrerelease;
        const m6 = version.trim().match(options.loose ? re[t6.LOOSE] : re[t6.FULL]);
        if (!m6) {
          throw new TypeError(`Invalid Version: ${version}`);
        }
        this.raw = version;
        this.major = +m6[1];
        this.minor = +m6[2];
        this.patch = +m6[3];
        if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
          throw new TypeError("Invalid major version");
        }
        if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
          throw new TypeError("Invalid minor version");
        }
        if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
          throw new TypeError("Invalid patch version");
        }
        if (!m6[4]) {
          this.prerelease = [];
        } else {
          this.prerelease = m6[4].split(".").map((id) => {
            if (/^[0-9]+$/.test(id)) {
              const num = +id;
              if (num >= 0 && num < MAX_SAFE_INTEGER) {
                return num;
              }
            }
            return id;
          });
        }
        this.build = m6[5] ? m6[5].split(".") : [];
        this.format();
      }
      format() {
        this.version = `${this.major}.${this.minor}.${this.patch}`;
        if (this.prerelease.length) {
          this.version += `-${this.prerelease.join(".")}`;
        }
        return this.version;
      }
      toString() {
        return this.version;
      }
      compare(other) {
        debug("SemVer.compare", this.version, this.options, other);
        if (!(other instanceof _SemVer)) {
          if (typeof other === "string" && other === this.version) {
            return 0;
          }
          other = new _SemVer(other, this.options);
        }
        if (other.version === this.version) {
          return 0;
        }
        return this.compareMain(other) || this.comparePre(other);
      }
      compareMain(other) {
        if (!(other instanceof _SemVer)) {
          other = new _SemVer(other, this.options);
        }
        return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
      }
      comparePre(other) {
        if (!(other instanceof _SemVer)) {
          other = new _SemVer(other, this.options);
        }
        if (this.prerelease.length && !other.prerelease.length) {
          return -1;
        } else if (!this.prerelease.length && other.prerelease.length) {
          return 1;
        } else if (!this.prerelease.length && !other.prerelease.length) {
          return 0;
        }
        let i6 = 0;
        do {
          const a5 = this.prerelease[i6];
          const b5 = other.prerelease[i6];
          debug("prerelease compare", i6, a5, b5);
          if (a5 === void 0 && b5 === void 0) {
            return 0;
          } else if (b5 === void 0) {
            return 1;
          } else if (a5 === void 0) {
            return -1;
          } else if (a5 === b5) {
            continue;
          } else {
            return compareIdentifiers(a5, b5);
          }
        } while (++i6);
      }
      compareBuild(other) {
        if (!(other instanceof _SemVer)) {
          other = new _SemVer(other, this.options);
        }
        let i6 = 0;
        do {
          const a5 = this.build[i6];
          const b5 = other.build[i6];
          debug("build compare", i6, a5, b5);
          if (a5 === void 0 && b5 === void 0) {
            return 0;
          } else if (b5 === void 0) {
            return 1;
          } else if (a5 === void 0) {
            return -1;
          } else if (a5 === b5) {
            continue;
          } else {
            return compareIdentifiers(a5, b5);
          }
        } while (++i6);
      }
      // preminor will bump the version up to the next minor release, and immediately
      // down to pre-release. premajor and prepatch work the same way.
      inc(release2, identifier, identifierBase) {
        if (release2.startsWith("pre")) {
          if (!identifier && identifierBase === false) {
            throw new Error("invalid increment argument: identifier is empty");
          }
          if (identifier) {
            const match2 = `-${identifier}`.match(this.options.loose ? re[t6.PRERELEASELOOSE] : re[t6.PRERELEASE]);
            if (!match2 || match2[1] !== identifier) {
              throw new Error(`invalid identifier: ${identifier}`);
            }
          }
        }
        switch (release2) {
          case "premajor":
            this.prerelease.length = 0;
            this.patch = 0;
            this.minor = 0;
            this.major++;
            this.inc("pre", identifier, identifierBase);
            break;
          case "preminor":
            this.prerelease.length = 0;
            this.patch = 0;
            this.minor++;
            this.inc("pre", identifier, identifierBase);
            break;
          case "prepatch":
            this.prerelease.length = 0;
            this.inc("patch", identifier, identifierBase);
            this.inc("pre", identifier, identifierBase);
            break;
          // If the input is a non-prerelease version, this acts the same as
          // prepatch.
          case "prerelease":
            if (this.prerelease.length === 0) {
              this.inc("patch", identifier, identifierBase);
            }
            this.inc("pre", identifier, identifierBase);
            break;
          case "release":
            if (this.prerelease.length === 0) {
              throw new Error(`version ${this.raw} is not a prerelease`);
            }
            this.prerelease.length = 0;
            break;
          case "major":
            if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
              this.major++;
            }
            this.minor = 0;
            this.patch = 0;
            this.prerelease = [];
            break;
          case "minor":
            if (this.patch !== 0 || this.prerelease.length === 0) {
              this.minor++;
            }
            this.patch = 0;
            this.prerelease = [];
            break;
          case "patch":
            if (this.prerelease.length === 0) {
              this.patch++;
            }
            this.prerelease = [];
            break;
          // This probably shouldn't be used publicly.
          // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
          case "pre": {
            const base = Number(identifierBase) ? 1 : 0;
            if (this.prerelease.length === 0) {
              this.prerelease = [base];
            } else {
              let i6 = this.prerelease.length;
              while (--i6 >= 0) {
                if (typeof this.prerelease[i6] === "number") {
                  this.prerelease[i6]++;
                  i6 = -2;
                }
              }
              if (i6 === -1) {
                if (identifier === this.prerelease.join(".") && identifierBase === false) {
                  throw new Error("invalid increment argument: identifier already exists");
                }
                this.prerelease.push(base);
              }
            }
            if (identifier) {
              let prerelease = [identifier, base];
              if (identifierBase === false) {
                prerelease = [identifier];
              }
              if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
                if (isNaN(this.prerelease[1])) {
                  this.prerelease = prerelease;
                }
              } else {
                this.prerelease = prerelease;
              }
            }
            break;
          }
          default:
            throw new Error(`invalid increment argument: ${release2}`);
        }
        this.raw = this.format();
        if (this.build.length) {
          this.raw += `+${this.build.join(".")}`;
        }
        return this;
      }
    };
    module2.exports = SemVer;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/parse.js
var require_parse = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/parse.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var parse4 = (version, options, throwErrors = false) => {
      if (version instanceof SemVer) {
        return version;
      }
      try {
        return new SemVer(version, options);
      } catch (er) {
        if (!throwErrors) {
          return null;
        }
        throw er;
      }
    };
    module2.exports = parse4;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.js
var require_valid = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.js"(exports2, module2) {
    "use strict";
    var parse4 = require_parse();
    var valid = (version, options) => {
      const v6 = parse4(version, options);
      return v6 ? v6.version : null;
    };
    module2.exports = valid;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/clean.js
var require_clean = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/clean.js"(exports2, module2) {
    "use strict";
    var parse4 = require_parse();
    var clean = (version, options) => {
      const s6 = parse4(version.trim().replace(/^[=v]+/, ""), options);
      return s6 ? s6.version : null;
    };
    module2.exports = clean;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/inc.js
var require_inc = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/inc.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var inc = (version, release2, options, identifier, identifierBase) => {
      if (typeof options === "string") {
        identifierBase = identifier;
        identifier = options;
        options = void 0;
      }
      try {
        return new SemVer(
          version instanceof SemVer ? version.version : version,
          options
        ).inc(release2, identifier, identifierBase).version;
      } catch (er) {
        return null;
      }
    };
    module2.exports = inc;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/diff.js
var require_diff = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/diff.js"(exports2, module2) {
    "use strict";
    var parse4 = require_parse();
    var diff2 = (version1, version2) => {
      const v1 = parse4(version1, null, true);
      const v22 = parse4(version2, null, true);
      const comparison = v1.compare(v22);
      if (comparison === 0) {
        return null;
      }
      const v1Higher = comparison > 0;
      const highVersion = v1Higher ? v1 : v22;
      const lowVersion = v1Higher ? v22 : v1;
      const highHasPre = !!highVersion.prerelease.length;
      const lowHasPre = !!lowVersion.prerelease.length;
      if (lowHasPre && !highHasPre) {
        if (!lowVersion.patch && !lowVersion.minor) {
          return "major";
        }
        if (lowVersion.compareMain(highVersion) === 0) {
          if (lowVersion.minor && !lowVersion.patch) {
            return "minor";
          }
          return "patch";
        }
      }
      const prefix2 = highHasPre ? "pre" : "";
      if (v1.major !== v22.major) {
        return prefix2 + "major";
      }
      if (v1.minor !== v22.minor) {
        return prefix2 + "minor";
      }
      if (v1.patch !== v22.patch) {
        return prefix2 + "patch";
      }
      return "prerelease";
    };
    module2.exports = diff2;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/major.js
var require_major = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/major.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var major = (a5, loose) => new SemVer(a5, loose).major;
    module2.exports = major;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/minor.js
var require_minor = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/minor.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var minor = (a5, loose) => new SemVer(a5, loose).minor;
    module2.exports = minor;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/patch.js
var require_patch = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/patch.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var patch = (a5, loose) => new SemVer(a5, loose).patch;
    module2.exports = patch;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/prerelease.js
var require_prerelease = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/prerelease.js"(exports2, module2) {
    "use strict";
    var parse4 = require_parse();
    var prerelease = (version, options) => {
      const parsed = parse4(version, options);
      return parsed && parsed.prerelease.length ? parsed.prerelease : null;
    };
    module2.exports = prerelease;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare.js
var require_compare = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var compare = (a5, b5, loose) => new SemVer(a5, loose).compare(new SemVer(b5, loose));
    module2.exports = compare;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rcompare.js
var require_rcompare = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rcompare.js"(exports2, module2) {
    "use strict";
    var compare = require_compare();
    var rcompare = (a5, b5, loose) => compare(b5, a5, loose);
    module2.exports = rcompare;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-loose.js
var require_compare_loose = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-loose.js"(exports2, module2) {
    "use strict";
    var compare = require_compare();
    var compareLoose = (a5, b5) => compare(a5, b5, true);
    module2.exports = compareLoose;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-build.js
var require_compare_build = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-build.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var compareBuild = (a5, b5, loose) => {
      const versionA = new SemVer(a5, loose);
      const versionB = new SemVer(b5, loose);
      return versionA.compare(versionB) || versionA.compareBuild(versionB);
    };
    module2.exports = compareBuild;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/sort.js
var require_sort = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/sort.js"(exports2, module2) {
    "use strict";
    var compareBuild = require_compare_build();
    var sort = (list, loose) => list.sort((a5, b5) => compareBuild(a5, b5, loose));
    module2.exports = sort;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rsort.js
var require_rsort = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rsort.js"(exports2, module2) {
    "use strict";
    var compareBuild = require_compare_build();
    var rsort = (list, loose) => list.sort((a5, b5) => compareBuild(b5, a5, loose));
    module2.exports = rsort;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gt.js
var require_gt = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gt.js"(exports2, module2) {
    "use strict";
    var compare = require_compare();
    var gt = (a5, b5, loose) => compare(a5, b5, loose) > 0;
    module2.exports = gt;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lt.js
var require_lt = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lt.js"(exports2, module2) {
    "use strict";
    var compare = require_compare();
    var lt = (a5, b5, loose) => compare(a5, b5, loose) < 0;
    module2.exports = lt;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/eq.js
var require_eq = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/eq.js"(exports2, module2) {
    "use strict";
    var compare = require_compare();
    var eq = (a5, b5, loose) => compare(a5, b5, loose) === 0;
    module2.exports = eq;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/neq.js
var require_neq = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/neq.js"(exports2, module2) {
    "use strict";
    var compare = require_compare();
    var neq = (a5, b5, loose) => compare(a5, b5, loose) !== 0;
    module2.exports = neq;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gte.js
var require_gte = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gte.js"(exports2, module2) {
    "use strict";
    var compare = require_compare();
    var gte = (a5, b5, loose) => compare(a5, b5, loose) >= 0;
    module2.exports = gte;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lte.js
var require_lte = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lte.js"(exports2, module2) {
    "use strict";
    var compare = require_compare();
    var lte = (a5, b5, loose) => compare(a5, b5, loose) <= 0;
    module2.exports = lte;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/cmp.js
var require_cmp = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/cmp.js"(exports2, module2) {
    "use strict";
    var eq = require_eq();
    var neq = require_neq();
    var gt = require_gt();
    var gte = require_gte();
    var lt = require_lt();
    var lte = require_lte();
    var cmp = (a5, op, b5, loose) => {
      switch (op) {
        case "===":
          if (typeof a5 === "object") {
            a5 = a5.version;
          }
          if (typeof b5 === "object") {
            b5 = b5.version;
          }
          return a5 === b5;
        case "!==":
          if (typeof a5 === "object") {
            a5 = a5.version;
          }
          if (typeof b5 === "object") {
            b5 = b5.version;
          }
          return a5 !== b5;
        case "":
        case "=":
        case "==":
          return eq(a5, b5, loose);
        case "!=":
          return neq(a5, b5, loose);
        case ">":
          return gt(a5, b5, loose);
        case ">=":
          return gte(a5, b5, loose);
        case "<":
          return lt(a5, b5, loose);
        case "<=":
          return lte(a5, b5, loose);
        default:
          throw new TypeError(`Invalid operator: ${op}`);
      }
    };
    module2.exports = cmp;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/coerce.js
var require_coerce = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/coerce.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var parse4 = require_parse();
    var { safeRe: re, t: t6 } = require_re();
    var coerce2 = (version, options) => {
      if (version instanceof SemVer) {
        return version;
      }
      if (typeof version === "number") {
        version = String(version);
      }
      if (typeof version !== "string") {
        return null;
      }
      options = options || {};
      let match2 = null;
      if (!options.rtl) {
        match2 = version.match(options.includePrerelease ? re[t6.COERCEFULL] : re[t6.COERCE]);
      } else {
        const coerceRtlRegex = options.includePrerelease ? re[t6.COERCERTLFULL] : re[t6.COERCERTL];
        let next;
        while ((next = coerceRtlRegex.exec(version)) && (!match2 || match2.index + match2[0].length !== version.length)) {
          if (!match2 || next.index + next[0].length !== match2.index + match2[0].length) {
            match2 = next;
          }
          coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;
        }
        coerceRtlRegex.lastIndex = -1;
      }
      if (match2 === null) {
        return null;
      }
      const major = match2[2];
      const minor = match2[3] || "0";
      const patch = match2[4] || "0";
      const prerelease = options.includePrerelease && match2[5] ? `-${match2[5]}` : "";
      const build = options.includePrerelease && match2[6] ? `+${match2[6]}` : "";
      return parse4(`${major}.${minor}.${patch}${prerelease}${build}`, options);
    };
    module2.exports = coerce2;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/lrucache.js
var require_lrucache = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/lrucache.js"(exports2, module2) {
    "use strict";
    var LRUCache = class {
      constructor() {
        this.max = 1e3;
        this.map = /* @__PURE__ */ new Map();
      }
      get(key) {
        const value = this.map.get(key);
        if (value === void 0) {
          return void 0;
        } else {
          this.map.delete(key);
          this.map.set(key, value);
          return value;
        }
      }
      delete(key) {
        return this.map.delete(key);
      }
      set(key, value) {
        const deleted = this.delete(key);
        if (!deleted && value !== void 0) {
          if (this.map.size >= this.max) {
            const firstKey = this.map.keys().next().value;
            this.delete(firstKey);
          }
          this.map.set(key, value);
        }
        return this;
      }
    };
    module2.exports = LRUCache;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/range.js
var require_range = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/range.js"(exports2, module2) {
    "use strict";
    var SPACE_CHARACTERS = /\s+/g;
    var Range = class _Range {
      constructor(range, options) {
        options = parseOptions(options);
        if (range instanceof _Range) {
          if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
            return range;
          } else {
            return new _Range(range.raw, options);
          }
        }
        if (range instanceof Comparator) {
          this.raw = range.value;
          this.set = [[range]];
          this.formatted = void 0;
          return this;
        }
        this.options = options;
        this.loose = !!options.loose;
        this.includePrerelease = !!options.includePrerelease;
        this.raw = range.trim().replace(SPACE_CHARACTERS, " ");
        this.set = this.raw.split("||").map((r6) => this.parseRange(r6.trim())).filter((c5) => c5.length);
        if (!this.set.length) {
          throw new TypeError(`Invalid SemVer Range: ${this.raw}`);
        }
        if (this.set.length > 1) {
          const first = this.set[0];
          this.set = this.set.filter((c5) => !isNullSet(c5[0]));
          if (this.set.length === 0) {
            this.set = [first];
          } else if (this.set.length > 1) {
            for (const c5 of this.set) {
              if (c5.length === 1 && isAny(c5[0])) {
                this.set = [c5];
                break;
              }
            }
          }
        }
        this.formatted = void 0;
      }
      get range() {
        if (this.formatted === void 0) {
          this.formatted = "";
          for (let i6 = 0; i6 < this.set.length; i6++) {
            if (i6 > 0) {
              this.formatted += "||";
            }
            const comps = this.set[i6];
            for (let k5 = 0; k5 < comps.length; k5++) {
              if (k5 > 0) {
                this.formatted += " ";
              }
              this.formatted += comps[k5].toString().trim();
            }
          }
        }
        return this.formatted;
      }
      format() {
        return this.range;
      }
      toString() {
        return this.range;
      }
      parseRange(range) {
        const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
        const memoKey = memoOpts + ":" + range;
        const cached = cache5.get(memoKey);
        if (cached) {
          return cached;
        }
        const loose = this.options.loose;
        const hr = loose ? re[t6.HYPHENRANGELOOSE] : re[t6.HYPHENRANGE];
        range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
        debug("hyphen replace", range);
        range = range.replace(re[t6.COMPARATORTRIM], comparatorTrimReplace);
        debug("comparator trim", range);
        range = range.replace(re[t6.TILDETRIM], tildeTrimReplace);
        debug("tilde trim", range);
        range = range.replace(re[t6.CARETTRIM], caretTrimReplace);
        debug("caret trim", range);
        let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));
        if (loose) {
          rangeList = rangeList.filter((comp) => {
            debug("loose invalid filter", comp, this.options);
            return !!comp.match(re[t6.COMPARATORLOOSE]);
          });
        }
        debug("range list", rangeList);
        const rangeMap = /* @__PURE__ */ new Map();
        const comparators = rangeList.map((comp) => new Comparator(comp, this.options));
        for (const comp of comparators) {
          if (isNullSet(comp)) {
            return [comp];
          }
          rangeMap.set(comp.value, comp);
        }
        if (rangeMap.size > 1 && rangeMap.has("")) {
          rangeMap.delete("");
        }
        const result = [...rangeMap.values()];
        cache5.set(memoKey, result);
        return result;
      }
      intersects(range, options) {
        if (!(range instanceof _Range)) {
          throw new TypeError("a Range is required");
        }
        return this.set.some((thisComparators) => {
          return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => {
            return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => {
              return rangeComparators.every((rangeComparator) => {
                return thisComparator.intersects(rangeComparator, options);
              });
            });
          });
        });
      }
      // if ANY of the sets match ALL of its comparators, then pass
      test(version) {
        if (!version) {
          return false;
        }
        if (typeof version === "string") {
          try {
            version = new SemVer(version, this.options);
          } catch (er) {
            return false;
          }
        }
        for (let i6 = 0; i6 < this.set.length; i6++) {
          if (testSet(this.set[i6], version, this.options)) {
            return true;
          }
        }
        return false;
      }
    };
    module2.exports = Range;
    var LRU = require_lrucache();
    var cache5 = new LRU();
    var parseOptions = require_parse_options();
    var Comparator = require_comparator();
    var debug = require_debug();
    var SemVer = require_semver();
    var {
      safeRe: re,
      t: t6,
      comparatorTrimReplace,
      tildeTrimReplace,
      caretTrimReplace
    } = require_re();
    var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants2();
    var isNullSet = (c5) => c5.value === "<0.0.0-0";
    var isAny = (c5) => c5.value === "";
    var isSatisfiable = (comparators, options) => {
      let result = true;
      const remainingComparators = comparators.slice();
      let testComparator = remainingComparators.pop();
      while (result && remainingComparators.length) {
        result = remainingComparators.every((otherComparator) => {
          return testComparator.intersects(otherComparator, options);
        });
        testComparator = remainingComparators.pop();
      }
      return result;
    };
    var parseComparator = (comp, options) => {
      debug("comp", comp, options);
      comp = replaceCarets(comp, options);
      debug("caret", comp);
      comp = replaceTildes(comp, options);
      debug("tildes", comp);
      comp = replaceXRanges(comp, options);
      debug("xrange", comp);
      comp = replaceStars(comp, options);
      debug("stars", comp);
      return comp;
    };
    var isX = (id) => !id || id.toLowerCase() === "x" || id === "*";
    var replaceTildes = (comp, options) => {
      return comp.trim().split(/\s+/).map((c5) => replaceTilde(c5, options)).join(" ");
    };
    var replaceTilde = (comp, options) => {
      const r6 = options.loose ? re[t6.TILDELOOSE] : re[t6.TILDE];
      return comp.replace(r6, (_3, M, m6, p5, pr) => {
        debug("tilde", comp, _3, M, m6, p5, pr);
        let ret;
        if (isX(M)) {
          ret = "";
        } else if (isX(m6)) {
          ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
        } else if (isX(p5)) {
          ret = `>=${M}.${m6}.0 <${M}.${+m6 + 1}.0-0`;
        } else if (pr) {
          debug("replaceTilde pr", pr);
          ret = `>=${M}.${m6}.${p5}-${pr} <${M}.${+m6 + 1}.0-0`;
        } else {
          ret = `>=${M}.${m6}.${p5} <${M}.${+m6 + 1}.0-0`;
        }
        debug("tilde return", ret);
        return ret;
      });
    };
    var replaceCarets = (comp, options) => {
      return comp.trim().split(/\s+/).map((c5) => replaceCaret(c5, options)).join(" ");
    };
    var replaceCaret = (comp, options) => {
      debug("caret", comp, options);
      const r6 = options.loose ? re[t6.CARETLOOSE] : re[t6.CARET];
      const z2 = options.includePrerelease ? "-0" : "";
      return comp.replace(r6, (_3, M, m6, p5, pr) => {
        debug("caret", comp, _3, M, m6, p5, pr);
        let ret;
        if (isX(M)) {
          ret = "";
        } else if (isX(m6)) {
          ret = `>=${M}.0.0${z2} <${+M + 1}.0.0-0`;
        } else if (isX(p5)) {
          if (M === "0") {
            ret = `>=${M}.${m6}.0${z2} <${M}.${+m6 + 1}.0-0`;
          } else {
            ret = `>=${M}.${m6}.0${z2} <${+M + 1}.0.0-0`;
          }
        } else if (pr) {
          debug("replaceCaret pr", pr);
          if (M === "0") {
            if (m6 === "0") {
              ret = `>=${M}.${m6}.${p5}-${pr} <${M}.${m6}.${+p5 + 1}-0`;
            } else {
              ret = `>=${M}.${m6}.${p5}-${pr} <${M}.${+m6 + 1}.0-0`;
            }
          } else {
            ret = `>=${M}.${m6}.${p5}-${pr} <${+M + 1}.0.0-0`;
          }
        } else {
          debug("no pr");
          if (M === "0") {
            if (m6 === "0") {
              ret = `>=${M}.${m6}.${p5}${z2} <${M}.${m6}.${+p5 + 1}-0`;
            } else {
              ret = `>=${M}.${m6}.${p5}${z2} <${M}.${+m6 + 1}.0-0`;
            }
          } else {
            ret = `>=${M}.${m6}.${p5} <${+M + 1}.0.0-0`;
          }
        }
        debug("caret return", ret);
        return ret;
      });
    };
    var replaceXRanges = (comp, options) => {
      debug("replaceXRanges", comp, options);
      return comp.split(/\s+/).map((c5) => replaceXRange(c5, options)).join(" ");
    };
    var replaceXRange = (comp, options) => {
      comp = comp.trim();
      const r6 = options.loose ? re[t6.XRANGELOOSE] : re[t6.XRANGE];
      return comp.replace(r6, (ret, gtlt, M, m6, p5, pr) => {
        debug("xRange", comp, ret, gtlt, M, m6, p5, pr);
        const xM = isX(M);
        const xm = xM || isX(m6);
        const xp = xm || isX(p5);
        const anyX = xp;
        if (gtlt === "=" && anyX) {
          gtlt = "";
        }
        pr = options.includePrerelease ? "-0" : "";
        if (xM) {
          if (gtlt === ">" || gtlt === "<") {
            ret = "<0.0.0-0";
          } else {
            ret = "*";
          }
        } else if (gtlt && anyX) {
          if (xm) {
            m6 = 0;
          }
          p5 = 0;
          if (gtlt === ">") {
            gtlt = ">=";
            if (xm) {
              M = +M + 1;
              m6 = 0;
              p5 = 0;
            } else {
              m6 = +m6 + 1;
              p5 = 0;
            }
          } else if (gtlt === "<=") {
            gtlt = "<";
            if (xm) {
              M = +M + 1;
            } else {
              m6 = +m6 + 1;
            }
          }
          if (gtlt === "<") {
            pr = "-0";
          }
          ret = `${gtlt + M}.${m6}.${p5}${pr}`;
        } else if (xm) {
          ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
        } else if (xp) {
          ret = `>=${M}.${m6}.0${pr} <${M}.${+m6 + 1}.0-0`;
        }
        debug("xRange return", ret);
        return ret;
      });
    };
    var replaceStars = (comp, options) => {
      debug("replaceStars", comp, options);
      return comp.trim().replace(re[t6.STAR], "");
    };
    var replaceGTE0 = (comp, options) => {
      debug("replaceGTE0", comp, options);
      return comp.trim().replace(re[options.includePrerelease ? t6.GTE0PRE : t6.GTE0], "");
    };
    var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
      if (isX(fM)) {
        from = "";
      } else if (isX(fm)) {
        from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
      } else if (isX(fp)) {
        from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
      } else if (fpr) {
        from = `>=${from}`;
      } else {
        from = `>=${from}${incPr ? "-0" : ""}`;
      }
      if (isX(tM)) {
        to = "";
      } else if (isX(tm)) {
        to = `<${+tM + 1}.0.0-0`;
      } else if (isX(tp)) {
        to = `<${tM}.${+tm + 1}.0-0`;
      } else if (tpr) {
        to = `<=${tM}.${tm}.${tp}-${tpr}`;
      } else if (incPr) {
        to = `<${tM}.${tm}.${+tp + 1}-0`;
      } else {
        to = `<=${to}`;
      }
      return `${from} ${to}`.trim();
    };
    var testSet = (set, version, options) => {
      for (let i6 = 0; i6 < set.length; i6++) {
        if (!set[i6].test(version)) {
          return false;
        }
      }
      if (version.prerelease.length && !options.includePrerelease) {
        for (let i6 = 0; i6 < set.length; i6++) {
          debug(set[i6].semver);
          if (set[i6].semver === Comparator.ANY) {
            continue;
          }
          if (set[i6].semver.prerelease.length > 0) {
            const allowed = set[i6].semver;
            if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
              return true;
            }
          }
        }
        return false;
      }
      return true;
    };
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/comparator.js
var require_comparator = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/comparator.js"(exports2, module2) {
    "use strict";
    var ANY = Symbol("SemVer ANY");
    var Comparator = class _Comparator {
      static get ANY() {
        return ANY;
      }
      constructor(comp, options) {
        options = parseOptions(options);
        if (comp instanceof _Comparator) {
          if (comp.loose === !!options.loose) {
            return comp;
          } else {
            comp = comp.value;
          }
        }
        comp = comp.trim().split(/\s+/).join(" ");
        debug("comparator", comp, options);
        this.options = options;
        this.loose = !!options.loose;
        this.parse(comp);
        if (this.semver === ANY) {
          this.value = "";
        } else {
          this.value = this.operator + this.semver.version;
        }
        debug("comp", this);
      }
      parse(comp) {
        const r6 = this.options.loose ? re[t6.COMPARATORLOOSE] : re[t6.COMPARATOR];
        const m6 = comp.match(r6);
        if (!m6) {
          throw new TypeError(`Invalid comparator: ${comp}`);
        }
        this.operator = m6[1] !== void 0 ? m6[1] : "";
        if (this.operator === "=") {
          this.operator = "";
        }
        if (!m6[2]) {
          this.semver = ANY;
        } else {
          this.semver = new SemVer(m6[2], this.options.loose);
        }
      }
      toString() {
        return this.value;
      }
      test(version) {
        debug("Comparator.test", version, this.options.loose);
        if (this.semver === ANY || version === ANY) {
          return true;
        }
        if (typeof version === "string") {
          try {
            version = new SemVer(version, this.options);
          } catch (er) {
            return false;
          }
        }
        return cmp(version, this.operator, this.semver, this.options);
      }
      intersects(comp, options) {
        if (!(comp instanceof _Comparator)) {
          throw new TypeError("a Comparator is required");
        }
        if (this.operator === "") {
          if (this.value === "") {
            return true;
          }
          return new Range(comp.value, options).test(this.value);
        } else if (comp.operator === "") {
          if (comp.value === "") {
            return true;
          }
          return new Range(this.value, options).test(comp.semver);
        }
        options = parseOptions(options);
        if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) {
          return false;
        }
        if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) {
          return false;
        }
        if (this.operator.startsWith(">") && comp.operator.startsWith(">")) {
          return true;
        }
        if (this.operator.startsWith("<") && comp.operator.startsWith("<")) {
          return true;
        }
        if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {
          return true;
        }
        if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
          return true;
        }
        if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
          return true;
        }
        return false;
      }
    };
    module2.exports = Comparator;
    var parseOptions = require_parse_options();
    var { safeRe: re, t: t6 } = require_re();
    var cmp = require_cmp();
    var debug = require_debug();
    var SemVer = require_semver();
    var Range = require_range();
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/satisfies.js
var require_satisfies = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/satisfies.js"(exports2, module2) {
    "use strict";
    var Range = require_range();
    var satisfies = (version, range, options) => {
      try {
        range = new Range(range, options);
      } catch (er) {
        return false;
      }
      return range.test(version);
    };
    module2.exports = satisfies;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/to-comparators.js
var require_to_comparators = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/to-comparators.js"(exports2, module2) {
    "use strict";
    var Range = require_range();
    var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c5) => c5.value).join(" ").trim().split(" "));
    module2.exports = toComparators;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/max-satisfying.js
var require_max_satisfying = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/max-satisfying.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var Range = require_range();
    var maxSatisfying = (versions2, range, options) => {
      let max = null;
      let maxSV = null;
      let rangeObj = null;
      try {
        rangeObj = new Range(range, options);
      } catch (er) {
        return null;
      }
      versions2.forEach((v6) => {
        if (rangeObj.test(v6)) {
          if (!max || maxSV.compare(v6) === -1) {
            max = v6;
            maxSV = new SemVer(max, options);
          }
        }
      });
      return max;
    };
    module2.exports = maxSatisfying;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-satisfying.js
var require_min_satisfying = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-satisfying.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var Range = require_range();
    var minSatisfying = (versions2, range, options) => {
      let min = null;
      let minSV = null;
      let rangeObj = null;
      try {
        rangeObj = new Range(range, options);
      } catch (er) {
        return null;
      }
      versions2.forEach((v6) => {
        if (rangeObj.test(v6)) {
          if (!min || minSV.compare(v6) === 1) {
            min = v6;
            minSV = new SemVer(min, options);
          }
        }
      });
      return min;
    };
    module2.exports = minSatisfying;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-version.js
var require_min_version = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-version.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var Range = require_range();
    var gt = require_gt();
    var minVersion = (range, loose) => {
      range = new Range(range, loose);
      let minver = new SemVer("0.0.0");
      if (range.test(minver)) {
        return minver;
      }
      minver = new SemVer("0.0.0-0");
      if (range.test(minver)) {
        return minver;
      }
      minver = null;
      for (let i6 = 0; i6 < range.set.length; ++i6) {
        const comparators = range.set[i6];
        let setMin = null;
        comparators.forEach((comparator) => {
          const compver = new SemVer(comparator.semver.version);
          switch (comparator.operator) {
            case ">":
              if (compver.prerelease.length === 0) {
                compver.patch++;
              } else {
                compver.prerelease.push(0);
              }
              compver.raw = compver.format();
            /* fallthrough */
            case "":
            case ">=":
              if (!setMin || gt(compver, setMin)) {
                setMin = compver;
              }
              break;
            case "<":
            case "<=":
              break;
            /* istanbul ignore next */
            default:
              throw new Error(`Unexpected operation: ${comparator.operator}`);
          }
        });
        if (setMin && (!minver || gt(minver, setMin))) {
          minver = setMin;
        }
      }
      if (minver && range.test(minver)) {
        return minver;
      }
      return null;
    };
    module2.exports = minVersion;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/valid.js
var require_valid2 = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/valid.js"(exports2, module2) {
    "use strict";
    var Range = require_range();
    var validRange = (range, options) => {
      try {
        return new Range(range, options).range || "*";
      } catch (er) {
        return null;
      }
    };
    module2.exports = validRange;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/outside.js
var require_outside = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/outside.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var Comparator = require_comparator();
    var { ANY } = Comparator;
    var Range = require_range();
    var satisfies = require_satisfies();
    var gt = require_gt();
    var lt = require_lt();
    var lte = require_lte();
    var gte = require_gte();
    var outside = (version, range, hilo, options) => {
      version = new SemVer(version, options);
      range = new Range(range, options);
      let gtfn, ltefn, ltfn, comp, ecomp;
      switch (hilo) {
        case ">":
          gtfn = gt;
          ltefn = lte;
          ltfn = lt;
          comp = ">";
          ecomp = ">=";
          break;
        case "<":
          gtfn = lt;
          ltefn = gte;
          ltfn = gt;
          comp = "<";
          ecomp = "<=";
          break;
        default:
          throw new TypeError('Must provide a hilo val of "<" or ">"');
      }
      if (satisfies(version, range, options)) {
        return false;
      }
      for (let i6 = 0; i6 < range.set.length; ++i6) {
        const comparators = range.set[i6];
        let high = null;
        let low = null;
        comparators.forEach((comparator) => {
          if (comparator.semver === ANY) {
            comparator = new Comparator(">=0.0.0");
          }
          high = high || comparator;
          low = low || comparator;
          if (gtfn(comparator.semver, high.semver, options)) {
            high = comparator;
          } else if (ltfn(comparator.semver, low.semver, options)) {
            low = comparator;
          }
        });
        if (high.operator === comp || high.operator === ecomp) {
          return false;
        }
        if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
          return false;
        } else if (low.operator === ecomp && ltfn(version, low.semver)) {
          return false;
        }
      }
      return true;
    };
    module2.exports = outside;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/gtr.js
var require_gtr = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/gtr.js"(exports2, module2) {
    "use strict";
    var outside = require_outside();
    var gtr = (version, range, options) => outside(version, range, ">", options);
    module2.exports = gtr;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/ltr.js
var require_ltr = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/ltr.js"(exports2, module2) {
    "use strict";
    var outside = require_outside();
    var ltr = (version, range, options) => outside(version, range, "<", options);
    module2.exports = ltr;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/intersects.js
var require_intersects = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/intersects.js"(exports2, module2) {
    "use strict";
    var Range = require_range();
    var intersects = (r1, r22, options) => {
      r1 = new Range(r1, options);
      r22 = new Range(r22, options);
      return r1.intersects(r22, options);
    };
    module2.exports = intersects;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/simplify.js
var require_simplify = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/simplify.js"(exports2, module2) {
    "use strict";
    var satisfies = require_satisfies();
    var compare = require_compare();
    module2.exports = (versions2, range, options) => {
      const set = [];
      let first = null;
      let prev = null;
      const v6 = versions2.sort((a5, b5) => compare(a5, b5, options));
      for (const version of v6) {
        const included = satisfies(version, range, options);
        if (included) {
          prev = version;
          if (!first) {
            first = version;
          }
        } else {
          if (prev) {
            set.push([first, prev]);
          }
          prev = null;
          first = null;
        }
      }
      if (first) {
        set.push([first, null]);
      }
      const ranges = [];
      for (const [min, max] of set) {
        if (min === max) {
          ranges.push(min);
        } else if (!max && min === v6[0]) {
          ranges.push("*");
        } else if (!max) {
          ranges.push(`>=${min}`);
        } else if (min === v6[0]) {
          ranges.push(`<=${max}`);
        } else {
          ranges.push(`${min} - ${max}`);
        }
      }
      const simplified = ranges.join(" || ");
      const original = typeof range.raw === "string" ? range.raw : String(range);
      return simplified.length < original.length ? simplified : range;
    };
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/subset.js
var require_subset = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/subset.js"(exports2, module2) {
    "use strict";
    var Range = require_range();
    var Comparator = require_comparator();
    var { ANY } = Comparator;
    var satisfies = require_satisfies();
    var compare = require_compare();
    var subset = (sub, dom, options = {}) => {
      if (sub === dom) {
        return true;
      }
      sub = new Range(sub, options);
      dom = new Range(dom, options);
      let sawNonNull = false;
      OUTER: for (const simpleSub of sub.set) {
        for (const simpleDom of dom.set) {
          const isSub = simpleSubset(simpleSub, simpleDom, options);
          sawNonNull = sawNonNull || isSub !== null;
          if (isSub) {
            continue OUTER;
          }
        }
        if (sawNonNull) {
          return false;
        }
      }
      return true;
    };
    var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")];
    var minimumVersion = [new Comparator(">=0.0.0")];
    var simpleSubset = (sub, dom, options) => {
      if (sub === dom) {
        return true;
      }
      if (sub.length === 1 && sub[0].semver === ANY) {
        if (dom.length === 1 && dom[0].semver === ANY) {
          return true;
        } else if (options.includePrerelease) {
          sub = minimumVersionWithPreRelease;
        } else {
          sub = minimumVersion;
        }
      }
      if (dom.length === 1 && dom[0].semver === ANY) {
        if (options.includePrerelease) {
          return true;
        } else {
          dom = minimumVersion;
        }
      }
      const eqSet = /* @__PURE__ */ new Set();
      let gt, lt;
      for (const c5 of sub) {
        if (c5.operator === ">" || c5.operator === ">=") {
          gt = higherGT(gt, c5, options);
        } else if (c5.operator === "<" || c5.operator === "<=") {
          lt = lowerLT(lt, c5, options);
        } else {
          eqSet.add(c5.semver);
        }
      }
      if (eqSet.size > 1) {
        return null;
      }
      let gtltComp;
      if (gt && lt) {
        gtltComp = compare(gt.semver, lt.semver, options);
        if (gtltComp > 0) {
          return null;
        } else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) {
          return null;
        }
      }
      for (const eq of eqSet) {
        if (gt && !satisfies(eq, String(gt), options)) {
          return null;
        }
        if (lt && !satisfies(eq, String(lt), options)) {
          return null;
        }
        for (const c5 of dom) {
          if (!satisfies(eq, String(c5), options)) {
            return false;
          }
        }
        return true;
      }
      let higher, lower2;
      let hasDomLT, hasDomGT;
      let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false;
      let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false;
      if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) {
        needDomLTPre = false;
      }
      for (const c5 of dom) {
        hasDomGT = hasDomGT || c5.operator === ">" || c5.operator === ">=";
        hasDomLT = hasDomLT || c5.operator === "<" || c5.operator === "<=";
        if (gt) {
          if (needDomGTPre) {
            if (c5.semver.prerelease && c5.semver.prerelease.length && c5.semver.major === needDomGTPre.major && c5.semver.minor === needDomGTPre.minor && c5.semver.patch === needDomGTPre.patch) {
              needDomGTPre = false;
            }
          }
          if (c5.operator === ">" || c5.operator === ">=") {
            higher = higherGT(gt, c5, options);
            if (higher === c5 && higher !== gt) {
              return false;
            }
          } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c5), options)) {
            return false;
          }
        }
        if (lt) {
          if (needDomLTPre) {
            if (c5.semver.prerelease && c5.semver.prerelease.length && c5.semver.major === needDomLTPre.major && c5.semver.minor === needDomLTPre.minor && c5.semver.patch === needDomLTPre.patch) {
              needDomLTPre = false;
            }
          }
          if (c5.operator === "<" || c5.operator === "<=") {
            lower2 = lowerLT(lt, c5, options);
            if (lower2 === c5 && lower2 !== lt) {
              return false;
            }
          } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c5), options)) {
            return false;
          }
        }
        if (!c5.operator && (lt || gt) && gtltComp !== 0) {
          return false;
        }
      }
      if (gt && hasDomLT && !lt && gtltComp !== 0) {
        return false;
      }
      if (lt && hasDomGT && !gt && gtltComp !== 0) {
        return false;
      }
      if (needDomGTPre || needDomLTPre) {
        return false;
      }
      return true;
    };
    var higherGT = (a5, b5, options) => {
      if (!a5) {
        return b5;
      }
      const comp = compare(a5.semver, b5.semver, options);
      return comp > 0 ? a5 : comp < 0 ? b5 : b5.operator === ">" && a5.operator === ">=" ? b5 : a5;
    };
    var lowerLT = (a5, b5, options) => {
      if (!a5) {
        return b5;
      }
      const comp = compare(a5.semver, b5.semver, options);
      return comp < 0 ? a5 : comp > 0 ? b5 : b5.operator === "<" && a5.operator === "<=" ? b5 : a5;
    };
    module2.exports = subset;
  }
});

// ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/index.js
var require_semver2 = __commonJS({
  "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/index.js"(exports2, module2) {
    "use strict";
    var internalRe = require_re();
    var constants = require_constants2();
    var SemVer = require_semver();
    var identifiers = require_identifiers();
    var parse4 = require_parse();
    var valid = require_valid();
    var clean = require_clean();
    var inc = require_inc();
    var diff2 = require_diff();
    var major = require_major();
    var minor = require_minor();
    var patch = require_patch();
    var prerelease = require_prerelease();
    var compare = require_compare();
    var rcompare = require_rcompare();
    var compareLoose = require_compare_loose();
    var compareBuild = require_compare_build();
    var sort = require_sort();
    var rsort = require_rsort();
    var gt = require_gt();
    var lt = require_lt();
    var eq = require_eq();
    var neq = require_neq();
    var gte = require_gte();
    var lte = require_lte();
    var cmp = require_cmp();
    var coerce2 = require_coerce();
    var Comparator = require_comparator();
    var Range = require_range();
    var satisfies = require_satisfies();
    var toComparators = require_to_comparators();
    var maxSatisfying = require_max_satisfying();
    var minSatisfying = require_min_satisfying();
    var minVersion = require_min_version();
    var validRange = require_valid2();
    var outside = require_outside();
    var gtr = require_gtr();
    var ltr = require_ltr();
    var intersects = require_intersects();
    var simplifyRange = require_simplify();
    var subset = require_subset();
    module2.exports = {
      parse: parse4,
      valid,
      clean,
      inc,
      diff: diff2,
      major,
      minor,
      patch,
      prerelease,
      compare,
      rcompare,
      compareLoose,
      compareBuild,
      sort,
      rsort,
      gt,
      lt,
      eq,
      neq,
      gte,
      lte,
      cmp,
      coerce: coerce2,
      Comparator,
      Range,
      satisfies,
      toComparators,
      maxSatisfying,
      minSatisfying,
      minVersion,
      validRange,
      outside,
      gtr,
      ltr,
      intersects,
      simplifyRange,
      subset,
      SemVer,
      re: internalRe.re,
      src: internalRe.src,
      tokens: internalRe.t,
      SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
      RELEASE_TYPES: constants.RELEASE_TYPES,
      compareIdentifiers: identifiers.compareIdentifiers,
      rcompareIdentifiers: identifiers.rcompareIdentifiers
    };
  }
});

// src/cli/utils.ts
var import_semver, checkPackage, assertPackages;
var init_utils4 = __esm({
  "src/cli/utils.ts"() {
    "use strict";
    import_semver = __toESM(require_semver2());
    init_views();
    checkPackage = async (it) => {
      try {
        require(it);
        return true;
      } catch (e6) {
        return false;
      }
    };
    assertPackages = async (...pkgs) => {
      try {
        for (let i6 = 0; i6 < pkgs.length; i6++) {
          const it = pkgs[i6];
          require(it);
        }
      } catch (e6) {
        err(
          `please install required packages: ${pkgs.map((it) => `'${it}'`).join(" ")}`
        );
        process.exit(1);
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js
var getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig;
var init_httpExtensionConfiguration = __esm({
  "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js"() {
    "use strict";
    getHttpHandlerExtensionConfiguration = (runtimeConfig) => {
      return {
        setHttpHandler(handler) {
          runtimeConfig.httpHandler = handler;
        },
        httpHandler() {
          return runtimeConfig.httpHandler;
        },
        updateHttpClientConfig(key, value) {
          runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);
        },
        httpHandlerConfigs() {
          return runtimeConfig.httpHandler.httpHandlerConfigs();
        }
      };
    };
    resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {
      return {
        httpHandler: httpHandlerExtensionConfiguration.httpHandler()
      };
    };
  }
});

// ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
var init_extensions = __esm({
  "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/extensions/index.js"() {
    "use strict";
    init_httpExtensionConfiguration();
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/abort.js
var init_abort = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/abort.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/auth.js
var HttpAuthLocation;
var init_auth = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/auth.js"() {
    "use strict";
    (function(HttpAuthLocation2) {
      HttpAuthLocation2["HEADER"] = "header";
      HttpAuthLocation2["QUERY"] = "query";
    })(HttpAuthLocation || (HttpAuthLocation = {}));
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js
var HttpApiKeyAuthLocation;
var init_HttpApiKeyAuth = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js"() {
    "use strict";
    (function(HttpApiKeyAuthLocation2) {
      HttpApiKeyAuthLocation2["HEADER"] = "header";
      HttpApiKeyAuthLocation2["QUERY"] = "query";
    })(HttpApiKeyAuthLocation || (HttpApiKeyAuthLocation = {}));
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js
var init_HttpAuthScheme = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js
var init_HttpAuthSchemeProvider = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpSigner.js
var init_HttpSigner = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpSigner.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js
var init_IdentityProviderConfig = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/index.js
var init_auth2 = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/index.js"() {
    "use strict";
    init_auth();
    init_HttpApiKeyAuth();
    init_HttpAuthScheme();
    init_HttpAuthSchemeProvider();
    init_HttpSigner();
    init_IdentityProviderConfig();
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js
var init_blob_payload_input_types = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/checksum.js
var init_checksum = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/checksum.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/client.js
var init_client = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/client.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/command.js
var init_command = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/command.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/config.js
var init_config = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/config.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/manager.js
var init_manager = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/manager.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/pool.js
var init_pool = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/pool.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/index.js
var init_connection = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/index.js"() {
    "use strict";
    init_config();
    init_manager();
    init_pool();
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/crypto.js
var init_crypto2 = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/crypto.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/encode.js
var init_encode = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/encode.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoint.js
var EndpointURLScheme;
var init_endpoint = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoint.js"() {
    "use strict";
    (function(EndpointURLScheme2) {
      EndpointURLScheme2["HTTP"] = "http";
      EndpointURLScheme2["HTTPS"] = "https";
    })(EndpointURLScheme || (EndpointURLScheme = {}));
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js
var init_EndpointRuleObject = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js
var init_ErrorRuleObject = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js
var init_RuleSetObject = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/shared.js
var init_shared = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/shared.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js
var init_TreeRuleObject = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/index.js
var init_endpoints = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/index.js"() {
    "use strict";
    init_EndpointRuleObject();
    init_ErrorRuleObject();
    init_RuleSetObject();
    init_shared();
    init_TreeRuleObject();
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/eventStream.js
var init_eventStream = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/eventStream.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/checksum.js
var AlgorithmId;
var init_checksum2 = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/checksum.js"() {
    "use strict";
    (function(AlgorithmId2) {
      AlgorithmId2["MD5"] = "md5";
      AlgorithmId2["CRC32"] = "crc32";
      AlgorithmId2["CRC32C"] = "crc32c";
      AlgorithmId2["SHA1"] = "sha1";
      AlgorithmId2["SHA256"] = "sha256";
    })(AlgorithmId || (AlgorithmId = {}));
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js
var init_defaultClientConfiguration = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js"() {
    "use strict";
    init_checksum2();
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js
var init_defaultExtensionConfiguration = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/index.js
var init_extensions2 = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/index.js"() {
    "use strict";
    init_defaultClientConfiguration();
    init_defaultExtensionConfiguration();
    init_checksum2();
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/feature-ids.js
var init_feature_ids = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/feature-ids.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/http.js
var FieldPosition;
var init_http = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/http.js"() {
    "use strict";
    (function(FieldPosition2) {
      FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
      FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
    })(FieldPosition || (FieldPosition = {}));
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js
var init_httpHandlerInitialization = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js
var init_apiKeyIdentity = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js
var init_awsCredentialIdentity = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/identity.js
var init_identity = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/identity.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/tokenIdentity.js
var init_tokenIdentity = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/tokenIdentity.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/index.js
var init_identity2 = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/index.js"() {
    "use strict";
    init_apiKeyIdentity();
    init_awsCredentialIdentity();
    init_identity();
    init_tokenIdentity();
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/logger.js
var init_logger = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/logger.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/middleware.js
var SMITHY_CONTEXT_KEY;
var init_middleware = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/middleware.js"() {
    "use strict";
    SMITHY_CONTEXT_KEY = "__smithy_context";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/pagination.js
var init_pagination = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/pagination.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/profile.js
var IniSectionType;
var init_profile = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/profile.js"() {
    "use strict";
    (function(IniSectionType2) {
      IniSectionType2["PROFILE"] = "profile";
      IniSectionType2["SSO_SESSION"] = "sso-session";
      IniSectionType2["SERVICES"] = "services";
    })(IniSectionType || (IniSectionType = {}));
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/response.js
var init_response2 = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/response.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/retry.js
var init_retry = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/retry.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/schema/schema.js
var init_schema = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/schema/schema.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/schema/sentinels.js
var init_sentinels = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/schema/sentinels.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/serde.js
var init_serde = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/serde.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/shapes.js
var init_shapes = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/shapes.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/signature.js
var init_signature = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/signature.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/stream.js
var init_stream = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/stream.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js
var init_streaming_blob_common_types = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js
var init_streaming_blob_payload_input_types = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js
var init_streaming_blob_payload_output_types = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transfer.js
var RequestHandlerProtocol;
var init_transfer = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transfer.js"() {
    "use strict";
    (function(RequestHandlerProtocol2) {
      RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
      RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
      RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
    })(RequestHandlerProtocol || (RequestHandlerProtocol = {}));
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js
var init_client_payload_blob_type_narrow = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/mutable.js
var init_mutable = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/mutable.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/no-undefined.js
var init_no_undefined = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/no-undefined.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/type-transform.js
var init_type_transform = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/type-transform.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/uri.js
var init_uri = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/uri.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/util.js
var init_util2 = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/util.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/waiter.js
var init_waiter = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/waiter.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/index.js
var init_dist_es = __esm({
  "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/index.js"() {
    "use strict";
    init_abort();
    init_auth2();
    init_blob_payload_input_types();
    init_checksum();
    init_client();
    init_command();
    init_connection();
    init_crypto2();
    init_encode();
    init_endpoint();
    init_endpoints();
    init_eventStream();
    init_extensions2();
    init_feature_ids();
    init_http();
    init_httpHandlerInitialization();
    init_identity2();
    init_logger();
    init_middleware();
    init_pagination();
    init_profile();
    init_response2();
    init_retry();
    init_schema();
    init_sentinels();
    init_serde();
    init_shapes();
    init_signature();
    init_stream();
    init_streaming_blob_common_types();
    init_streaming_blob_payload_input_types();
    init_streaming_blob_payload_output_types();
    init_transfer();
    init_client_payload_blob_type_narrow();
    init_mutable();
    init_no_undefined();
    init_type_transform();
    init_uri();
    init_util2();
    init_waiter();
  }
});

// ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/Field.js
var init_Field = __esm({
  "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/Field.js"() {
    "use strict";
    init_dist_es();
  }
});

// ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/Fields.js
var init_Fields = __esm({
  "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/Fields.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
var init_httpHandler = __esm({
  "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/httpHandler.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/httpRequest.js
function cloneQuery(query) {
  return Object.keys(query).reduce((carry, paramName) => {
    const param = query[paramName];
    return {
      ...carry,
      [paramName]: Array.isArray(param) ? [...param] : param
    };
  }, {});
}
var HttpRequest;
var init_httpRequest = __esm({
  "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/httpRequest.js"() {
    "use strict";
    HttpRequest = class _HttpRequest {
      constructor(options) {
        this.method = options.method || "GET";
        this.hostname = options.hostname || "localhost";
        this.port = options.port;
        this.query = options.query || {};
        this.headers = options.headers || {};
        this.body = options.body;
        this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
        this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
        this.username = options.username;
        this.password = options.password;
        this.fragment = options.fragment;
      }
      static clone(request2) {
        const cloned = new _HttpRequest({
          ...request2,
          headers: { ...request2.headers }
        });
        if (cloned.query) {
          cloned.query = cloneQuery(cloned.query);
        }
        return cloned;
      }
      static isInstance(request2) {
        if (!request2) {
          return false;
        }
        const req = request2;
        return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
      }
      clone() {
        return _HttpRequest.clone(this);
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/httpResponse.js
var HttpResponse;
var init_httpResponse = __esm({
  "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/httpResponse.js"() {
    "use strict";
    HttpResponse = class {
      constructor(options) {
        this.statusCode = options.statusCode;
        this.reason = options.reason;
        this.headers = options.headers || {};
        this.body = options.body;
      }
      static isInstance(response) {
        if (!response)
          return false;
        const resp = response;
        return typeof resp.statusCode === "number" && typeof resp.headers === "object";
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js
var init_isValidHostname = __esm({
  "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/types.js
var init_types2 = __esm({
  "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/types.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/index.js
var init_dist_es2 = __esm({
  "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/index.js"() {
    "use strict";
    init_extensions();
    init_Field();
    init_Fields();
    init_httpHandler();
    init_httpRequest();
    init_httpResponse();
    init_isValidHostname();
    init_types2();
  }
});

// ../node_modules/.pnpm/@aws-sdk+middleware-host-header@3.804.0/node_modules/@aws-sdk/middleware-host-header/dist-es/index.js
function resolveHostHeaderConfig(input) {
  return input;
}
var hostHeaderMiddleware, hostHeaderMiddlewareOptions, getHostHeaderPlugin;
var init_dist_es3 = __esm({
  "../node_modules/.pnpm/@aws-sdk+middleware-host-header@3.804.0/node_modules/@aws-sdk/middleware-host-header/dist-es/index.js"() {
    "use strict";
    init_dist_es2();
    hostHeaderMiddleware = (options) => (next) => async (args) => {
      if (!HttpRequest.isInstance(args.request))
        return next(args);
      const { request: request2 } = args;
      const { handlerProtocol = "" } = options.requestHandler.metadata || {};
      if (handlerProtocol.indexOf("h2") >= 0 && !request2.headers[":authority"]) {
        delete request2.headers["host"];
        request2.headers[":authority"] = request2.hostname + (request2.port ? ":" + request2.port : "");
      } else if (!request2.headers["host"]) {
        let host = request2.hostname;
        if (request2.port != null)
          host += `:${request2.port}`;
        request2.headers["host"] = host;
      }
      return next(args);
    };
    hostHeaderMiddlewareOptions = {
      name: "hostHeaderMiddleware",
      step: "build",
      priority: "low",
      tags: ["HOST"],
      override: true
    };
    getHostHeaderPlugin = (options) => ({
      applyToStack: (clientStack) => {
        clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions);
      }
    });
  }
});

// ../node_modules/.pnpm/@aws-sdk+middleware-logger@3.804.0/node_modules/@aws-sdk/middleware-logger/dist-es/loggerMiddleware.js
var loggerMiddleware, loggerMiddlewareOptions, getLoggerPlugin;
var init_loggerMiddleware = __esm({
  "../node_modules/.pnpm/@aws-sdk+middleware-logger@3.804.0/node_modules/@aws-sdk/middleware-logger/dist-es/loggerMiddleware.js"() {
    "use strict";
    loggerMiddleware = () => (next, context) => async (args) => {
      try {
        const response = await next(args);
        const { clientName, commandName, logger: logger2, dynamoDbDocumentClientOptions = {} } = context;
        const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
        const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog;
        const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog;
        const { $metadata, ...outputWithoutMetadata } = response.output;
        logger2?.info?.({
          clientName,
          commandName,
          input: inputFilterSensitiveLog(args.input),
          output: outputFilterSensitiveLog(outputWithoutMetadata),
          metadata: $metadata
        });
        return response;
      } catch (error2) {
        const { clientName, commandName, logger: logger2, dynamoDbDocumentClientOptions = {} } = context;
        const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
        const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog;
        logger2?.error?.({
          clientName,
          commandName,
          input: inputFilterSensitiveLog(args.input),
          error: error2,
          metadata: error2.$metadata
        });
        throw error2;
      }
    };
    loggerMiddlewareOptions = {
      name: "loggerMiddleware",
      tags: ["LOGGER"],
      step: "initialize",
      override: true
    };
    getLoggerPlugin = (options) => ({
      applyToStack: (clientStack) => {
        clientStack.add(loggerMiddleware(), loggerMiddlewareOptions);
      }
    });
  }
});

// ../node_modules/.pnpm/@aws-sdk+middleware-logger@3.804.0/node_modules/@aws-sdk/middleware-logger/dist-es/index.js
var init_dist_es4 = __esm({
  "../node_modules/.pnpm/@aws-sdk+middleware-logger@3.804.0/node_modules/@aws-sdk/middleware-logger/dist-es/index.js"() {
    "use strict";
    init_loggerMiddleware();
  }
});

// ../node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.804.0/node_modules/@aws-sdk/middleware-recursion-detection/dist-es/index.js
var TRACE_ID_HEADER_NAME, ENV_LAMBDA_FUNCTION_NAME, ENV_TRACE_ID, recursionDetectionMiddleware, addRecursionDetectionMiddlewareOptions, getRecursionDetectionPlugin;
var init_dist_es5 = __esm({
  "../node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.804.0/node_modules/@aws-sdk/middleware-recursion-detection/dist-es/index.js"() {
    "use strict";
    init_dist_es2();
    TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id";
    ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME";
    ENV_TRACE_ID = "_X_AMZN_TRACE_ID";
    recursionDetectionMiddleware = (options) => (next) => async (args) => {
      const { request: request2 } = args;
      if (!HttpRequest.isInstance(request2) || options.runtime !== "node") {
        return next(args);
      }
      const traceIdHeader = Object.keys(request2.headers ?? {}).find((h6) => h6.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? TRACE_ID_HEADER_NAME;
      if (request2.headers.hasOwnProperty(traceIdHeader)) {
        return next(args);
      }
      const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME];
      const traceId = process.env[ENV_TRACE_ID];
      const nonEmptyString = (str) => typeof str === "string" && str.length > 0;
      if (nonEmptyString(functionName) && nonEmptyString(traceId)) {
        request2.headers[TRACE_ID_HEADER_NAME] = traceId;
      }
      return next({
        ...args,
        request: request2
      });
    };
    addRecursionDetectionMiddlewareOptions = {
      step: "build",
      tags: ["RECURSION_DETECTION"],
      name: "recursionDetectionMiddleware",
      override: true,
      priority: "low"
    };
    getRecursionDetectionPlugin = (options) => ({
      applyToStack: (clientStack) => {
        clientStack.add(recursionDetectionMiddleware(options), addRecursionDetectionMiddlewareOptions);
      }
    });
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/getSmithyContext.js
var init_getSmithyContext = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/getSmithyContext.js"() {
    "use strict";
    init_dist_es();
  }
});

// ../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-es/getSmithyContext.js
var getSmithyContext;
var init_getSmithyContext2 = __esm({
  "../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-es/getSmithyContext.js"() {
    "use strict";
    init_dist_es();
    getSmithyContext = (context) => context[SMITHY_CONTEXT_KEY] || (context[SMITHY_CONTEXT_KEY] = {});
  }
});

// ../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js
var normalizeProvider;
var init_normalizeProvider = __esm({
  "../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js"() {
    "use strict";
    normalizeProvider = (input) => {
      if (typeof input === "function")
        return input;
      const promisified = Promise.resolve(input);
      return () => promisified;
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-es/index.js
var init_dist_es6 = __esm({
  "../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-es/index.js"() {
    "use strict";
    init_getSmithyContext2();
    init_normalizeProvider();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js
var resolveAuthOptions;
var init_resolveAuthOptions = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js"() {
    "use strict";
    resolveAuthOptions = (candidateAuthOptions, authSchemePreference) => {
      if (!authSchemePreference || authSchemePreference.length === 0) {
        return candidateAuthOptions;
      }
      const preferredAuthOptions = [];
      for (const preferredSchemeName of authSchemePreference) {
        for (const candidateAuthOption of candidateAuthOptions) {
          const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1];
          if (candidateAuthSchemeName === preferredSchemeName) {
            preferredAuthOptions.push(candidateAuthOption);
          }
        }
      }
      for (const candidateAuthOption of candidateAuthOptions) {
        if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) {
          preferredAuthOptions.push(candidateAuthOption);
        }
      }
      return preferredAuthOptions;
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js
function convertHttpAuthSchemesToMap(httpAuthSchemes) {
  const map2 = /* @__PURE__ */ new Map();
  for (const scheme of httpAuthSchemes) {
    map2.set(scheme.schemeId, scheme);
  }
  return map2;
}
var httpAuthSchemeMiddleware;
var init_httpAuthSchemeMiddleware = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js"() {
    "use strict";
    init_dist_es();
    init_dist_es6();
    init_resolveAuthOptions();
    httpAuthSchemeMiddleware = (config, mwOptions) => (next, context) => async (args) => {
      const options = config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input));
      const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : [];
      const resolvedOptions = resolveAuthOptions(options, authSchemePreference);
      const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes);
      const smithyContext = getSmithyContext(context);
      const failureReasons = [];
      for (const option of resolvedOptions) {
        const scheme = authSchemes.get(option.schemeId);
        if (!scheme) {
          failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`);
          continue;
        }
        const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config));
        if (!identityProvider) {
          failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`);
          continue;
        }
        const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {};
        option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties);
        option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties);
        smithyContext.selectedHttpAuthScheme = {
          httpAuthOption: option,
          identity: await identityProvider(option.identityProperties),
          signer: scheme.signer
        };
        break;
      }
      if (!smithyContext.selectedHttpAuthScheme) {
        throw new Error(failureReasons.join("\n"));
      }
      return next(args);
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js
var httpAuthSchemeEndpointRuleSetMiddlewareOptions, getHttpAuthSchemeEndpointRuleSetPlugin;
var init_getHttpAuthSchemeEndpointRuleSetPlugin = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js"() {
    "use strict";
    init_httpAuthSchemeMiddleware();
    httpAuthSchemeEndpointRuleSetMiddlewareOptions = {
      step: "serialize",
      tags: ["HTTP_AUTH_SCHEME"],
      name: "httpAuthSchemeMiddleware",
      override: true,
      relation: "before",
      toMiddleware: "endpointV2Middleware"
    };
    getHttpAuthSchemeEndpointRuleSetPlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({
      applyToStack: (clientStack) => {
        clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, {
          httpAuthSchemeParametersProvider,
          identityProviderConfigProvider
        }), httpAuthSchemeEndpointRuleSetMiddlewareOptions);
      }
    });
  }
});

// ../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/deserializerMiddleware.js
var deserializerMiddleware, findHeader;
var init_deserializerMiddleware = __esm({
  "../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/deserializerMiddleware.js"() {
    "use strict";
    init_dist_es2();
    deserializerMiddleware = (options, deserializer) => (next, context) => async (args) => {
      const { response } = await next(args);
      try {
        const parsed = await deserializer(response, options);
        return {
          response,
          output: parsed
        };
      } catch (error2) {
        Object.defineProperty(error2, "$response", {
          value: response
        });
        if (!("$metadata" in error2)) {
          const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`;
          try {
            error2.message += "\n  " + hint;
          } catch (e6) {
            if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") {
              console.warn(hint);
            } else {
              context.logger?.warn?.(hint);
            }
          }
          if (typeof error2.$responseBodyText !== "undefined") {
            if (error2.$response) {
              error2.$response.body = error2.$responseBodyText;
            }
          }
          try {
            if (HttpResponse.isInstance(response)) {
              const { headers = {} } = response;
              const headerEntries = Object.entries(headers);
              error2.$metadata = {
                httpStatusCode: response.statusCode,
                requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries),
                extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries),
                cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries)
              };
            }
          } catch (e6) {
          }
        }
        throw error2;
      }
    };
    findHeader = (pattern, headers) => {
      return (headers.find(([k5]) => {
        return k5.match(pattern);
      }) || [void 0, void 0])[1];
    };
  }
});

// ../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/serializerMiddleware.js
var serializerMiddleware;
var init_serializerMiddleware = __esm({
  "../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/serializerMiddleware.js"() {
    "use strict";
    serializerMiddleware = (options, serializer) => (next, context) => async (args) => {
      const endpointConfig = options;
      const endpoint = context.endpointV2?.url && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context.endpointV2.url) : endpointConfig.endpoint;
      if (!endpoint) {
        throw new Error("No valid endpoint provider available.");
      }
      const request2 = await serializer(args.input, { ...options, endpoint });
      return next({
        ...args,
        request: request2
      });
    };
  }
});

// ../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/serdePlugin.js
function getSerdePlugin(config, serializer, deserializer) {
  return {
    applyToStack: (commandStack) => {
      commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption);
      commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption);
    }
  };
}
var deserializerMiddlewareOption, serializerMiddlewareOption;
var init_serdePlugin = __esm({
  "../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/serdePlugin.js"() {
    "use strict";
    init_deserializerMiddleware();
    init_serializerMiddleware();
    deserializerMiddlewareOption = {
      name: "deserializerMiddleware",
      step: "deserialize",
      tags: ["DESERIALIZER"],
      override: true
    };
    serializerMiddlewareOption = {
      name: "serializerMiddleware",
      step: "serialize",
      tags: ["SERIALIZER"],
      override: true
    };
  }
});

// ../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/index.js
var init_dist_es7 = __esm({
  "../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/index.js"() {
    "use strict";
    init_deserializerMiddleware();
    init_serdePlugin();
    init_serializerMiddleware();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js
var httpAuthSchemeMiddlewareOptions;
var init_getHttpAuthSchemePlugin = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js"() {
    "use strict";
    init_dist_es7();
    init_httpAuthSchemeMiddleware();
    httpAuthSchemeMiddlewareOptions = {
      step: "serialize",
      tags: ["HTTP_AUTH_SCHEME"],
      name: "httpAuthSchemeMiddleware",
      override: true,
      relation: "before",
      toMiddleware: serializerMiddlewareOption.name
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js
var init_middleware_http_auth_scheme = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js"() {
    "use strict";
    init_httpAuthSchemeMiddleware();
    init_getHttpAuthSchemeEndpointRuleSetPlugin();
    init_getHttpAuthSchemePlugin();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js
var defaultErrorHandler, defaultSuccessHandler, httpSigningMiddleware;
var init_httpSigningMiddleware = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js"() {
    "use strict";
    init_dist_es2();
    init_dist_es();
    init_dist_es6();
    defaultErrorHandler = (signingProperties) => (error2) => {
      throw error2;
    };
    defaultSuccessHandler = (httpResponse, signingProperties) => {
    };
    httpSigningMiddleware = (config) => (next, context) => async (args) => {
      if (!HttpRequest.isInstance(args.request)) {
        return next(args);
      }
      const smithyContext = getSmithyContext(context);
      const scheme = smithyContext.selectedHttpAuthScheme;
      if (!scheme) {
        throw new Error(`No HttpAuthScheme was selected: unable to sign request`);
      }
      const { httpAuthOption: { signingProperties = {} }, identity, signer } = scheme;
      const output = await next({
        ...args,
        request: await signer.sign(args.request, identity, signingProperties)
      }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties));
      (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties);
      return output;
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js
var httpSigningMiddlewareOptions, getHttpSigningPlugin;
var init_getHttpSigningMiddleware = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js"() {
    "use strict";
    init_httpSigningMiddleware();
    httpSigningMiddlewareOptions = {
      step: "finalizeRequest",
      tags: ["HTTP_SIGNING"],
      name: "httpSigningMiddleware",
      aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"],
      override: true,
      relation: "after",
      toMiddleware: "retryMiddleware"
    };
    getHttpSigningPlugin = (config) => ({
      applyToStack: (clientStack) => {
        clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions);
      }
    });
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js
var init_middleware_http_signing = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js"() {
    "use strict";
    init_httpSigningMiddleware();
    init_getHttpSigningMiddleware();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/normalizeProvider.js
var normalizeProvider2;
var init_normalizeProvider2 = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/normalizeProvider.js"() {
    "use strict";
    normalizeProvider2 = (input) => {
      if (typeof input === "function")
        return input;
      const promisified = Promise.resolve(input);
      return () => promisified;
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/pagination/createPaginator.js
function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) {
  return async function* paginateOperation(config, input, ...additionalArguments) {
    const _input = input;
    let token = config.startingToken ?? _input[inputTokenName];
    let hasNext = true;
    let page;
    while (hasNext) {
      _input[inputTokenName] = token;
      if (pageSizeTokenName) {
        _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize;
      }
      if (config.client instanceof ClientCtor) {
        page = await makePagedClientRequest(CommandCtor, config.client, input, config.withCommand, ...additionalArguments);
      } else {
        throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`);
      }
      yield page;
      const prevToken = token;
      token = get(page, outputTokenName);
      hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken));
    }
    return void 0;
  };
}
var makePagedClientRequest, get;
var init_createPaginator = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/pagination/createPaginator.js"() {
    "use strict";
    makePagedClientRequest = async (CommandCtor, client, input, withCommand = (_3) => _3, ...args) => {
      let command = new CommandCtor(input);
      command = withCommand(command) ?? command;
      return await client.send(command, ...args);
    };
    get = (fromObject, path3) => {
      let cursor = fromObject;
      const pathComponents = path3.split(".");
      for (const step of pathComponents) {
        if (!cursor || typeof cursor !== "object") {
          return void 0;
        }
        cursor = cursor[step];
      }
      return cursor;
    };
  }
});

// ../node_modules/.pnpm/@smithy+is-array-buffer@4.0.0/node_modules/@smithy/is-array-buffer/dist-es/index.js
var isArrayBuffer;
var init_dist_es8 = __esm({
  "../node_modules/.pnpm/@smithy+is-array-buffer@4.0.0/node_modules/@smithy/is-array-buffer/dist-es/index.js"() {
    "use strict";
    isArrayBuffer = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
  }
});

// ../node_modules/.pnpm/@smithy+util-buffer-from@4.0.0/node_modules/@smithy/util-buffer-from/dist-es/index.js
var import_buffer2, fromArrayBuffer, fromString;
var init_dist_es9 = __esm({
  "../node_modules/.pnpm/@smithy+util-buffer-from@4.0.0/node_modules/@smithy/util-buffer-from/dist-es/index.js"() {
    "use strict";
    init_dist_es8();
    import_buffer2 = require("buffer");
    fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => {
      if (!isArrayBuffer(input)) {
        throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
      }
      return import_buffer2.Buffer.from(input, offset, length);
    };
    fromString = (input, encoding) => {
      if (typeof input !== "string") {
        throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
      }
      return encoding ? import_buffer2.Buffer.from(input, encoding) : import_buffer2.Buffer.from(input);
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-es/fromBase64.js
var BASE64_REGEX, fromBase64;
var init_fromBase64 = __esm({
  "../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-es/fromBase64.js"() {
    "use strict";
    init_dist_es9();
    BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/;
    fromBase64 = (input) => {
      if (input.length * 3 % 4 !== 0) {
        throw new TypeError(`Incorrect padding on base64 string.`);
      }
      if (!BASE64_REGEX.exec(input)) {
        throw new TypeError(`Invalid base64 string.`);
      }
      const buffer = fromString(input, "base64");
      return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/fromUtf8.js
var fromUtf8;
var init_fromUtf8 = __esm({
  "../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/fromUtf8.js"() {
    "use strict";
    init_dist_es9();
    fromUtf8 = (input) => {
      const buf = fromString(input, "utf8");
      return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js
var toUint8Array;
var init_toUint8Array = __esm({
  "../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js"() {
    "use strict";
    init_fromUtf8();
    toUint8Array = (data) => {
      if (typeof data === "string") {
        return fromUtf8(data);
      }
      if (ArrayBuffer.isView(data)) {
        return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
      }
      return new Uint8Array(data);
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/toUtf8.js
var toUtf8;
var init_toUtf8 = __esm({
  "../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/toUtf8.js"() {
    "use strict";
    init_dist_es9();
    toUtf8 = (input) => {
      if (typeof input === "string") {
        return input;
      }
      if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
        throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");
      }
      return fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("utf8");
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/index.js
var init_dist_es10 = __esm({
  "../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/index.js"() {
    "use strict";
    init_fromUtf8();
    init_toUint8Array();
    init_toUtf8();
  }
});

// ../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-es/toBase64.js
var toBase64;
var init_toBase64 = __esm({
  "../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-es/toBase64.js"() {
    "use strict";
    init_dist_es9();
    init_dist_es10();
    toBase64 = (_input) => {
      let input;
      if (typeof _input === "string") {
        input = fromUtf8(_input);
      } else {
        input = _input;
      }
      if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
        throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
      }
      return fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("base64");
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-es/index.js
var init_dist_es11 = __esm({
  "../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-es/index.js"() {
    "use strict";
    init_fromBase64();
    init_toBase64();
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/blob/transforms.js
function transformToString(payload, encoding = "utf-8") {
  if (encoding === "base64") {
    return toBase64(payload);
  }
  return toUtf8(payload);
}
function transformFromString(str, encoding) {
  if (encoding === "base64") {
    return Uint8ArrayBlobAdapter.mutate(fromBase64(str));
  }
  return Uint8ArrayBlobAdapter.mutate(fromUtf8(str));
}
var init_transforms = __esm({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/blob/transforms.js"() {
    "use strict";
    init_dist_es11();
    init_dist_es10();
    init_Uint8ArrayBlobAdapter();
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/blob/Uint8ArrayBlobAdapter.js
var Uint8ArrayBlobAdapter;
var init_Uint8ArrayBlobAdapter = __esm({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/blob/Uint8ArrayBlobAdapter.js"() {
    "use strict";
    init_transforms();
    Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array {
      static fromString(source, encoding = "utf-8") {
        switch (typeof source) {
          case "string":
            return transformFromString(source, encoding);
          default:
            throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`);
        }
      }
      static mutate(source) {
        Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype);
        return source;
      }
      transformToString(encoding = "utf-8") {
        return transformToString(this, encoding);
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.js
var init_ChecksumStream = __esm({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.js"() {
    "use strict";
    init_dist_es11();
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/stream-type-check.js
var isReadableStream;
var init_stream_type_check = __esm({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/stream-type-check.js"() {
    "use strict";
    isReadableStream = (stream) => typeof ReadableStream === "function" && (stream?.constructor?.name === ReadableStream.name || stream instanceof ReadableStream);
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.browser.js
var init_ChecksumStream_browser = __esm({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.browser.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.browser.js
var init_createChecksumStream_browser = __esm({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.browser.js"() {
    "use strict";
    init_dist_es11();
    init_stream_type_check();
    init_ChecksumStream_browser();
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.js
var init_createChecksumStream = __esm({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.js"() {
    "use strict";
    init_stream_type_check();
    init_ChecksumStream();
    init_createChecksumStream_browser();
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/ByteArrayCollector.js
var init_ByteArrayCollector = __esm({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/ByteArrayCollector.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/createBufferedReadableStream.js
var init_createBufferedReadableStream = __esm({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/createBufferedReadableStream.js"() {
    "use strict";
    init_ByteArrayCollector();
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/createBufferedReadable.js
var import_node_stream3;
var init_createBufferedReadable = __esm({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/createBufferedReadable.js"() {
    "use strict";
    import_node_stream3 = require("stream");
    init_ByteArrayCollector();
    init_createBufferedReadableStream();
    init_stream_type_check();
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/getAwsChunkedEncodingStream.js
var init_getAwsChunkedEncodingStream = __esm({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/getAwsChunkedEncodingStream.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/headStream.browser.js
var init_headStream_browser = __esm({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/headStream.browser.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/headStream.js
var init_headStream = __esm({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/headStream.js"() {
    "use strict";
    init_headStream_browser();
    init_stream_type_check();
  }
});

// ../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js
var escapeUri, hexEncode;
var init_escape_uri = __esm({
  "../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js"() {
    "use strict";
    escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode);
    hexEncode = (c5) => `%${c5.charCodeAt(0).toString(16).toUpperCase()}`;
  }
});

// ../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-es/escape-uri-path.js
var init_escape_uri_path = __esm({
  "../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-es/escape-uri-path.js"() {
    "use strict";
    init_escape_uri();
  }
});

// ../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-es/index.js
var init_dist_es12 = __esm({
  "../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-es/index.js"() {
    "use strict";
    init_escape_uri();
    init_escape_uri_path();
  }
});

// ../node_modules/.pnpm/@smithy+querystring-builder@4.0.4/node_modules/@smithy/querystring-builder/dist-es/index.js
function buildQueryString(query) {
  const parts = [];
  for (let key of Object.keys(query).sort()) {
    const value = query[key];
    key = escapeUri(key);
    if (Array.isArray(value)) {
      for (let i6 = 0, iLen = value.length; i6 < iLen; i6++) {
        parts.push(`${key}=${escapeUri(value[i6])}`);
      }
    } else {
      let qsEntry = key;
      if (value || typeof value === "string") {
        qsEntry += `=${escapeUri(value)}`;
      }
      parts.push(qsEntry);
    }
  }
  return parts.join("&");
}
var init_dist_es13 = __esm({
  "../node_modules/.pnpm/@smithy+querystring-builder@4.0.4/node_modules/@smithy/querystring-builder/dist-es/index.js"() {
    "use strict";
    init_dist_es12();
  }
});

// ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/constants.js
var NODEJS_TIMEOUT_ERROR_CODES;
var init_constants2 = __esm({
  "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/constants.js"() {
    "use strict";
    NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"];
  }
});

// ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/get-transformed-headers.js
var getTransformedHeaders;
var init_get_transformed_headers = __esm({
  "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/get-transformed-headers.js"() {
    "use strict";
    getTransformedHeaders = (headers) => {
      const transformedHeaders = {};
      for (const name of Object.keys(headers)) {
        const headerValues = headers[name];
        transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues;
      }
      return transformedHeaders;
    };
  }
});

// ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/timing.js
var timing;
var init_timing = __esm({
  "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/timing.js"() {
    "use strict";
    timing = {
      setTimeout: (cb, ms) => setTimeout(cb, ms),
      clearTimeout: (timeoutId) => clearTimeout(timeoutId)
    };
  }
});

// ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/set-connection-timeout.js
var DEFER_EVENT_LISTENER_TIME, setConnectionTimeout;
var init_set_connection_timeout = __esm({
  "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/set-connection-timeout.js"() {
    "use strict";
    init_timing();
    DEFER_EVENT_LISTENER_TIME = 1e3;
    setConnectionTimeout = (request2, reject, timeoutInMs = 0) => {
      if (!timeoutInMs) {
        return -1;
      }
      const registerTimeout = (offset) => {
        const timeoutId = timing.setTimeout(() => {
          request2.destroy();
          reject(Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), {
            name: "TimeoutError"
          }));
        }, timeoutInMs - offset);
        const doWithSocket = (socket) => {
          if (socket?.connecting) {
            socket.on("connect", () => {
              timing.clearTimeout(timeoutId);
            });
          } else {
            timing.clearTimeout(timeoutId);
          }
        };
        if (request2.socket) {
          doWithSocket(request2.socket);
        } else {
          request2.on("socket", doWithSocket);
        }
      };
      if (timeoutInMs < 2e3) {
        registerTimeout(0);
        return 0;
      }
      return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME);
    };
  }
});

// ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/set-socket-keep-alive.js
var DEFER_EVENT_LISTENER_TIME2, setSocketKeepAlive;
var init_set_socket_keep_alive = __esm({
  "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/set-socket-keep-alive.js"() {
    "use strict";
    init_timing();
    DEFER_EVENT_LISTENER_TIME2 = 3e3;
    setSocketKeepAlive = (request2, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => {
      if (keepAlive !== true) {
        return -1;
      }
      const registerListener = () => {
        if (request2.socket) {
          request2.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);
        } else {
          request2.on("socket", (socket) => {
            socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);
          });
        }
      };
      if (deferTimeMs === 0) {
        registerListener();
        return 0;
      }
      return timing.setTimeout(registerListener, deferTimeMs);
    };
  }
});

// ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/set-socket-timeout.js
var DEFER_EVENT_LISTENER_TIME3, setSocketTimeout;
var init_set_socket_timeout = __esm({
  "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/set-socket-timeout.js"() {
    "use strict";
    init_node_http_handler();
    init_timing();
    DEFER_EVENT_LISTENER_TIME3 = 3e3;
    setSocketTimeout = (request2, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => {
      const registerTimeout = (offset) => {
        const timeout = timeoutInMs - offset;
        const onTimeout = () => {
          request2.destroy();
          reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" }));
        };
        if (request2.socket) {
          request2.socket.setTimeout(timeout, onTimeout);
          request2.on("close", () => request2.socket?.removeListener("timeout", onTimeout));
        } else {
          request2.setTimeout(timeout, onTimeout);
        }
      };
      if (0 < timeoutInMs && timeoutInMs < 6e3) {
        registerTimeout(0);
        return 0;
      }
      return timing.setTimeout(registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), DEFER_EVENT_LISTENER_TIME3);
    };
  }
});

// ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/write-request-body.js
async function writeRequestBody(httpRequest2, request2, maxContinueTimeoutMs = MIN_WAIT_TIME) {
  const headers = request2.headers ?? {};
  const expect = headers["Expect"] || headers["expect"];
  let timeoutId = -1;
  let sendBody = true;
  if (expect === "100-continue") {
    sendBody = await Promise.race([
      new Promise((resolve) => {
        timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs)));
      }),
      new Promise((resolve) => {
        httpRequest2.on("continue", () => {
          timing.clearTimeout(timeoutId);
          resolve(true);
        });
        httpRequest2.on("response", () => {
          timing.clearTimeout(timeoutId);
          resolve(false);
        });
        httpRequest2.on("error", () => {
          timing.clearTimeout(timeoutId);
          resolve(false);
        });
      })
    ]);
  }
  if (sendBody) {
    writeBody(httpRequest2, request2.body);
  }
}
function writeBody(httpRequest2, body) {
  if (body instanceof import_stream3.Readable) {
    body.pipe(httpRequest2);
    return;
  }
  if (body) {
    if (Buffer.isBuffer(body) || typeof body === "string") {
      httpRequest2.end(body);
      return;
    }
    const uint8 = body;
    if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") {
      httpRequest2.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength));
      return;
    }
    httpRequest2.end(Buffer.from(body));
    return;
  }
  httpRequest2.end();
}
var import_stream3, MIN_WAIT_TIME;
var init_write_request_body = __esm({
  "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/write-request-body.js"() {
    "use strict";
    import_stream3 = require("stream");
    init_timing();
    MIN_WAIT_TIME = 6e3;
  }
});

// ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http-handler.js
var import_http3, import_https, DEFAULT_REQUEST_TIMEOUT, NodeHttpHandler;
var init_node_http_handler = __esm({
  "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http-handler.js"() {
    "use strict";
    init_dist_es2();
    init_dist_es13();
    import_http3 = require("http");
    import_https = require("https");
    init_constants2();
    init_get_transformed_headers();
    init_set_connection_timeout();
    init_set_socket_keep_alive();
    init_set_socket_timeout();
    init_timing();
    init_write_request_body();
    DEFAULT_REQUEST_TIMEOUT = 0;
    NodeHttpHandler = class _NodeHttpHandler {
      static create(instanceOrOptions) {
        if (typeof instanceOrOptions?.handle === "function") {
          return instanceOrOptions;
        }
        return new _NodeHttpHandler(instanceOrOptions);
      }
      static checkSocketUsage(agent, socketWarningTimestamp, logger2 = console) {
        const { sockets, requests, maxSockets } = agent;
        if (typeof maxSockets !== "number" || maxSockets === Infinity) {
          return socketWarningTimestamp;
        }
        const interval = 15e3;
        if (Date.now() - interval < socketWarningTimestamp) {
          return socketWarningTimestamp;
        }
        if (sockets && requests) {
          for (const origin in sockets) {
            const socketsInUse = sockets[origin]?.length ?? 0;
            const requestsEnqueued = requests[origin]?.length ?? 0;
            if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) {
              logger2?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued.
See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html
or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`);
              return Date.now();
            }
          }
        }
        return socketWarningTimestamp;
      }
      constructor(options) {
        this.socketWarningTimestamp = 0;
        this.metadata = { handlerProtocol: "http/1.1" };
        this.configProvider = new Promise((resolve, reject) => {
          if (typeof options === "function") {
            options().then((_options) => {
              resolve(this.resolveDefaultConfig(_options));
            }).catch(reject);
          } else {
            resolve(this.resolveDefaultConfig(options));
          }
        });
      }
      resolveDefaultConfig(options) {
        const { requestTimeout: requestTimeout2, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {};
        const keepAlive = true;
        const maxSockets = 50;
        return {
          connectionTimeout,
          requestTimeout: requestTimeout2 ?? socketTimeout,
          socketAcquisitionWarningTimeout,
          httpAgent: (() => {
            if (httpAgent instanceof import_http3.Agent || typeof httpAgent?.destroy === "function") {
              return httpAgent;
            }
            return new import_http3.Agent({ keepAlive, maxSockets, ...httpAgent });
          })(),
          httpsAgent: (() => {
            if (httpsAgent instanceof import_https.Agent || typeof httpsAgent?.destroy === "function") {
              return httpsAgent;
            }
            return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent });
          })(),
          logger: console
        };
      }
      destroy() {
        this.config?.httpAgent?.destroy();
        this.config?.httpsAgent?.destroy();
      }
      async handle(request2, { abortSignal } = {}) {
        if (!this.config) {
          this.config = await this.configProvider;
        }
        return new Promise((_resolve, _reject) => {
          let writeRequestBodyPromise = void 0;
          const timeouts = [];
          const resolve = async (arg) => {
            await writeRequestBodyPromise;
            timeouts.forEach(timing.clearTimeout);
            _resolve(arg);
          };
          const reject = async (arg) => {
            await writeRequestBodyPromise;
            timeouts.forEach(timing.clearTimeout);
            _reject(arg);
          };
          if (!this.config) {
            throw new Error("Node HTTP request handler config is not resolved");
          }
          if (abortSignal?.aborted) {
            const abortError = new Error("Request aborted");
            abortError.name = "AbortError";
            reject(abortError);
            return;
          }
          const isSSL = request2.protocol === "https:";
          const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent;
          timeouts.push(timing.setTimeout(() => {
            this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, this.config.logger);
          }, this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3)));
          const queryString = buildQueryString(request2.query || {});
          let auth = void 0;
          if (request2.username != null || request2.password != null) {
            const username = request2.username ?? "";
            const password = request2.password ?? "";
            auth = `${username}:${password}`;
          }
          let path3 = request2.path;
          if (queryString) {
            path3 += `?${queryString}`;
          }
          if (request2.fragment) {
            path3 += `#${request2.fragment}`;
          }
          let hostname = request2.hostname ?? "";
          if (hostname[0] === "[" && hostname.endsWith("]")) {
            hostname = request2.hostname.slice(1, -1);
          } else {
            hostname = request2.hostname;
          }
          const nodeHttpsOptions = {
            headers: request2.headers,
            host: hostname,
            method: request2.method,
            path: path3,
            port: request2.port,
            agent,
            auth
          };
          const requestFunc = isSSL ? import_https.request : import_http3.request;
          const req = requestFunc(nodeHttpsOptions, (res) => {
            const httpResponse = new HttpResponse({
              statusCode: res.statusCode || -1,
              reason: res.statusMessage,
              headers: getTransformedHeaders(res.headers),
              body: res
            });
            resolve({ response: httpResponse });
          });
          req.on("error", (err2) => {
            if (NODEJS_TIMEOUT_ERROR_CODES.includes(err2.code)) {
              reject(Object.assign(err2, { name: "TimeoutError" }));
            } else {
              reject(err2);
            }
          });
          if (abortSignal) {
            const onAbort = () => {
              req.destroy();
              const abortError = new Error("Request aborted");
              abortError.name = "AbortError";
              reject(abortError);
            };
            if (typeof abortSignal.addEventListener === "function") {
              const signal = abortSignal;
              signal.addEventListener("abort", onAbort, { once: true });
              req.once("close", () => signal.removeEventListener("abort", onAbort));
            } else {
              abortSignal.onabort = onAbort;
            }
          }
          timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout));
          timeouts.push(setSocketTimeout(req, reject, this.config.requestTimeout));
          const httpAgent = nodeHttpsOptions.agent;
          if (typeof httpAgent === "object" && "keepAlive" in httpAgent) {
            timeouts.push(setSocketKeepAlive(req, {
              keepAlive: httpAgent.keepAlive,
              keepAliveMsecs: httpAgent.keepAliveMsecs
            }));
          }
          writeRequestBodyPromise = writeRequestBody(req, request2, this.config.requestTimeout).catch((e6) => {
            timeouts.forEach(timing.clearTimeout);
            return _reject(e6);
          });
        });
      }
      updateHttpClientConfig(key, value) {
        this.config = void 0;
        this.configProvider = this.configProvider.then((config) => {
          return {
            ...config,
            [key]: value
          };
        });
      }
      httpHandlerConfigs() {
        return this.config ?? {};
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-pool.js
var init_node_http2_connection_pool = __esm({
  "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-pool.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-manager.js
var init_node_http2_connection_manager = __esm({
  "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-manager.js"() {
    "use strict";
    init_node_http2_connection_pool();
  }
});

// ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http2-handler.js
var init_node_http2_handler = __esm({
  "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http2-handler.js"() {
    "use strict";
    init_dist_es2();
    init_dist_es13();
    init_get_transformed_headers();
    init_node_http2_connection_manager();
    init_write_request_body();
  }
});

// ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/stream-collector/collector.js
var import_stream4, Collector;
var init_collector = __esm({
  "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/stream-collector/collector.js"() {
    "use strict";
    import_stream4 = require("stream");
    Collector = class extends import_stream4.Writable {
      constructor() {
        super(...arguments);
        this.bufferedBytes = [];
      }
      _write(chunk, encoding, callback) {
        this.bufferedBytes.push(chunk);
        callback();
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/stream-collector/index.js
async function collectReadableStream(stream) {
  const chunks = [];
  const reader = stream.getReader();
  let isDone = false;
  let length = 0;
  while (!isDone) {
    const { done, value } = await reader.read();
    if (value) {
      chunks.push(value);
      length += value.length;
    }
    isDone = done;
  }
  const collected = new Uint8Array(length);
  let offset = 0;
  for (const chunk of chunks) {
    collected.set(chunk, offset);
    offset += chunk.length;
  }
  return collected;
}
var streamCollector, isReadableStreamInstance;
var init_stream_collector = __esm({
  "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/stream-collector/index.js"() {
    "use strict";
    init_collector();
    streamCollector = (stream) => {
      if (isReadableStreamInstance(stream)) {
        return collectReadableStream(stream);
      }
      return new Promise((resolve, reject) => {
        const collector = new Collector();
        stream.pipe(collector);
        stream.on("error", (err2) => {
          collector.end();
          reject(err2);
        });
        collector.on("error", reject);
        collector.on("finish", function() {
          const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes));
          resolve(bytes);
        });
      });
    };
    isReadableStreamInstance = (stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream;
  }
});

// ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/index.js
var init_dist_es14 = __esm({
  "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/index.js"() {
    "use strict";
    init_node_http_handler();
    init_node_http2_handler();
    init_stream_collector();
  }
});

// ../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/create-request.js
var init_create_request = __esm({
  "../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/create-request.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/request-timeout.js
var init_request_timeout = __esm({
  "../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/request-timeout.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/fetch-http-handler.js
var init_fetch_http_handler = __esm({
  "../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/fetch-http-handler.js"() {
    "use strict";
    init_dist_es2();
    init_dist_es13();
    init_create_request();
    init_request_timeout();
  }
});

// ../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/stream-collector.js
async function collectBlob(blob) {
  const base64 = await readToBase64(blob);
  const arrayBuffer = fromBase64(base64);
  return new Uint8Array(arrayBuffer);
}
async function collectStream(stream) {
  const chunks = [];
  const reader = stream.getReader();
  let isDone = false;
  let length = 0;
  while (!isDone) {
    const { done, value } = await reader.read();
    if (value) {
      chunks.push(value);
      length += value.length;
    }
    isDone = done;
  }
  const collected = new Uint8Array(length);
  let offset = 0;
  for (const chunk of chunks) {
    collected.set(chunk, offset);
    offset += chunk.length;
  }
  return collected;
}
function readToBase64(blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onloadend = () => {
      if (reader.readyState !== 2) {
        return reject(new Error("Reader aborted too early"));
      }
      const result = reader.result ?? "";
      const commaIndex = result.indexOf(",");
      const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length;
      resolve(result.substring(dataOffset));
    };
    reader.onabort = () => reject(new Error("Read aborted"));
    reader.onerror = () => reject(reader.error);
    reader.readAsDataURL(blob);
  });
}
var streamCollector2;
var init_stream_collector2 = __esm({
  "../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/stream-collector.js"() {
    "use strict";
    init_dist_es11();
    streamCollector2 = async (stream) => {
      if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") {
        if (Blob.prototype.arrayBuffer !== void 0) {
          return new Uint8Array(await stream.arrayBuffer());
        }
        return collectBlob(stream);
      }
      return collectStream(stream);
    };
  }
});

// ../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/index.js
var init_dist_es15 = __esm({
  "../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/index.js"() {
    "use strict";
    init_fetch_http_handler();
    init_stream_collector2();
  }
});

// ../node_modules/.pnpm/@smithy+util-hex-encoding@4.0.0/node_modules/@smithy/util-hex-encoding/dist-es/index.js
function fromHex(encoded) {
  if (encoded.length % 2 !== 0) {
    throw new Error("Hex encoded strings must have an even number length");
  }
  const out = new Uint8Array(encoded.length / 2);
  for (let i6 = 0; i6 < encoded.length; i6 += 2) {
    const encodedByte = encoded.slice(i6, i6 + 2).toLowerCase();
    if (encodedByte in HEX_TO_SHORT) {
      out[i6 / 2] = HEX_TO_SHORT[encodedByte];
    } else {
      throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);
    }
  }
  return out;
}
function toHex(bytes) {
  let out = "";
  for (let i6 = 0; i6 < bytes.byteLength; i6++) {
    out += SHORT_TO_HEX[bytes[i6]];
  }
  return out;
}
var SHORT_TO_HEX, HEX_TO_SHORT;
var init_dist_es16 = __esm({
  "../node_modules/.pnpm/@smithy+util-hex-encoding@4.0.0/node_modules/@smithy/util-hex-encoding/dist-es/index.js"() {
    "use strict";
    SHORT_TO_HEX = {};
    HEX_TO_SHORT = {};
    for (let i6 = 0; i6 < 256; i6++) {
      let encodedByte = i6.toString(16).toLowerCase();
      if (encodedByte.length === 1) {
        encodedByte = `0${encodedByte}`;
      }
      SHORT_TO_HEX[i6] = encodedByte;
      HEX_TO_SHORT[encodedByte] = i6;
    }
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.browser.js
var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED, sdkStreamMixin, isBlobInstance;
var init_sdk_stream_mixin_browser = __esm({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.browser.js"() {
    "use strict";
    init_dist_es15();
    init_dist_es11();
    init_dist_es16();
    init_dist_es10();
    init_stream_type_check();
    ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed.";
    sdkStreamMixin = (stream) => {
      if (!isBlobInstance(stream) && !isReadableStream(stream)) {
        const name = stream?.__proto__?.constructor?.name || stream;
        throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`);
      }
      let transformed = false;
      const transformToByteArray = async () => {
        if (transformed) {
          throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
        }
        transformed = true;
        return await streamCollector2(stream);
      };
      const blobToWebStream = (blob) => {
        if (typeof blob.stream !== "function") {
          throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\nIf you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body");
        }
        return blob.stream();
      };
      return Object.assign(stream, {
        transformToByteArray,
        transformToString: async (encoding) => {
          const buf = await transformToByteArray();
          if (encoding === "base64") {
            return toBase64(buf);
          } else if (encoding === "hex") {
            return toHex(buf);
          } else if (encoding === void 0 || encoding === "utf8" || encoding === "utf-8") {
            return toUtf8(buf);
          } else if (typeof TextDecoder === "function") {
            return new TextDecoder(encoding).decode(buf);
          } else {
            throw new Error("TextDecoder is not available, please make sure polyfill is provided.");
          }
        },
        transformToWebStream: () => {
          if (transformed) {
            throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
          }
          transformed = true;
          if (isBlobInstance(stream)) {
            return blobToWebStream(stream);
          } else if (isReadableStream(stream)) {
            return stream;
          } else {
            throw new Error(`Cannot transform payload to web stream, got ${stream}`);
          }
        }
      });
    };
    isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob;
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.js
var import_stream5, ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2, sdkStreamMixin2;
var init_sdk_stream_mixin = __esm({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.js"() {
    "use strict";
    init_dist_es14();
    init_dist_es9();
    import_stream5 = require("stream");
    init_sdk_stream_mixin_browser();
    ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2 = "The stream has already been transformed.";
    sdkStreamMixin2 = (stream) => {
      if (!(stream instanceof import_stream5.Readable)) {
        try {
          return sdkStreamMixin(stream);
        } catch (e6) {
          const name = stream?.__proto__?.constructor?.name || stream;
          throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`);
        }
      }
      let transformed = false;
      const transformToByteArray = async () => {
        if (transformed) {
          throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2);
        }
        transformed = true;
        return await streamCollector(stream);
      };
      return Object.assign(stream, {
        transformToByteArray,
        transformToString: async (encoding) => {
          const buf = await transformToByteArray();
          if (encoding === void 0 || Buffer.isEncoding(encoding)) {
            return fromArrayBuffer(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding);
          } else {
            const decoder = new TextDecoder(encoding);
            return decoder.decode(buf);
          }
        },
        transformToWebStream: () => {
          if (transformed) {
            throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2);
          }
          if (stream.readableFlowing !== null) {
            throw new Error("The stream has been consumed by other callbacks.");
          }
          if (typeof import_stream5.Readable.toWeb !== "function") {
            throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");
          }
          transformed = true;
          return import_stream5.Readable.toWeb(stream);
        }
      });
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/splitStream.browser.js
var init_splitStream_browser = __esm({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/splitStream.browser.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/splitStream.js
var init_splitStream = __esm({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/splitStream.js"() {
    "use strict";
    init_splitStream_browser();
    init_stream_type_check();
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/index.js
var init_dist_es17 = __esm({
  "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/index.js"() {
    "use strict";
    init_Uint8ArrayBlobAdapter();
    init_ChecksumStream();
    init_createChecksumStream();
    init_createBufferedReadable();
    init_getAwsChunkedEncodingStream();
    init_headStream();
    init_sdk_stream_mixin();
    init_splitStream();
    init_stream_type_check();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js
var collectBody;
var init_collect_stream_body = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js"() {
    "use strict";
    init_dist_es17();
    collectBody = async (streamBody = new Uint8Array(), context) => {
      if (streamBody instanceof Uint8Array) {
        return Uint8ArrayBlobAdapter.mutate(streamBody);
      }
      if (!streamBody) {
        return Uint8ArrayBlobAdapter.mutate(new Uint8Array());
      }
      const fromContext = context.streamCollector(streamBody);
      return Uint8ArrayBlobAdapter.mutate(await fromContext);
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js
function extendedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c5) {
    return "%" + c5.charCodeAt(0).toString(16).toUpperCase();
  });
}
var init_extended_encode_uri_component = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/deref.js
var init_deref = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/deref.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js
var init_schemaDeserializationMiddleware = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js"() {
    "use strict";
    init_dist_es2();
    init_dist_es6();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js
var init_schemaSerializationMiddleware = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js"() {
    "use strict";
    init_dist_es6();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js
var init_getSchemaSerdePlugin = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js"() {
    "use strict";
    init_schemaDeserializationMiddleware();
    init_schemaSerializationMiddleware();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js
var TypeRegistry;
var init_TypeRegistry = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js"() {
    "use strict";
    TypeRegistry = class _TypeRegistry {
      constructor(namespace, schemas = /* @__PURE__ */ new Map()) {
        this.namespace = namespace;
        this.schemas = schemas;
      }
      static for(namespace) {
        if (!_TypeRegistry.registries.has(namespace)) {
          _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace));
        }
        return _TypeRegistry.registries.get(namespace);
      }
      register(shapeId, schema6) {
        const qualifiedName = this.normalizeShapeId(shapeId);
        const registry = _TypeRegistry.for(this.getNamespace(shapeId));
        registry.schemas.set(qualifiedName, schema6);
      }
      getSchema(shapeId) {
        const id = this.normalizeShapeId(shapeId);
        if (!this.schemas.has(id)) {
          throw new Error(`@smithy/core/schema - schema not found for ${id}`);
        }
        return this.schemas.get(id);
      }
      getBaseException() {
        for (const [id, schema6] of this.schemas.entries()) {
          if (id.startsWith("smithyts.client.synthetic.") && id.endsWith("ServiceException")) {
            return schema6;
          }
        }
        return void 0;
      }
      find(predicate) {
        return [...this.schemas.values()].find(predicate);
      }
      destroy() {
        _TypeRegistry.registries.delete(this.namespace);
        this.schemas.clear();
      }
      normalizeShapeId(shapeId) {
        if (shapeId.includes("#")) {
          return shapeId;
        }
        return this.namespace + "#" + shapeId;
      }
      getNamespace(shapeId) {
        return this.normalizeShapeId(shapeId).split("#")[0];
      }
    };
    TypeRegistry.registries = /* @__PURE__ */ new Map();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/Schema.js
var init_Schema = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/Schema.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js
var init_ListSchema = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js"() {
    "use strict";
    init_TypeRegistry();
    init_Schema();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/MapSchema.js
var init_MapSchema = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/MapSchema.js"() {
    "use strict";
    init_TypeRegistry();
    init_Schema();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/OperationSchema.js
var init_OperationSchema = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/OperationSchema.js"() {
    "use strict";
    init_TypeRegistry();
    init_Schema();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js
var init_StructureSchema = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js"() {
    "use strict";
    init_TypeRegistry();
    init_Schema();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js
var init_ErrorSchema = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js"() {
    "use strict";
    init_TypeRegistry();
    init_StructureSchema();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js
var init_sentinels2 = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js
var init_SimpleSchema = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js"() {
    "use strict";
    init_TypeRegistry();
    init_Schema();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js
var init_NormalizedSchema = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js"() {
    "use strict";
    init_deref();
    init_ListSchema();
    init_MapSchema();
    init_sentinels2();
    init_SimpleSchema();
    init_StructureSchema();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/index.js
var init_schema2 = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/index.js"() {
    "use strict";
    init_deref();
    init_getSchemaSerdePlugin();
    init_ListSchema();
    init_MapSchema();
    init_OperationSchema();
    init_ErrorSchema();
    init_NormalizedSchema();
    init_Schema();
    init_SimpleSchema();
    init_StructureSchema();
    init_sentinels2();
    init_TypeRegistry();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js
var init_copyDocumentWithTransform = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js"() {
    "use strict";
    init_schema2();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js
var expectBoolean, expectNumber, MAX_FLOAT, expectFloat32, expectLong, expectInt32, expectShort, expectByte, expectSizedInt, castInt, expectNonNull, expectObject, expectString, expectUnion, strictParseFloat32, NUMBER_REGEX, parseNumber, limitedParseDouble, limitedParseFloat32, parseFloatString, strictParseInt32, strictParseShort, strictParseByte, stackTraceWarning, logger;
var init_parse_utils = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js"() {
    "use strict";
    expectBoolean = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (typeof value === "number") {
        if (value === 0 || value === 1) {
          logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`));
        }
        if (value === 0) {
          return false;
        }
        if (value === 1) {
          return true;
        }
      }
      if (typeof value === "string") {
        const lower2 = value.toLowerCase();
        if (lower2 === "false" || lower2 === "true") {
          logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`));
        }
        if (lower2 === "false") {
          return false;
        }
        if (lower2 === "true") {
          return true;
        }
      }
      if (typeof value === "boolean") {
        return value;
      }
      throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`);
    };
    expectNumber = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (typeof value === "string") {
        const parsed = parseFloat(value);
        if (!Number.isNaN(parsed)) {
          if (String(parsed) !== String(value)) {
            logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`));
          }
          return parsed;
        }
      }
      if (typeof value === "number") {
        return value;
      }
      throw new TypeError(`Expected number, got ${typeof value}: ${value}`);
    };
    MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23));
    expectFloat32 = (value) => {
      const expected = expectNumber(value);
      if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) {
        if (Math.abs(expected) > MAX_FLOAT) {
          throw new TypeError(`Expected 32-bit float, got ${value}`);
        }
      }
      return expected;
    };
    expectLong = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (Number.isInteger(value) && !Number.isNaN(value)) {
        return value;
      }
      throw new TypeError(`Expected integer, got ${typeof value}: ${value}`);
    };
    expectInt32 = (value) => expectSizedInt(value, 32);
    expectShort = (value) => expectSizedInt(value, 16);
    expectByte = (value) => expectSizedInt(value, 8);
    expectSizedInt = (value, size) => {
      const expected = expectLong(value);
      if (expected !== void 0 && castInt(expected, size) !== expected) {
        throw new TypeError(`Expected ${size}-bit integer, got ${value}`);
      }
      return expected;
    };
    castInt = (value, size) => {
      switch (size) {
        case 32:
          return Int32Array.of(value)[0];
        case 16:
          return Int16Array.of(value)[0];
        case 8:
          return Int8Array.of(value)[0];
      }
    };
    expectNonNull = (value, location) => {
      if (value === null || value === void 0) {
        if (location) {
          throw new TypeError(`Expected a non-null value for ${location}`);
        }
        throw new TypeError("Expected a non-null value");
      }
      return value;
    };
    expectObject = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (typeof value === "object" && !Array.isArray(value)) {
        return value;
      }
      const receivedType = Array.isArray(value) ? "array" : typeof value;
      throw new TypeError(`Expected object, got ${receivedType}: ${value}`);
    };
    expectString = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (typeof value === "string") {
        return value;
      }
      if (["boolean", "number", "bigint"].includes(typeof value)) {
        logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`));
        return String(value);
      }
      throw new TypeError(`Expected string, got ${typeof value}: ${value}`);
    };
    expectUnion = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      const asObject = expectObject(value);
      const setKeys = Object.entries(asObject).filter(([, v6]) => v6 != null).map(([k5]) => k5);
      if (setKeys.length === 0) {
        throw new TypeError(`Unions must have exactly one non-null member. None were found.`);
      }
      if (setKeys.length > 1) {
        throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`);
      }
      return asObject;
    };
    strictParseFloat32 = (value) => {
      if (typeof value == "string") {
        return expectFloat32(parseNumber(value));
      }
      return expectFloat32(value);
    };
    NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g;
    parseNumber = (value) => {
      const matches = value.match(NUMBER_REGEX);
      if (matches === null || matches[0].length !== value.length) {
        throw new TypeError(`Expected real number, got implicit NaN`);
      }
      return parseFloat(value);
    };
    limitedParseDouble = (value) => {
      if (typeof value == "string") {
        return parseFloatString(value);
      }
      return expectNumber(value);
    };
    limitedParseFloat32 = (value) => {
      if (typeof value == "string") {
        return parseFloatString(value);
      }
      return expectFloat32(value);
    };
    parseFloatString = (value) => {
      switch (value) {
        case "NaN":
          return NaN;
        case "Infinity":
          return Infinity;
        case "-Infinity":
          return -Infinity;
        default:
          throw new Error(`Unable to parse float value: ${value}`);
      }
    };
    strictParseInt32 = (value) => {
      if (typeof value === "string") {
        return expectInt32(parseNumber(value));
      }
      return expectInt32(value);
    };
    strictParseShort = (value) => {
      if (typeof value === "string") {
        return expectShort(parseNumber(value));
      }
      return expectShort(value);
    };
    strictParseByte = (value) => {
      if (typeof value === "string") {
        return expectByte(parseNumber(value));
      }
      return expectByte(value);
    };
    stackTraceWarning = (message) => {
      return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s6) => !s6.includes("stackTraceWarning")).join("\n");
    };
    logger = {
      warn: console.warn
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js
var MONTHS, RFC3339, parseRfc3339DateTime, RFC3339_WITH_OFFSET, parseRfc3339DateTimeWithOffset, IMF_FIXDATE, RFC_850_DATE, ASC_TIME, buildDate, FIFTY_YEARS_IN_MILLIS, DAYS_IN_MONTH, validateDayOfMonth, isLeapYear, parseDateValue, parseMilliseconds, parseOffsetToMilliseconds, stripLeadingZeroes;
var init_date_utils = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js"() {
    "use strict";
    init_parse_utils();
    MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/);
    parseRfc3339DateTime = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (typeof value !== "string") {
        throw new TypeError("RFC-3339 date-times must be expressed as strings");
      }
      const match2 = RFC3339.exec(value);
      if (!match2) {
        throw new TypeError("Invalid RFC-3339 date-time value");
      }
      const [_3, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match2;
      const year = strictParseShort(stripLeadingZeroes(yearStr));
      const month = parseDateValue(monthStr, "month", 1, 12);
      const day = parseDateValue(dayStr, "day", 1, 31);
      return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds });
    };
    RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/);
    parseRfc3339DateTimeWithOffset = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (typeof value !== "string") {
        throw new TypeError("RFC-3339 date-times must be expressed as strings");
      }
      const match2 = RFC3339_WITH_OFFSET.exec(value);
      if (!match2) {
        throw new TypeError("Invalid RFC-3339 date-time value");
      }
      const [_3, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match2;
      const year = strictParseShort(stripLeadingZeroes(yearStr));
      const month = parseDateValue(monthStr, "month", 1, 12);
      const day = parseDateValue(dayStr, "day", 1, 31);
      const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds });
      if (offsetStr.toUpperCase() != "Z") {
        date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr));
      }
      return date;
    };
    IMF_FIXDATE = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);
    RFC_850_DATE = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);
    ASC_TIME = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/);
    buildDate = (year, month, day, time) => {
      const adjustedMonth = month - 1;
      validateDayOfMonth(year, adjustedMonth, day);
      return new Date(Date.UTC(year, adjustedMonth, day, parseDateValue(time.hours, "hour", 0, 23), parseDateValue(time.minutes, "minute", 0, 59), parseDateValue(time.seconds, "seconds", 0, 60), parseMilliseconds(time.fractionalMilliseconds)));
    };
    FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3;
    DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    validateDayOfMonth = (year, month, day) => {
      let maxDays = DAYS_IN_MONTH[month];
      if (month === 1 && isLeapYear(year)) {
        maxDays = 29;
      }
      if (day > maxDays) {
        throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`);
      }
    };
    isLeapYear = (year) => {
      return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
    };
    parseDateValue = (value, type, lower2, upper) => {
      const dateVal = strictParseByte(stripLeadingZeroes(value));
      if (dateVal < lower2 || dateVal > upper) {
        throw new TypeError(`${type} must be between ${lower2} and ${upper}, inclusive`);
      }
      return dateVal;
    };
    parseMilliseconds = (value) => {
      if (value === null || value === void 0) {
        return 0;
      }
      return strictParseFloat32("0." + value) * 1e3;
    };
    parseOffsetToMilliseconds = (value) => {
      const directionStr = value[0];
      let direction = 1;
      if (directionStr == "+") {
        direction = 1;
      } else if (directionStr == "-") {
        direction = -1;
      } else {
        throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`);
      }
      const hour = Number(value.substring(1, 3));
      const minute = Number(value.substring(4, 6));
      return direction * (hour * 60 + minute) * 60 * 1e3;
    };
    stripLeadingZeroes = (value) => {
      let idx = 0;
      while (idx < value.length - 1 && value.charAt(idx) === "0") {
        idx++;
      }
      if (idx === 0) {
        return value;
      }
      return value.slice(idx);
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js
var LazyJsonString;
var init_lazy_json = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js"() {
    "use strict";
    LazyJsonString = function LazyJsonString2(val2) {
      const str = Object.assign(new String(val2), {
        deserializeJSON() {
          return JSON.parse(String(val2));
        },
        toString() {
          return String(val2);
        },
        toJSON() {
          return String(val2);
        }
      });
      return str;
    };
    LazyJsonString.from = (object) => {
      if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) {
        return object;
      } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) {
        return LazyJsonString(String(object));
      }
      return LazyJsonString(JSON.stringify(object));
    };
    LazyJsonString.fromObject = LazyJsonString.from;
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js
var init_quote_header = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-every.js
var init_split_every = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-every.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-header.js
var init_split_header = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-header.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js
var init_NumericValue = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/index.js
var init_serde2 = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/index.js"() {
    "use strict";
    init_copyDocumentWithTransform();
    init_date_utils();
    init_lazy_json();
    init_parse_utils();
    init_quote_header();
    init_split_every();
    init_split_header();
    init_NumericValue();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js
var init_HttpProtocol = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js"() {
    "use strict";
    init_schema2();
    init_serde2();
    init_dist_es2();
    init_dist_es17();
    init_collect_stream_body();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js
var init_HttpBindingProtocol = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js"() {
    "use strict";
    init_schema2();
    init_dist_es2();
    init_collect_stream_body();
    init_extended_encode_uri_component();
    init_HttpProtocol();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js
var init_RpcProtocol = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js"() {
    "use strict";
    init_schema2();
    init_dist_es2();
    init_collect_stream_body();
    init_HttpProtocol();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js
var resolvedPath;
var init_resolve_path = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js"() {
    "use strict";
    init_extended_encode_uri_component();
    resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => {
      if (input != null && input[memberName] !== void 0) {
        const labelValue = labelValueProvider();
        if (labelValue.length <= 0) {
          throw new Error("Empty value provided for input HTTP label: " + memberName + ".");
        }
        resolvedPath2 = resolvedPath2.replace(uriLabel, isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue));
      } else {
        throw new Error("No value provided for input HTTP label: " + memberName + ".");
      }
      return resolvedPath2;
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js
function requestBuilder(input, context) {
  return new RequestBuilder(input, context);
}
var RequestBuilder;
var init_requestBuilder = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js"() {
    "use strict";
    init_dist_es2();
    init_resolve_path();
    RequestBuilder = class {
      constructor(input, context) {
        this.input = input;
        this.context = context;
        this.query = {};
        this.method = "";
        this.headers = {};
        this.path = "";
        this.body = null;
        this.hostname = "";
        this.resolvePathStack = [];
      }
      async build() {
        const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint();
        this.path = basePath;
        for (const resolvePath of this.resolvePathStack) {
          resolvePath(this.path);
        }
        return new HttpRequest({
          protocol,
          hostname: this.hostname || hostname,
          port,
          method: this.method,
          path: this.path,
          query: this.query,
          body: this.body,
          headers: this.headers
        });
      }
      hn(hostname) {
        this.hostname = hostname;
        return this;
      }
      bp(uriLabel) {
        this.resolvePathStack.push((basePath) => {
          this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel;
        });
        return this;
      }
      p(memberName, labelValueProvider, uriLabel, isGreedyLabel) {
        this.resolvePathStack.push((path3) => {
          this.path = resolvedPath(path3, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel);
        });
        return this;
      }
      h(headers) {
        this.headers = headers;
        return this;
      }
      q(query) {
        this.query = query;
        return this;
      }
      b(body) {
        this.body = body;
        return this;
      }
      m(method) {
        this.method = method;
        return this;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js
var init_determineTimestampFormat = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js"() {
    "use strict";
    init_schema2();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js
var init_FromStringShapeDeserializer = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js"() {
    "use strict";
    init_schema2();
    init_serde2();
    init_dist_es11();
    init_dist_es10();
    init_determineTimestampFormat();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js
var init_HttpInterceptingShapeDeserializer = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js"() {
    "use strict";
    init_schema2();
    init_dist_es10();
    init_FromStringShapeDeserializer();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js
var init_ToStringShapeSerializer = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js"() {
    "use strict";
    init_schema2();
    init_serde2();
    init_dist_es11();
    init_determineTimestampFormat();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js
var init_HttpInterceptingShapeSerializer = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js"() {
    "use strict";
    init_schema2();
    init_ToStringShapeSerializer();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/index.js
var init_protocols = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/index.js"() {
    "use strict";
    init_collect_stream_body();
    init_extended_encode_uri_component();
    init_HttpBindingProtocol();
    init_RpcProtocol();
    init_requestBuilder();
    init_resolve_path();
    init_FromStringShapeDeserializer();
    init_HttpInterceptingShapeDeserializer();
    init_HttpInterceptingShapeSerializer();
    init_ToStringShapeSerializer();
    init_determineTimestampFormat();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/protocols/requestBuilder.js
var init_requestBuilder2 = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/protocols/requestBuilder.js"() {
    "use strict";
    init_protocols();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/setFeature.js
function setFeature(context, feature, value) {
  if (!context.__smithy_context) {
    context.__smithy_context = {
      features: {}
    };
  } else if (!context.__smithy_context.features) {
    context.__smithy_context.features = {};
  }
  context.__smithy_context.features[feature] = value;
}
var init_setFeature = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/setFeature.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js
var DefaultIdentityProviderConfig;
var init_DefaultIdentityProviderConfig = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js"() {
    "use strict";
    DefaultIdentityProviderConfig = class {
      constructor(config) {
        this.authSchemes = /* @__PURE__ */ new Map();
        for (const [key, value] of Object.entries(config)) {
          if (value !== void 0) {
            this.authSchemes.set(key, value);
          }
        }
      }
      getIdentityProvider(schemeId) {
        return this.authSchemes.get(schemeId);
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js
var init_httpApiKeyAuth = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js"() {
    "use strict";
    init_dist_es2();
    init_dist_es();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js
var init_httpBearerAuth = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js"() {
    "use strict";
    init_dist_es2();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js
var NoAuthSigner;
var init_noAuth = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js"() {
    "use strict";
    NoAuthSigner = class {
      async sign(httpRequest2, identity, signingProperties) {
        return httpRequest2;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js
var init_httpAuthSchemes = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js"() {
    "use strict";
    init_httpApiKeyAuth();
    init_httpBearerAuth();
    init_noAuth();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js
var createIsIdentityExpiredFunction, EXPIRATION_MS, isIdentityExpired, doesIdentityRequireRefresh, memoizeIdentityProvider;
var init_memoizeIdentityProvider = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js"() {
    "use strict";
    createIsIdentityExpiredFunction = (expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs;
    EXPIRATION_MS = 3e5;
    isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS);
    doesIdentityRequireRefresh = (identity) => identity.expiration !== void 0;
    memoizeIdentityProvider = (provider, isExpired, requiresRefresh) => {
      if (provider === void 0) {
        return void 0;
      }
      const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider;
      let resolved;
      let pending;
      let hasResult;
      let isConstant = false;
      const coalesceProvider = async (options) => {
        if (!pending) {
          pending = normalizedProvider(options);
        }
        try {
          resolved = await pending;
          hasResult = true;
          isConstant = false;
        } finally {
          pending = void 0;
        }
        return resolved;
      };
      if (isExpired === void 0) {
        return async (options) => {
          if (!hasResult || options?.forceRefresh) {
            resolved = await coalesceProvider(options);
          }
          return resolved;
        };
      }
      return async (options) => {
        if (!hasResult || options?.forceRefresh) {
          resolved = await coalesceProvider(options);
        }
        if (isConstant) {
          return resolved;
        }
        if (!requiresRefresh(resolved)) {
          isConstant = true;
          return resolved;
        }
        if (isExpired(resolved)) {
          await coalesceProvider(options);
          return resolved;
        }
        return resolved;
      };
    };
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js
var init_util_identity_and_auth = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js"() {
    "use strict";
    init_DefaultIdentityProviderConfig();
    init_httpAuthSchemes();
    init_memoizeIdentityProvider();
  }
});

// ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/index.js
var init_dist_es18 = __esm({
  "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/index.js"() {
    "use strict";
    init_getSmithyContext();
    init_middleware_http_auth_scheme();
    init_middleware_http_signing();
    init_normalizeProvider2();
    init_createPaginator();
    init_requestBuilder2();
    init_setFeature();
    init_util_identity_and_auth();
  }
});

// ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/configurations.js
function isValidUserAgentAppId(appId) {
  if (appId === void 0) {
    return true;
  }
  return typeof appId === "string" && appId.length <= 50;
}
function resolveUserAgentConfig(input) {
  const normalizedAppIdProvider = normalizeProvider2(input.userAgentAppId ?? DEFAULT_UA_APP_ID);
  const { customUserAgent } = input;
  return Object.assign(input, {
    customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent,
    userAgentAppId: async () => {
      const appId = await normalizedAppIdProvider();
      if (!isValidUserAgentAppId(appId)) {
        const logger2 = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger;
        if (typeof appId !== "string") {
          logger2?.warn("userAgentAppId must be a string or undefined.");
        } else if (appId.length > 50) {
          logger2?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.");
        }
      }
      return appId;
    }
  });
}
var DEFAULT_UA_APP_ID;
var init_configurations = __esm({
  "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/configurations.js"() {
    "use strict";
    init_dist_es18();
    DEFAULT_UA_APP_ID = void 0;
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/cache/EndpointCache.js
var EndpointCache;
var init_EndpointCache = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/cache/EndpointCache.js"() {
    "use strict";
    EndpointCache = class {
      constructor({ size, params }) {
        this.data = /* @__PURE__ */ new Map();
        this.parameters = [];
        this.capacity = size ?? 50;
        if (params) {
          this.parameters = params;
        }
      }
      get(endpointParams, resolver) {
        const key = this.hash(endpointParams);
        if (key === false) {
          return resolver();
        }
        if (!this.data.has(key)) {
          if (this.data.size > this.capacity + 10) {
            const keys = this.data.keys();
            let i6 = 0;
            while (true) {
              const { value, done } = keys.next();
              this.data.delete(value);
              if (done || ++i6 > 10) {
                break;
              }
            }
          }
          this.data.set(key, resolver());
        }
        return this.data.get(key);
      }
      size() {
        return this.data.size;
      }
      hash(endpointParams) {
        let buffer = "";
        const { parameters } = this;
        if (parameters.length === 0) {
          return false;
        }
        for (const param of parameters) {
          const val2 = String(endpointParams[param] ?? "");
          if (val2.includes("|;")) {
            return false;
          }
          buffer += val2 + "|;";
        }
        return buffer;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/isIpAddress.js
var IP_V4_REGEX, isIpAddress;
var init_isIpAddress = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/isIpAddress.js"() {
    "use strict";
    IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`);
    isIpAddress = (value) => IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]");
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/isValidHostLabel.js
var VALID_HOST_LABEL_REGEX, isValidHostLabel;
var init_isValidHostLabel = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/isValidHostLabel.js"() {
    "use strict";
    VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`);
    isValidHostLabel = (value, allowSubDomains = false) => {
      if (!allowSubDomains) {
        return VALID_HOST_LABEL_REGEX.test(value);
      }
      const labels = value.split(".");
      for (const label of labels) {
        if (!isValidHostLabel(label)) {
          return false;
        }
      }
      return true;
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/customEndpointFunctions.js
var customEndpointFunctions;
var init_customEndpointFunctions = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/customEndpointFunctions.js"() {
    "use strict";
    customEndpointFunctions = {};
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/debug/debugId.js
var debugId;
var init_debugId = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/debug/debugId.js"() {
    "use strict";
    debugId = "endpoints";
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/debug/toDebugString.js
function toDebugString(input) {
  if (typeof input !== "object" || input == null) {
    return input;
  }
  if ("ref" in input) {
    return `$${toDebugString(input.ref)}`;
  }
  if ("fn" in input) {
    return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`;
  }
  return JSON.stringify(input, null, 2);
}
var init_toDebugString = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/debug/toDebugString.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/debug/index.js
var init_debug = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/debug/index.js"() {
    "use strict";
    init_debugId();
    init_toDebugString();
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/EndpointError.js
var EndpointError;
var init_EndpointError = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/EndpointError.js"() {
    "use strict";
    EndpointError = class extends Error {
      constructor(message) {
        super(message);
        this.name = "EndpointError";
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/EndpointFunctions.js
var init_EndpointFunctions = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/EndpointFunctions.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/EndpointRuleObject.js
var init_EndpointRuleObject2 = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/EndpointRuleObject.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/ErrorRuleObject.js
var init_ErrorRuleObject2 = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/ErrorRuleObject.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/RuleSetObject.js
var init_RuleSetObject2 = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/RuleSetObject.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/TreeRuleObject.js
var init_TreeRuleObject2 = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/TreeRuleObject.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/shared.js
var init_shared2 = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/shared.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/index.js
var init_types3 = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/index.js"() {
    "use strict";
    init_EndpointError();
    init_EndpointFunctions();
    init_EndpointRuleObject2();
    init_ErrorRuleObject2();
    init_RuleSetObject2();
    init_TreeRuleObject2();
    init_shared2();
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/booleanEquals.js
var booleanEquals;
var init_booleanEquals = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/booleanEquals.js"() {
    "use strict";
    booleanEquals = (value1, value2) => value1 === value2;
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/getAttrPathList.js
var getAttrPathList;
var init_getAttrPathList = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/getAttrPathList.js"() {
    "use strict";
    init_types3();
    getAttrPathList = (path3) => {
      const parts = path3.split(".");
      const pathList = [];
      for (const part of parts) {
        const squareBracketIndex = part.indexOf("[");
        if (squareBracketIndex !== -1) {
          if (part.indexOf("]") !== part.length - 1) {
            throw new EndpointError(`Path: '${path3}' does not end with ']'`);
          }
          const arrayIndex = part.slice(squareBracketIndex + 1, -1);
          if (Number.isNaN(parseInt(arrayIndex))) {
            throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path3}'`);
          }
          if (squareBracketIndex !== 0) {
            pathList.push(part.slice(0, squareBracketIndex));
          }
          pathList.push(arrayIndex);
        } else {
          pathList.push(part);
        }
      }
      return pathList;
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/getAttr.js
var getAttr;
var init_getAttr = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/getAttr.js"() {
    "use strict";
    init_types3();
    init_getAttrPathList();
    getAttr = (value, path3) => getAttrPathList(path3).reduce((acc, index6) => {
      if (typeof acc !== "object") {
        throw new EndpointError(`Index '${index6}' in '${path3}' not found in '${JSON.stringify(value)}'`);
      } else if (Array.isArray(acc)) {
        return acc[parseInt(index6)];
      }
      return acc[index6];
    }, value);
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/isSet.js
var isSet;
var init_isSet = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/isSet.js"() {
    "use strict";
    isSet = (value) => value != null;
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/not.js
var not;
var init_not = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/not.js"() {
    "use strict";
    not = (value) => !value;
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/parseURL.js
var DEFAULT_PORTS, parseURL;
var init_parseURL = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/parseURL.js"() {
    "use strict";
    init_dist_es();
    init_isIpAddress();
    DEFAULT_PORTS = {
      [EndpointURLScheme.HTTP]: 80,
      [EndpointURLScheme.HTTPS]: 443
    };
    parseURL = (value) => {
      const whatwgURL = (() => {
        try {
          if (value instanceof URL) {
            return value;
          }
          if (typeof value === "object" && "hostname" in value) {
            const { hostname: hostname2, port, protocol: protocol2 = "", path: path3 = "", query = {} } = value;
            const url = new URL(`${protocol2}//${hostname2}${port ? `:${port}` : ""}${path3}`);
            url.search = Object.entries(query).map(([k5, v6]) => `${k5}=${v6}`).join("&");
            return url;
          }
          return new URL(value);
        } catch (error2) {
          return null;
        }
      })();
      if (!whatwgURL) {
        console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`);
        return null;
      }
      const urlString = whatwgURL.href;
      const { host, hostname, pathname, protocol, search } = whatwgURL;
      if (search) {
        return null;
      }
      const scheme = protocol.slice(0, -1);
      if (!Object.values(EndpointURLScheme).includes(scheme)) {
        return null;
      }
      const isIp = isIpAddress(hostname);
      const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`);
      const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`;
      return {
        scheme,
        authority,
        path: pathname,
        normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`,
        isIp
      };
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/stringEquals.js
var stringEquals;
var init_stringEquals = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/stringEquals.js"() {
    "use strict";
    stringEquals = (value1, value2) => value1 === value2;
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/substring.js
var substring;
var init_substring = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/substring.js"() {
    "use strict";
    substring = (input, start, stop, reverse) => {
      if (start >= stop || input.length < stop) {
        return null;
      }
      if (!reverse) {
        return input.substring(start, stop);
      }
      return input.substring(input.length - stop, input.length - start);
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/uriEncode.js
var uriEncode;
var init_uriEncode = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/uriEncode.js"() {
    "use strict";
    uriEncode = (value) => encodeURIComponent(value).replace(/[!*'()]/g, (c5) => `%${c5.charCodeAt(0).toString(16).toUpperCase()}`);
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/index.js
var init_lib = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/index.js"() {
    "use strict";
    init_booleanEquals();
    init_getAttr();
    init_isSet();
    init_isValidHostLabel();
    init_not();
    init_parseURL();
    init_stringEquals();
    init_substring();
    init_uriEncode();
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/endpointFunctions.js
var endpointFunctions;
var init_endpointFunctions = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/endpointFunctions.js"() {
    "use strict";
    init_lib();
    endpointFunctions = {
      booleanEquals,
      getAttr,
      isSet,
      isValidHostLabel,
      not,
      parseURL,
      stringEquals,
      substring,
      uriEncode
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTemplate.js
var evaluateTemplate;
var init_evaluateTemplate = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTemplate.js"() {
    "use strict";
    init_lib();
    evaluateTemplate = (template, options) => {
      const evaluatedTemplateArr = [];
      const templateContext = {
        ...options.endpointParams,
        ...options.referenceRecord
      };
      let currentIndex = 0;
      while (currentIndex < template.length) {
        const openingBraceIndex = template.indexOf("{", currentIndex);
        if (openingBraceIndex === -1) {
          evaluatedTemplateArr.push(template.slice(currentIndex));
          break;
        }
        evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex));
        const closingBraceIndex = template.indexOf("}", openingBraceIndex);
        if (closingBraceIndex === -1) {
          evaluatedTemplateArr.push(template.slice(openingBraceIndex));
          break;
        }
        if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") {
          evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex));
          currentIndex = closingBraceIndex + 2;
        }
        const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex);
        if (parameterName.includes("#")) {
          const [refName, attrName] = parameterName.split("#");
          evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName));
        } else {
          evaluatedTemplateArr.push(templateContext[parameterName]);
        }
        currentIndex = closingBraceIndex + 1;
      }
      return evaluatedTemplateArr.join("");
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getReferenceValue.js
var getReferenceValue;
var init_getReferenceValue = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getReferenceValue.js"() {
    "use strict";
    getReferenceValue = ({ ref }, options) => {
      const referenceRecord = {
        ...options.endpointParams,
        ...options.referenceRecord
      };
      return referenceRecord[ref];
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateExpression.js
var evaluateExpression;
var init_evaluateExpression = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateExpression.js"() {
    "use strict";
    init_types3();
    init_callFunction();
    init_evaluateTemplate();
    init_getReferenceValue();
    evaluateExpression = (obj, keyName, options) => {
      if (typeof obj === "string") {
        return evaluateTemplate(obj, options);
      } else if (obj["fn"]) {
        return callFunction(obj, options);
      } else if (obj["ref"]) {
        return getReferenceValue(obj, options);
      }
      throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`);
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/callFunction.js
var callFunction;
var init_callFunction = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/callFunction.js"() {
    "use strict";
    init_customEndpointFunctions();
    init_endpointFunctions();
    init_evaluateExpression();
    callFunction = ({ fn, argv }, options) => {
      const evaluatedArgs = argv.map((arg) => ["boolean", "number"].includes(typeof arg) ? arg : evaluateExpression(arg, "arg", options));
      const fnSegments = fn.split(".");
      if (fnSegments[0] in customEndpointFunctions && fnSegments[1] != null) {
        return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs);
      }
      return endpointFunctions[fn](...evaluatedArgs);
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateCondition.js
var evaluateCondition;
var init_evaluateCondition = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateCondition.js"() {
    "use strict";
    init_debug();
    init_types3();
    init_callFunction();
    evaluateCondition = ({ assign, ...fnArgs }, options) => {
      if (assign && assign in options.referenceRecord) {
        throw new EndpointError(`'${assign}' is already defined in Reference Record.`);
      }
      const value = callFunction(fnArgs, options);
      options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`);
      return {
        result: value === "" ? true : !!value,
        ...assign != null && { toAssign: { name: assign, value } }
      };
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateConditions.js
var evaluateConditions;
var init_evaluateConditions = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateConditions.js"() {
    "use strict";
    init_debug();
    init_evaluateCondition();
    evaluateConditions = (conditions = [], options) => {
      const conditionsReferenceRecord = {};
      for (const condition of conditions) {
        const { result, toAssign } = evaluateCondition(condition, {
          ...options,
          referenceRecord: {
            ...options.referenceRecord,
            ...conditionsReferenceRecord
          }
        });
        if (!result) {
          return { result };
        }
        if (toAssign) {
          conditionsReferenceRecord[toAssign.name] = toAssign.value;
          options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`);
        }
      }
      return { result: true, referenceRecord: conditionsReferenceRecord };
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointHeaders.js
var getEndpointHeaders;
var init_getEndpointHeaders = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointHeaders.js"() {
    "use strict";
    init_types3();
    init_evaluateExpression();
    getEndpointHeaders = (headers, options) => Object.entries(headers).reduce((acc, [headerKey, headerVal]) => ({
      ...acc,
      [headerKey]: headerVal.map((headerValEntry) => {
        const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options);
        if (typeof processedExpr !== "string") {
          throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`);
        }
        return processedExpr;
      })
    }), {});
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperty.js
var getEndpointProperty;
var init_getEndpointProperty = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperty.js"() {
    "use strict";
    init_types3();
    init_evaluateTemplate();
    init_getEndpointProperties();
    getEndpointProperty = (property, options) => {
      if (Array.isArray(property)) {
        return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options));
      }
      switch (typeof property) {
        case "string":
          return evaluateTemplate(property, options);
        case "object":
          if (property === null) {
            throw new EndpointError(`Unexpected endpoint property: ${property}`);
          }
          return getEndpointProperties(property, options);
        case "boolean":
          return property;
        default:
          throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`);
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperties.js
var getEndpointProperties;
var init_getEndpointProperties = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperties.js"() {
    "use strict";
    init_getEndpointProperty();
    getEndpointProperties = (properties, options) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => ({
      ...acc,
      [propertyKey]: getEndpointProperty(propertyVal, options)
    }), {});
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointUrl.js
var getEndpointUrl;
var init_getEndpointUrl = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointUrl.js"() {
    "use strict";
    init_types3();
    init_evaluateExpression();
    getEndpointUrl = (endpointUrl, options) => {
      const expression = evaluateExpression(endpointUrl, "Endpoint URL", options);
      if (typeof expression === "string") {
        try {
          return new URL(expression);
        } catch (error2) {
          console.error(`Failed to construct URL with ${expression}`, error2);
          throw error2;
        }
      }
      throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`);
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateEndpointRule.js
var evaluateEndpointRule;
var init_evaluateEndpointRule = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateEndpointRule.js"() {
    "use strict";
    init_debug();
    init_evaluateConditions();
    init_getEndpointHeaders();
    init_getEndpointProperties();
    init_getEndpointUrl();
    evaluateEndpointRule = (endpointRule, options) => {
      const { conditions, endpoint } = endpointRule;
      const { result, referenceRecord } = evaluateConditions(conditions, options);
      if (!result) {
        return;
      }
      const endpointRuleOptions = {
        ...options,
        referenceRecord: { ...options.referenceRecord, ...referenceRecord }
      };
      const { url, properties, headers } = endpoint;
      options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`);
      return {
        ...headers != void 0 && {
          headers: getEndpointHeaders(headers, endpointRuleOptions)
        },
        ...properties != void 0 && {
          properties: getEndpointProperties(properties, endpointRuleOptions)
        },
        url: getEndpointUrl(url, endpointRuleOptions)
      };
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateErrorRule.js
var evaluateErrorRule;
var init_evaluateErrorRule = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateErrorRule.js"() {
    "use strict";
    init_types3();
    init_evaluateConditions();
    init_evaluateExpression();
    evaluateErrorRule = (errorRule, options) => {
      const { conditions, error: error2 } = errorRule;
      const { result, referenceRecord } = evaluateConditions(conditions, options);
      if (!result) {
        return;
      }
      throw new EndpointError(evaluateExpression(error2, "Error", {
        ...options,
        referenceRecord: { ...options.referenceRecord, ...referenceRecord }
      }));
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTreeRule.js
var evaluateTreeRule;
var init_evaluateTreeRule = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTreeRule.js"() {
    "use strict";
    init_evaluateConditions();
    init_evaluateRules();
    evaluateTreeRule = (treeRule, options) => {
      const { conditions, rules } = treeRule;
      const { result, referenceRecord } = evaluateConditions(conditions, options);
      if (!result) {
        return;
      }
      return evaluateRules(rules, {
        ...options,
        referenceRecord: { ...options.referenceRecord, ...referenceRecord }
      });
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateRules.js
var evaluateRules;
var init_evaluateRules = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateRules.js"() {
    "use strict";
    init_types3();
    init_evaluateEndpointRule();
    init_evaluateErrorRule();
    init_evaluateTreeRule();
    evaluateRules = (rules, options) => {
      for (const rule of rules) {
        if (rule.type === "endpoint") {
          const endpointOrUndefined = evaluateEndpointRule(rule, options);
          if (endpointOrUndefined) {
            return endpointOrUndefined;
          }
        } else if (rule.type === "error") {
          evaluateErrorRule(rule, options);
        } else if (rule.type === "tree") {
          const endpointOrUndefined = evaluateTreeRule(rule, options);
          if (endpointOrUndefined) {
            return endpointOrUndefined;
          }
        } else {
          throw new EndpointError(`Unknown endpoint rule: ${rule}`);
        }
      }
      throw new EndpointError(`Rules evaluation failed`);
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/index.js
var init_utils5 = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/index.js"() {
    "use strict";
    init_customEndpointFunctions();
    init_evaluateRules();
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/resolveEndpoint.js
var resolveEndpoint;
var init_resolveEndpoint = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/resolveEndpoint.js"() {
    "use strict";
    init_debug();
    init_types3();
    init_utils5();
    resolveEndpoint = (ruleSetObject, options) => {
      const { endpointParams, logger: logger2 } = options;
      const { parameters, rules } = ruleSetObject;
      options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`);
      const paramsWithDefault = Object.entries(parameters).filter(([, v6]) => v6.default != null).map(([k5, v6]) => [k5, v6.default]);
      if (paramsWithDefault.length > 0) {
        for (const [paramKey, paramDefaultValue] of paramsWithDefault) {
          endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue;
        }
      }
      const requiredParams = Object.entries(parameters).filter(([, v6]) => v6.required).map(([k5]) => k5);
      for (const requiredParam of requiredParams) {
        if (endpointParams[requiredParam] == null) {
          throw new EndpointError(`Missing required parameter: '${requiredParam}'`);
        }
      }
      const endpoint = evaluateRules(rules, { endpointParams, logger: logger2, referenceRecord: {} });
      options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`);
      return endpoint;
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/index.js
var init_dist_es19 = __esm({
  "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/index.js"() {
    "use strict";
    init_EndpointCache();
    init_isIpAddress();
    init_isValidHostLabel();
    init_customEndpointFunctions();
    init_resolveEndpoint();
    init_types3();
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js
var init_isIpAddress2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js"() {
    "use strict";
    init_dist_es19();
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js
var isVirtualHostableS3Bucket;
var init_isVirtualHostableS3Bucket = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js"() {
    "use strict";
    init_dist_es19();
    init_isIpAddress2();
    isVirtualHostableS3Bucket = (value, allowSubDomains = false) => {
      if (allowSubDomains) {
        for (const label of value.split(".")) {
          if (!isVirtualHostableS3Bucket(label)) {
            return false;
          }
        }
        return true;
      }
      if (!isValidHostLabel(value)) {
        return false;
      }
      if (value.length < 3 || value.length > 63) {
        return false;
      }
      if (value !== value.toLowerCase()) {
        return false;
      }
      if (isIpAddress(value)) {
        return false;
      }
      return true;
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js
var ARN_DELIMITER, RESOURCE_DELIMITER, parseArn;
var init_parseArn = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js"() {
    "use strict";
    ARN_DELIMITER = ":";
    RESOURCE_DELIMITER = "/";
    parseArn = (value) => {
      const segments = value.split(ARN_DELIMITER);
      if (segments.length < 6)
        return null;
      const [arn, partition2, service, region, accountId, ...resourcePath] = segments;
      if (arn !== "arn" || partition2 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "")
        return null;
      const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat();
      return {
        partition: partition2,
        service,
        region,
        accountId,
        resourceId
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json
var partitions_default;
var init_partitions = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json"() {
    partitions_default = {
      partitions: [{
        id: "aws",
        outputs: {
          dnsSuffix: "amazonaws.com",
          dualStackDnsSuffix: "api.aws",
          implicitGlobalRegion: "us-east-1",
          name: "aws",
          supportsDualStack: true,
          supportsFIPS: true
        },
        regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",
        regions: {
          "af-south-1": {
            description: "Africa (Cape Town)"
          },
          "ap-east-1": {
            description: "Asia Pacific (Hong Kong)"
          },
          "ap-northeast-1": {
            description: "Asia Pacific (Tokyo)"
          },
          "ap-northeast-2": {
            description: "Asia Pacific (Seoul)"
          },
          "ap-northeast-3": {
            description: "Asia Pacific (Osaka)"
          },
          "ap-south-1": {
            description: "Asia Pacific (Mumbai)"
          },
          "ap-south-2": {
            description: "Asia Pacific (Hyderabad)"
          },
          "ap-southeast-1": {
            description: "Asia Pacific (Singapore)"
          },
          "ap-southeast-2": {
            description: "Asia Pacific (Sydney)"
          },
          "ap-southeast-3": {
            description: "Asia Pacific (Jakarta)"
          },
          "ap-southeast-4": {
            description: "Asia Pacific (Melbourne)"
          },
          "ap-southeast-5": {
            description: "Asia Pacific (Malaysia)"
          },
          "ap-southeast-7": {
            description: "Asia Pacific (Thailand)"
          },
          "aws-global": {
            description: "AWS Standard global region"
          },
          "ca-central-1": {
            description: "Canada (Central)"
          },
          "ca-west-1": {
            description: "Canada West (Calgary)"
          },
          "eu-central-1": {
            description: "Europe (Frankfurt)"
          },
          "eu-central-2": {
            description: "Europe (Zurich)"
          },
          "eu-north-1": {
            description: "Europe (Stockholm)"
          },
          "eu-south-1": {
            description: "Europe (Milan)"
          },
          "eu-south-2": {
            description: "Europe (Spain)"
          },
          "eu-west-1": {
            description: "Europe (Ireland)"
          },
          "eu-west-2": {
            description: "Europe (London)"
          },
          "eu-west-3": {
            description: "Europe (Paris)"
          },
          "il-central-1": {
            description: "Israel (Tel Aviv)"
          },
          "me-central-1": {
            description: "Middle East (UAE)"
          },
          "me-south-1": {
            description: "Middle East (Bahrain)"
          },
          "mx-central-1": {
            description: "Mexico (Central)"
          },
          "sa-east-1": {
            description: "South America (Sao Paulo)"
          },
          "us-east-1": {
            description: "US East (N. Virginia)"
          },
          "us-east-2": {
            description: "US East (Ohio)"
          },
          "us-west-1": {
            description: "US West (N. California)"
          },
          "us-west-2": {
            description: "US West (Oregon)"
          }
        }
      }, {
        id: "aws-cn",
        outputs: {
          dnsSuffix: "amazonaws.com.cn",
          dualStackDnsSuffix: "api.amazonwebservices.com.cn",
          implicitGlobalRegion: "cn-northwest-1",
          name: "aws-cn",
          supportsDualStack: true,
          supportsFIPS: true
        },
        regionRegex: "^cn\\-\\w+\\-\\d+$",
        regions: {
          "aws-cn-global": {
            description: "AWS China global region"
          },
          "cn-north-1": {
            description: "China (Beijing)"
          },
          "cn-northwest-1": {
            description: "China (Ningxia)"
          }
        }
      }, {
        id: "aws-us-gov",
        outputs: {
          dnsSuffix: "amazonaws.com",
          dualStackDnsSuffix: "api.aws",
          implicitGlobalRegion: "us-gov-west-1",
          name: "aws-us-gov",
          supportsDualStack: true,
          supportsFIPS: true
        },
        regionRegex: "^us\\-gov\\-\\w+\\-\\d+$",
        regions: {
          "aws-us-gov-global": {
            description: "AWS GovCloud (US) global region"
          },
          "us-gov-east-1": {
            description: "AWS GovCloud (US-East)"
          },
          "us-gov-west-1": {
            description: "AWS GovCloud (US-West)"
          }
        }
      }, {
        id: "aws-iso",
        outputs: {
          dnsSuffix: "c2s.ic.gov",
          dualStackDnsSuffix: "c2s.ic.gov",
          implicitGlobalRegion: "us-iso-east-1",
          name: "aws-iso",
          supportsDualStack: false,
          supportsFIPS: true
        },
        regionRegex: "^us\\-iso\\-\\w+\\-\\d+$",
        regions: {
          "aws-iso-global": {
            description: "AWS ISO (US) global region"
          },
          "us-iso-east-1": {
            description: "US ISO East"
          },
          "us-iso-west-1": {
            description: "US ISO WEST"
          }
        }
      }, {
        id: "aws-iso-b",
        outputs: {
          dnsSuffix: "sc2s.sgov.gov",
          dualStackDnsSuffix: "sc2s.sgov.gov",
          implicitGlobalRegion: "us-isob-east-1",
          name: "aws-iso-b",
          supportsDualStack: false,
          supportsFIPS: true
        },
        regionRegex: "^us\\-isob\\-\\w+\\-\\d+$",
        regions: {
          "aws-iso-b-global": {
            description: "AWS ISOB (US) global region"
          },
          "us-isob-east-1": {
            description: "US ISOB East (Ohio)"
          }
        }
      }, {
        id: "aws-iso-e",
        outputs: {
          dnsSuffix: "cloud.adc-e.uk",
          dualStackDnsSuffix: "cloud.adc-e.uk",
          implicitGlobalRegion: "eu-isoe-west-1",
          name: "aws-iso-e",
          supportsDualStack: false,
          supportsFIPS: true
        },
        regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$",
        regions: {
          "aws-iso-e-global": {
            description: "AWS ISOE (Europe) global region"
          },
          "eu-isoe-west-1": {
            description: "EU ISOE West"
          }
        }
      }, {
        id: "aws-iso-f",
        outputs: {
          dnsSuffix: "csp.hci.ic.gov",
          dualStackDnsSuffix: "csp.hci.ic.gov",
          implicitGlobalRegion: "us-isof-south-1",
          name: "aws-iso-f",
          supportsDualStack: false,
          supportsFIPS: true
        },
        regionRegex: "^us\\-isof\\-\\w+\\-\\d+$",
        regions: {
          "aws-iso-f-global": {
            description: "AWS ISOF global region"
          },
          "us-isof-east-1": {
            description: "US ISOF EAST"
          },
          "us-isof-south-1": {
            description: "US ISOF SOUTH"
          }
        }
      }, {
        id: "aws-eusc",
        outputs: {
          dnsSuffix: "amazonaws.eu",
          dualStackDnsSuffix: "amazonaws.eu",
          implicitGlobalRegion: "eusc-de-east-1",
          name: "aws-eusc",
          supportsDualStack: false,
          supportsFIPS: true
        },
        regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$",
        regions: {
          "eusc-de-east-1": {
            description: "EU (Germany)"
          }
        }
      }],
      version: "1.1"
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js
var selectedPartitionsInfo, selectedUserAgentPrefix, partition, getUserAgentPrefix;
var init_partition = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js"() {
    "use strict";
    init_partitions();
    selectedPartitionsInfo = partitions_default;
    selectedUserAgentPrefix = "";
    partition = (value) => {
      const { partitions } = selectedPartitionsInfo;
      for (const partition2 of partitions) {
        const { regions, outputs: outputs2 } = partition2;
        for (const [region, regionData] of Object.entries(regions)) {
          if (region === value) {
            return {
              ...outputs2,
              ...regionData
            };
          }
        }
      }
      for (const partition2 of partitions) {
        const { regionRegex, outputs: outputs2 } = partition2;
        if (new RegExp(regionRegex).test(value)) {
          return {
            ...outputs2
          };
        }
      }
      const DEFAULT_PARTITION = partitions.find((partition2) => partition2.id === "aws");
      if (!DEFAULT_PARTITION) {
        throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");
      }
      return {
        ...DEFAULT_PARTITION.outputs
      };
    };
    getUserAgentPrefix = () => selectedUserAgentPrefix;
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/aws.js
var awsEndpointFunctions;
var init_aws = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/aws.js"() {
    "use strict";
    init_dist_es19();
    init_isVirtualHostableS3Bucket();
    init_parseArn();
    init_partition();
    awsEndpointFunctions = {
      isVirtualHostableS3Bucket,
      parseArn,
      partition
    };
    customEndpointFunctions.aws = awsEndpointFunctions;
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js
var init_resolveEndpoint2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js"() {
    "use strict";
    init_dist_es19();
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js
var init_EndpointError2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js"() {
    "use strict";
    init_dist_es19();
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js
var init_EndpointRuleObject3 = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js
var init_ErrorRuleObject3 = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js
var init_RuleSetObject3 = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js
var init_TreeRuleObject3 = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js
var init_shared3 = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js
var init_types4 = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js"() {
    "use strict";
    init_EndpointError2();
    init_EndpointRuleObject3();
    init_ErrorRuleObject3();
    init_RuleSetObject3();
    init_TreeRuleObject3();
    init_shared3();
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/index.js
var init_dist_es20 = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/index.js"() {
    "use strict";
    init_aws();
    init_partition();
    init_isIpAddress2();
    init_resolveEndpoint2();
    init_types4();
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js
var state, emitWarningIfUnsupportedVersion;
var init_emitWarningIfUnsupportedVersion = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js"() {
    "use strict";
    state = {
      warningEmitted: false
    };
    emitWarningIfUnsupportedVersion = (version) => {
      if (version && !state.warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 18) {
        state.warningEmitted = true;
        process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will
no longer support Node.js 16.x on January 6, 2025.

To continue receiving updates to AWS services, bug fixes, and security
updates please upgrade to a supported Node.js LTS version.

More information can be found at: https://a.co/74kJMmI`);
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js
function setCredentialFeature(credentials2, feature, value) {
  if (!credentials2.$source) {
    credentials2.$source = {};
  }
  credentials2.$source[feature] = value;
  return credentials2;
}
var init_setCredentialFeature = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js
function setFeature2(context, feature, value) {
  if (!context.__aws_sdk_context) {
    context.__aws_sdk_context = {
      features: {}
    };
  } else if (!context.__aws_sdk_context.features) {
    context.__aws_sdk_context.features = {};
  }
  context.__aws_sdk_context.features[feature] = value;
}
var init_setFeature2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/index.js
var init_client2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/index.js"() {
    "use strict";
    init_emitWarningIfUnsupportedVersion();
    init_setCredentialFeature();
    init_setFeature2();
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js
var getDateHeader;
var init_getDateHeader = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js"() {
    "use strict";
    init_dist_es2();
    getDateHeader = (response) => HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : void 0;
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js
var getSkewCorrectedDate;
var init_getSkewCorrectedDate = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js"() {
    "use strict";
    getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset);
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js
var isClockSkewed;
var init_isClockSkewed = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js"() {
    "use strict";
    init_getSkewCorrectedDate();
    isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5;
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js
var getUpdatedSystemClockOffset;
var init_getUpdatedSystemClockOffset = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js"() {
    "use strict";
    init_isClockSkewed();
    getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => {
      const clockTimeInMs = Date.parse(clockTime);
      if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) {
        return clockTimeInMs - Date.now();
      }
      return currentSystemClockOffset;
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js
var init_utils6 = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js"() {
    "use strict";
    init_getDateHeader();
    init_getSkewCorrectedDate();
    init_getUpdatedSystemClockOffset();
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js
var throwSigningPropertyError, validateSigningProperties, AwsSdkSigV4Signer;
var init_AwsSdkSigV4Signer = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js"() {
    "use strict";
    init_dist_es2();
    init_utils6();
    throwSigningPropertyError = (name, property) => {
      if (!property) {
        throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`);
      }
      return property;
    };
    validateSigningProperties = async (signingProperties) => {
      const context = throwSigningPropertyError("context", signingProperties.context);
      const config = throwSigningPropertyError("config", signingProperties.config);
      const authScheme = context.endpointV2?.properties?.authSchemes?.[0];
      const signerFunction = throwSigningPropertyError("signer", config.signer);
      const signer = await signerFunction(authScheme);
      const signingRegion = signingProperties?.signingRegion;
      const signingRegionSet = signingProperties?.signingRegionSet;
      const signingName = signingProperties?.signingName;
      return {
        config,
        signer,
        signingRegion,
        signingRegionSet,
        signingName
      };
    };
    AwsSdkSigV4Signer = class {
      async sign(httpRequest2, identity, signingProperties) {
        if (!HttpRequest.isInstance(httpRequest2)) {
          throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");
        }
        const validatedProps = await validateSigningProperties(signingProperties);
        const { config, signer } = validatedProps;
        let { signingRegion, signingName } = validatedProps;
        const handlerExecutionContext = signingProperties.context;
        if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) {
          const [first, second] = handlerExecutionContext.authSchemes;
          if (first?.name === "sigv4a" && second?.name === "sigv4") {
            signingRegion = second?.signingRegion ?? signingRegion;
            signingName = second?.signingName ?? signingName;
          }
        }
        const signedRequest = await signer.sign(httpRequest2, {
          signingDate: getSkewCorrectedDate(config.systemClockOffset),
          signingRegion,
          signingService: signingName
        });
        return signedRequest;
      }
      errorHandler(signingProperties) {
        return (error2) => {
          const serverTime = error2.ServerTime ?? getDateHeader(error2.$response);
          if (serverTime) {
            const config = throwSigningPropertyError("config", signingProperties.config);
            const initialSystemClockOffset = config.systemClockOffset;
            config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset);
            const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset;
            if (clockSkewCorrected && error2.$metadata) {
              error2.$metadata.clockSkewCorrected = true;
            }
          }
          throw error2;
        };
      }
      successHandler(httpResponse, signingProperties) {
        const dateHeader = getDateHeader(httpResponse);
        if (dateHeader) {
          const config = throwSigningPropertyError("config", signingProperties.config);
          config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset);
        }
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.js
var getArrayForCommaSeparatedString;
var init_getArrayForCommaSeparatedString = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.js"() {
    "use strict";
    getArrayForCommaSeparatedString = (str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : [];
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.js
var getBearerTokenEnvKey;
var init_getBearerTokenEnvKey = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.js"() {
    "use strict";
    getBearerTokenEnvKey = (signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`;
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.js
var NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY, NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS;
var init_NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.js"() {
    "use strict";
    init_getArrayForCommaSeparatedString();
    init_getBearerTokenEnvKey();
    NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE";
    NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference";
    NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = {
      environmentVariableSelector: (env4, options) => {
        if (options?.signingName) {
          const bearerTokenKey = getBearerTokenEnvKey(options.signingName);
          if (bearerTokenKey in env4)
            return ["httpBearerAuth"];
        }
        if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env4))
          return void 0;
        return getArrayForCommaSeparatedString(env4[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]);
      },
      configFileSelector: (profile) => {
        if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile))
          return void 0;
        return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]);
      },
      default: []
    };
  }
});

// ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/ProviderError.js
var ProviderError;
var init_ProviderError = __esm({
  "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/ProviderError.js"() {
    "use strict";
    ProviderError = class _ProviderError extends Error {
      constructor(message, options = true) {
        let logger2;
        let tryNextLink = true;
        if (typeof options === "boolean") {
          logger2 = void 0;
          tryNextLink = options;
        } else if (options != null && typeof options === "object") {
          logger2 = options.logger;
          tryNextLink = options.tryNextLink ?? true;
        }
        super(message);
        this.name = "ProviderError";
        this.tryNextLink = tryNextLink;
        Object.setPrototypeOf(this, _ProviderError.prototype);
        logger2?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`);
      }
      static from(error2, options = true) {
        return Object.assign(new this(error2.message, options), error2);
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/CredentialsProviderError.js
var CredentialsProviderError;
var init_CredentialsProviderError = __esm({
  "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/CredentialsProviderError.js"() {
    "use strict";
    init_ProviderError();
    CredentialsProviderError = class _CredentialsProviderError extends ProviderError {
      constructor(message, options = true) {
        super(message, options);
        this.name = "CredentialsProviderError";
        Object.setPrototypeOf(this, _CredentialsProviderError.prototype);
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/TokenProviderError.js
var TokenProviderError;
var init_TokenProviderError = __esm({
  "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/TokenProviderError.js"() {
    "use strict";
    init_ProviderError();
    TokenProviderError = class _TokenProviderError extends ProviderError {
      constructor(message, options = true) {
        super(message, options);
        this.name = "TokenProviderError";
        Object.setPrototypeOf(this, _TokenProviderError.prototype);
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/chain.js
var chain;
var init_chain = __esm({
  "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/chain.js"() {
    "use strict";
    init_ProviderError();
    chain = (...providers) => async () => {
      if (providers.length === 0) {
        throw new ProviderError("No providers in chain");
      }
      let lastProviderError;
      for (const provider of providers) {
        try {
          const credentials2 = await provider();
          return credentials2;
        } catch (err2) {
          lastProviderError = err2;
          if (err2?.tryNextLink) {
            continue;
          }
          throw err2;
        }
      }
      throw lastProviderError;
    };
  }
});

// ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/fromStatic.js
var fromStatic;
var init_fromStatic = __esm({
  "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/fromStatic.js"() {
    "use strict";
    fromStatic = (staticValue) => () => Promise.resolve(staticValue);
  }
});

// ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/memoize.js
var memoize;
var init_memoize = __esm({
  "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/memoize.js"() {
    "use strict";
    memoize = (provider, isExpired, requiresRefresh) => {
      let resolved;
      let pending;
      let hasResult;
      let isConstant = false;
      const coalesceProvider = async () => {
        if (!pending) {
          pending = provider();
        }
        try {
          resolved = await pending;
          hasResult = true;
          isConstant = false;
        } finally {
          pending = void 0;
        }
        return resolved;
      };
      if (isExpired === void 0) {
        return async (options) => {
          if (!hasResult || options?.forceRefresh) {
            resolved = await coalesceProvider();
          }
          return resolved;
        };
      }
      return async (options) => {
        if (!hasResult || options?.forceRefresh) {
          resolved = await coalesceProvider();
        }
        if (isConstant) {
          return resolved;
        }
        if (requiresRefresh && !requiresRefresh(resolved)) {
          isConstant = true;
          return resolved;
        }
        if (isExpired(resolved)) {
          await coalesceProvider();
          return resolved;
        }
        return resolved;
      };
    };
  }
});

// ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/index.js
var init_dist_es21 = __esm({
  "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/index.js"() {
    "use strict";
    init_CredentialsProviderError();
    init_ProviderError();
    init_TokenProviderError();
    init_chain();
    init_fromStatic();
    init_memoize();
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js
var init_resolveAwsSdkSigV4AConfig = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js"() {
    "use strict";
    init_dist_es18();
    init_dist_es21();
  }
});

// ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/constants.js
var ALGORITHM_QUERY_PARAM, CREDENTIAL_QUERY_PARAM, AMZ_DATE_QUERY_PARAM, SIGNED_HEADERS_QUERY_PARAM, EXPIRES_QUERY_PARAM, SIGNATURE_QUERY_PARAM, TOKEN_QUERY_PARAM, AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER, GENERATED_HEADERS, SIGNATURE_HEADER, SHA256_HEADER, TOKEN_HEADER, ALWAYS_UNSIGNABLE_HEADERS, PROXY_HEADER_PATTERN, SEC_HEADER_PATTERN, ALGORITHM_IDENTIFIER, EVENT_ALGORITHM_IDENTIFIER, UNSIGNED_PAYLOAD, MAX_CACHE_SIZE, KEY_TYPE_IDENTIFIER, MAX_PRESIGNED_TTL;
var init_constants3 = __esm({
  "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/constants.js"() {
    "use strict";
    ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm";
    CREDENTIAL_QUERY_PARAM = "X-Amz-Credential";
    AMZ_DATE_QUERY_PARAM = "X-Amz-Date";
    SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders";
    EXPIRES_QUERY_PARAM = "X-Amz-Expires";
    SIGNATURE_QUERY_PARAM = "X-Amz-Signature";
    TOKEN_QUERY_PARAM = "X-Amz-Security-Token";
    AUTH_HEADER = "authorization";
    AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase();
    DATE_HEADER = "date";
    GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER];
    SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase();
    SHA256_HEADER = "x-amz-content-sha256";
    TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase();
    ALWAYS_UNSIGNABLE_HEADERS = {
      authorization: true,
      "cache-control": true,
      connection: true,
      expect: true,
      from: true,
      "keep-alive": true,
      "max-forwards": true,
      pragma: true,
      referer: true,
      te: true,
      trailer: true,
      "transfer-encoding": true,
      upgrade: true,
      "user-agent": true,
      "x-amzn-trace-id": true
    };
    PROXY_HEADER_PATTERN = /^proxy-/;
    SEC_HEADER_PATTERN = /^sec-/;
    ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256";
    EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD";
    UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
    MAX_CACHE_SIZE = 50;
    KEY_TYPE_IDENTIFIER = "aws4_request";
    MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7;
  }
});

// ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/credentialDerivation.js
var signingKeyCache, cacheQueue, createScope, getSigningKey, hmac;
var init_credentialDerivation = __esm({
  "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/credentialDerivation.js"() {
    "use strict";
    init_dist_es16();
    init_dist_es10();
    init_constants3();
    signingKeyCache = {};
    cacheQueue = [];
    createScope = (shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`;
    getSigningKey = async (sha256Constructor, credentials2, shortDate, region, service) => {
      const credsHash = await hmac(sha256Constructor, credentials2.secretAccessKey, credentials2.accessKeyId);
      const cacheKey2 = `${shortDate}:${region}:${service}:${toHex(credsHash)}:${credentials2.sessionToken}`;
      if (cacheKey2 in signingKeyCache) {
        return signingKeyCache[cacheKey2];
      }
      cacheQueue.push(cacheKey2);
      while (cacheQueue.length > MAX_CACHE_SIZE) {
        delete signingKeyCache[cacheQueue.shift()];
      }
      let key = `AWS4${credentials2.secretAccessKey}`;
      for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) {
        key = await hmac(sha256Constructor, key, signable);
      }
      return signingKeyCache[cacheKey2] = key;
    };
    hmac = (ctor, secret, data) => {
      const hash = new ctor(secret);
      hash.update(toUint8Array(data));
      return hash.digest();
    };
  }
});

// ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/getCanonicalHeaders.js
var getCanonicalHeaders;
var init_getCanonicalHeaders = __esm({
  "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/getCanonicalHeaders.js"() {
    "use strict";
    init_constants3();
    getCanonicalHeaders = ({ headers }, unsignableHeaders, signableHeaders) => {
      const canonical = {};
      for (const headerName of Object.keys(headers).sort()) {
        if (headers[headerName] == void 0) {
          continue;
        }
        const canonicalHeaderName = headerName.toLowerCase();
        if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || unsignableHeaders?.has(canonicalHeaderName) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) {
          if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) {
            continue;
          }
        }
        canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " ");
      }
      return canonical;
    };
  }
});

// ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/getPayloadHash.js
var getPayloadHash;
var init_getPayloadHash = __esm({
  "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/getPayloadHash.js"() {
    "use strict";
    init_dist_es8();
    init_dist_es16();
    init_dist_es10();
    init_constants3();
    getPayloadHash = async ({ headers, body }, hashConstructor) => {
      for (const headerName of Object.keys(headers)) {
        if (headerName.toLowerCase() === SHA256_HEADER) {
          return headers[headerName];
        }
      }
      if (body == void 0) {
        return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
      } else if (typeof body === "string" || ArrayBuffer.isView(body) || isArrayBuffer(body)) {
        const hashCtor = new hashConstructor();
        hashCtor.update(toUint8Array(body));
        return toHex(await hashCtor.digest());
      }
      return UNSIGNED_PAYLOAD;
    };
  }
});

// ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/HeaderFormatter.js
function negate(bytes) {
  for (let i6 = 0; i6 < 8; i6++) {
    bytes[i6] ^= 255;
  }
  for (let i6 = 7; i6 > -1; i6--) {
    bytes[i6]++;
    if (bytes[i6] !== 0)
      break;
  }
}
var HeaderFormatter, HEADER_VALUE_TYPE, UUID_PATTERN, Int64;
var init_HeaderFormatter = __esm({
  "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/HeaderFormatter.js"() {
    "use strict";
    init_dist_es16();
    init_dist_es10();
    HeaderFormatter = class {
      format(headers) {
        const chunks = [];
        for (const headerName of Object.keys(headers)) {
          const bytes = fromUtf8(headerName);
          chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName]));
        }
        const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0));
        let position = 0;
        for (const chunk of chunks) {
          out.set(chunk, position);
          position += chunk.byteLength;
        }
        return out;
      }
      formatHeaderValue(header) {
        switch (header.type) {
          case "boolean":
            return Uint8Array.from([header.value ? 0 : 1]);
          case "byte":
            return Uint8Array.from([2, header.value]);
          case "short":
            const shortView = new DataView(new ArrayBuffer(3));
            shortView.setUint8(0, 3);
            shortView.setInt16(1, header.value, false);
            return new Uint8Array(shortView.buffer);
          case "integer":
            const intView = new DataView(new ArrayBuffer(5));
            intView.setUint8(0, 4);
            intView.setInt32(1, header.value, false);
            return new Uint8Array(intView.buffer);
          case "long":
            const longBytes = new Uint8Array(9);
            longBytes[0] = 5;
            longBytes.set(header.value.bytes, 1);
            return longBytes;
          case "binary":
            const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength));
            binView.setUint8(0, 6);
            binView.setUint16(1, header.value.byteLength, false);
            const binBytes = new Uint8Array(binView.buffer);
            binBytes.set(header.value, 3);
            return binBytes;
          case "string":
            const utf8Bytes = fromUtf8(header.value);
            const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength));
            strView.setUint8(0, 7);
            strView.setUint16(1, utf8Bytes.byteLength, false);
            const strBytes = new Uint8Array(strView.buffer);
            strBytes.set(utf8Bytes, 3);
            return strBytes;
          case "timestamp":
            const tsBytes = new Uint8Array(9);
            tsBytes[0] = 8;
            tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1);
            return tsBytes;
          case "uuid":
            if (!UUID_PATTERN.test(header.value)) {
              throw new Error(`Invalid UUID received: ${header.value}`);
            }
            const uuidBytes = new Uint8Array(17);
            uuidBytes[0] = 9;
            uuidBytes.set(fromHex(header.value.replace(/\-/g, "")), 1);
            return uuidBytes;
        }
      }
    };
    (function(HEADER_VALUE_TYPE2) {
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolTrue"] = 0] = "boolTrue";
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolFalse"] = 1] = "boolFalse";
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byte"] = 2] = "byte";
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["short"] = 3] = "short";
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["integer"] = 4] = "integer";
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["long"] = 5] = "long";
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byteArray"] = 6] = "byteArray";
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["string"] = 7] = "string";
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["timestamp"] = 8] = "timestamp";
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["uuid"] = 9] = "uuid";
    })(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {}));
    UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
    Int64 = class _Int64 {
      constructor(bytes) {
        this.bytes = bytes;
        if (bytes.byteLength !== 8) {
          throw new Error("Int64 buffers must be exactly 8 bytes");
        }
      }
      static fromNumber(number) {
        if (number > 9223372036854776e3 || number < -9223372036854776e3) {
          throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`);
        }
        const bytes = new Uint8Array(8);
        for (let i6 = 7, remaining = Math.abs(Math.round(number)); i6 > -1 && remaining > 0; i6--, remaining /= 256) {
          bytes[i6] = remaining;
        }
        if (number < 0) {
          negate(bytes);
        }
        return new _Int64(bytes);
      }
      valueOf() {
        const bytes = this.bytes.slice(0);
        const negative = bytes[0] & 128;
        if (negative) {
          negate(bytes);
        }
        return parseInt(toHex(bytes), 16) * (negative ? -1 : 1);
      }
      toString() {
        return String(this.valueOf());
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/headerUtil.js
var hasHeader;
var init_headerUtil = __esm({
  "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/headerUtil.js"() {
    "use strict";
    hasHeader = (soughtHeader, headers) => {
      soughtHeader = soughtHeader.toLowerCase();
      for (const headerName of Object.keys(headers)) {
        if (soughtHeader === headerName.toLowerCase()) {
          return true;
        }
      }
      return false;
    };
  }
});

// ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/moveHeadersToQuery.js
var moveHeadersToQuery;
var init_moveHeadersToQuery = __esm({
  "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/moveHeadersToQuery.js"() {
    "use strict";
    init_dist_es2();
    moveHeadersToQuery = (request2, options = {}) => {
      const { headers, query = {} } = HttpRequest.clone(request2);
      for (const name of Object.keys(headers)) {
        const lname = name.toLowerCase();
        if (lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname) || options.hoistableHeaders?.has(lname)) {
          query[name] = headers[name];
          delete headers[name];
        }
      }
      return {
        ...request2,
        headers,
        query
      };
    };
  }
});

// ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/prepareRequest.js
var prepareRequest;
var init_prepareRequest = __esm({
  "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/prepareRequest.js"() {
    "use strict";
    init_dist_es2();
    init_constants3();
    prepareRequest = (request2) => {
      request2 = HttpRequest.clone(request2);
      for (const headerName of Object.keys(request2.headers)) {
        if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) {
          delete request2.headers[headerName];
        }
      }
      return request2;
    };
  }
});

// ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/getCanonicalQuery.js
var getCanonicalQuery;
var init_getCanonicalQuery = __esm({
  "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/getCanonicalQuery.js"() {
    "use strict";
    init_dist_es12();
    init_constants3();
    getCanonicalQuery = ({ query = {} }) => {
      const keys = [];
      const serialized = {};
      for (const key of Object.keys(query)) {
        if (key.toLowerCase() === SIGNATURE_HEADER) {
          continue;
        }
        const encodedKey = escapeUri(key);
        keys.push(encodedKey);
        const value = query[key];
        if (typeof value === "string") {
          serialized[encodedKey] = `${encodedKey}=${escapeUri(value)}`;
        } else if (Array.isArray(value)) {
          serialized[encodedKey] = value.slice(0).reduce((encoded, value2) => encoded.concat([`${encodedKey}=${escapeUri(value2)}`]), []).sort().join("&");
        }
      }
      return keys.sort().map((key) => serialized[key]).filter((serialized2) => serialized2).join("&");
    };
  }
});

// ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/utilDate.js
var iso8601, toDate;
var init_utilDate = __esm({
  "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/utilDate.js"() {
    "use strict";
    iso8601 = (time) => toDate(time).toISOString().replace(/\.\d{3}Z$/, "Z");
    toDate = (time) => {
      if (typeof time === "number") {
        return new Date(time * 1e3);
      }
      if (typeof time === "string") {
        if (Number(time)) {
          return new Date(Number(time) * 1e3);
        }
        return new Date(time);
      }
      return time;
    };
  }
});

// ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/SignatureV4Base.js
var SignatureV4Base;
var init_SignatureV4Base = __esm({
  "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/SignatureV4Base.js"() {
    "use strict";
    init_dist_es16();
    init_dist_es6();
    init_dist_es12();
    init_dist_es10();
    init_getCanonicalQuery();
    init_utilDate();
    SignatureV4Base = class {
      constructor({ applyChecksum, credentials: credentials2, region, service, sha256: sha2562, uriEscapePath = true }) {
        this.service = service;
        this.sha256 = sha2562;
        this.uriEscapePath = uriEscapePath;
        this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true;
        this.regionProvider = normalizeProvider(region);
        this.credentialProvider = normalizeProvider(credentials2);
      }
      createCanonicalRequest(request2, canonicalHeaders, payloadHash) {
        const sortedHeaders = Object.keys(canonicalHeaders).sort();
        return `${request2.method}
${this.getCanonicalPath(request2)}
${getCanonicalQuery(request2)}
${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")}

${sortedHeaders.join(";")}
${payloadHash}`;
      }
      async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) {
        const hash = new this.sha256();
        hash.update(toUint8Array(canonicalRequest));
        const hashedRequest = await hash.digest();
        return `${algorithmIdentifier}
${longDate}
${credentialScope}
${toHex(hashedRequest)}`;
      }
      getCanonicalPath({ path: path3 }) {
        if (this.uriEscapePath) {
          const normalizedPathSegments = [];
          for (const pathSegment of path3.split("/")) {
            if (pathSegment?.length === 0)
              continue;
            if (pathSegment === ".")
              continue;
            if (pathSegment === "..") {
              normalizedPathSegments.pop();
            } else {
              normalizedPathSegments.push(pathSegment);
            }
          }
          const normalizedPath = `${path3?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path3?.endsWith("/") ? "/" : ""}`;
          const doubleEncoded = escapeUri(normalizedPath);
          return doubleEncoded.replace(/%2F/g, "/");
        }
        return path3;
      }
      validateResolvedCredentials(credentials2) {
        if (typeof credentials2 !== "object" || typeof credentials2.accessKeyId !== "string" || typeof credentials2.secretAccessKey !== "string") {
          throw new Error("Resolved credential object is not valid");
        }
      }
      formatDate(now) {
        const longDate = iso8601(now).replace(/[\-:]/g, "");
        return {
          longDate,
          shortDate: longDate.slice(0, 8)
        };
      }
      getCanonicalHeaderList(headers) {
        return Object.keys(headers).sort().join(";");
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/SignatureV4.js
var SignatureV4;
var init_SignatureV4 = __esm({
  "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/SignatureV4.js"() {
    "use strict";
    init_dist_es16();
    init_dist_es10();
    init_constants3();
    init_credentialDerivation();
    init_getCanonicalHeaders();
    init_getPayloadHash();
    init_HeaderFormatter();
    init_headerUtil();
    init_moveHeadersToQuery();
    init_prepareRequest();
    init_SignatureV4Base();
    SignatureV4 = class extends SignatureV4Base {
      constructor({ applyChecksum, credentials: credentials2, region, service, sha256: sha2562, uriEscapePath = true }) {
        super({
          applyChecksum,
          credentials: credentials2,
          region,
          service,
          sha256: sha2562,
          uriEscapePath
        });
        this.headerFormatter = new HeaderFormatter();
      }
      async presign(originalRequest, options = {}) {
        const { signingDate = /* @__PURE__ */ new Date(), expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, hoistableHeaders, signingRegion, signingService } = options;
        const credentials2 = await this.credentialProvider();
        this.validateResolvedCredentials(credentials2);
        const region = signingRegion ?? await this.regionProvider();
        const { longDate, shortDate } = this.formatDate(signingDate);
        if (expiresIn > MAX_PRESIGNED_TTL) {
          return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");
        }
        const scope = createScope(shortDate, region, signingService ?? this.service);
        const request2 = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders });
        if (credentials2.sessionToken) {
          request2.query[TOKEN_QUERY_PARAM] = credentials2.sessionToken;
        }
        request2.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER;
        request2.query[CREDENTIAL_QUERY_PARAM] = `${credentials2.accessKeyId}/${scope}`;
        request2.query[AMZ_DATE_QUERY_PARAM] = longDate;
        request2.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10);
        const canonicalHeaders = getCanonicalHeaders(request2, unsignableHeaders, signableHeaders);
        request2.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders);
        request2.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(longDate, scope, this.getSigningKey(credentials2, region, shortDate, signingService), this.createCanonicalRequest(request2, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256)));
        return request2;
      }
      async sign(toSign, options) {
        if (typeof toSign === "string") {
          return this.signString(toSign, options);
        } else if (toSign.headers && toSign.payload) {
          return this.signEvent(toSign, options);
        } else if (toSign.message) {
          return this.signMessage(toSign, options);
        } else {
          return this.signRequest(toSign, options);
        }
      }
      async signEvent({ headers, payload }, { signingDate = /* @__PURE__ */ new Date(), priorSignature, signingRegion, signingService }) {
        const region = signingRegion ?? await this.regionProvider();
        const { shortDate, longDate } = this.formatDate(signingDate);
        const scope = createScope(shortDate, region, signingService ?? this.service);
        const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256);
        const hash = new this.sha256();
        hash.update(headers);
        const hashedHeaders = toHex(await hash.digest());
        const stringToSign = [
          EVENT_ALGORITHM_IDENTIFIER,
          longDate,
          scope,
          priorSignature,
          hashedHeaders,
          hashedPayload
        ].join("\n");
        return this.signString(stringToSign, { signingDate, signingRegion: region, signingService });
      }
      async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) {
        const promise = this.signEvent({
          headers: this.headerFormatter.format(signableMessage.message.headers),
          payload: signableMessage.message.body
        }, {
          signingDate,
          signingRegion,
          signingService,
          priorSignature: signableMessage.priorSignature
        });
        return promise.then((signature) => {
          return { message: signableMessage.message, signature };
        });
      }
      async signString(stringToSign, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService } = {}) {
        const credentials2 = await this.credentialProvider();
        this.validateResolvedCredentials(credentials2);
        const region = signingRegion ?? await this.regionProvider();
        const { shortDate } = this.formatDate(signingDate);
        const hash = new this.sha256(await this.getSigningKey(credentials2, region, shortDate, signingService));
        hash.update(toUint8Array(stringToSign));
        return toHex(await hash.digest());
      }
      async signRequest(requestToSign, { signingDate = /* @__PURE__ */ new Date(), signableHeaders, unsignableHeaders, signingRegion, signingService } = {}) {
        const credentials2 = await this.credentialProvider();
        this.validateResolvedCredentials(credentials2);
        const region = signingRegion ?? await this.regionProvider();
        const request2 = prepareRequest(requestToSign);
        const { longDate, shortDate } = this.formatDate(signingDate);
        const scope = createScope(shortDate, region, signingService ?? this.service);
        request2.headers[AMZ_DATE_HEADER] = longDate;
        if (credentials2.sessionToken) {
          request2.headers[TOKEN_HEADER] = credentials2.sessionToken;
        }
        const payloadHash = await getPayloadHash(request2, this.sha256);
        if (!hasHeader(SHA256_HEADER, request2.headers) && this.applyChecksum) {
          request2.headers[SHA256_HEADER] = payloadHash;
        }
        const canonicalHeaders = getCanonicalHeaders(request2, unsignableHeaders, signableHeaders);
        const signature = await this.getSignature(longDate, scope, this.getSigningKey(credentials2, region, shortDate, signingService), this.createCanonicalRequest(request2, canonicalHeaders, payloadHash));
        request2.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials2.accessKeyId}/${scope}, SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`;
        return request2;
      }
      async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) {
        const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest, ALGORITHM_IDENTIFIER);
        const hash = new this.sha256(await keyPromise);
        hash.update(toUint8Array(stringToSign));
        return toHex(await hash.digest());
      }
      getSigningKey(credentials2, region, shortDate, service) {
        return getSigningKey(this.sha256, credentials2, shortDate, region, service || this.service);
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/signature-v4a-container.js
var init_signature_v4a_container = __esm({
  "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/signature-v4a-container.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/index.js
var init_dist_es22 = __esm({
  "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/index.js"() {
    "use strict";
    init_SignatureV4();
    init_constants3();
    init_getCanonicalHeaders();
    init_getCanonicalQuery();
    init_getPayloadHash();
    init_moveHeadersToQuery();
    init_prepareRequest();
    init_credentialDerivation();
    init_SignatureV4Base();
    init_headerUtil();
    init_signature_v4a_container();
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js
function normalizeCredentialProvider(config, { credentials: credentials2, credentialDefaultProvider }) {
  let credentialsProvider;
  if (credentials2) {
    if (!credentials2?.memoized) {
      credentialsProvider = memoizeIdentityProvider(credentials2, isIdentityExpired, doesIdentityRequireRefresh);
    } else {
      credentialsProvider = credentials2;
    }
  } else {
    if (credentialDefaultProvider) {
      credentialsProvider = normalizeProvider2(credentialDefaultProvider(Object.assign({}, config, {
        parentClientConfig: config
      })));
    } else {
      credentialsProvider = async () => {
        throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.");
      };
    }
  }
  credentialsProvider.memoized = true;
  return credentialsProvider;
}
function bindCallerConfig(config, credentialsProvider) {
  if (credentialsProvider.configBound) {
    return credentialsProvider;
  }
  const fn = async (options) => credentialsProvider({ ...options, callerClientConfig: config });
  fn.memoized = credentialsProvider.memoized;
  fn.configBound = true;
  return fn;
}
var resolveAwsSdkSigV4Config;
var init_resolveAwsSdkSigV4Config = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js"() {
    "use strict";
    init_client2();
    init_dist_es18();
    init_dist_es22();
    resolveAwsSdkSigV4Config = (config) => {
      let inputCredentials = config.credentials;
      let isUserSupplied = !!config.credentials;
      let resolvedCredentials = void 0;
      Object.defineProperty(config, "credentials", {
        set(credentials2) {
          if (credentials2 && credentials2 !== inputCredentials && credentials2 !== resolvedCredentials) {
            isUserSupplied = true;
          }
          inputCredentials = credentials2;
          const memoizedProvider = normalizeCredentialProvider(config, {
            credentials: inputCredentials,
            credentialDefaultProvider: config.credentialDefaultProvider
          });
          const boundProvider = bindCallerConfig(config, memoizedProvider);
          if (isUserSupplied && !boundProvider.attributed) {
            resolvedCredentials = async (options) => boundProvider(options).then((creds) => setCredentialFeature(creds, "CREDENTIALS_CODE", "e"));
            resolvedCredentials.memoized = boundProvider.memoized;
            resolvedCredentials.configBound = boundProvider.configBound;
            resolvedCredentials.attributed = true;
          } else {
            resolvedCredentials = boundProvider;
          }
        },
        get() {
          return resolvedCredentials;
        },
        enumerable: true,
        configurable: true
      });
      config.credentials = inputCredentials;
      const { signingEscapePath = true, systemClockOffset = config.systemClockOffset || 0, sha256: sha2562 } = config;
      let signer;
      if (config.signer) {
        signer = normalizeProvider2(config.signer);
      } else if (config.regionInfoProvider) {
        signer = () => normalizeProvider2(config.region)().then(async (region) => [
          await config.regionInfoProvider(region, {
            useFipsEndpoint: await config.useFipsEndpoint(),
            useDualstackEndpoint: await config.useDualstackEndpoint()
          }) || {},
          region
        ]).then(([regionInfo, region]) => {
          const { signingRegion, signingService } = regionInfo;
          config.signingRegion = config.signingRegion || signingRegion || region;
          config.signingName = config.signingName || signingService || config.serviceId;
          const params = {
            ...config,
            credentials: config.credentials,
            region: config.signingRegion,
            service: config.signingName,
            sha256: sha2562,
            uriEscapePath: signingEscapePath
          };
          const SignerCtor = config.signerConstructor || SignatureV4;
          return new SignerCtor(params);
        });
      } else {
        signer = async (authScheme) => {
          authScheme = Object.assign({}, {
            name: "sigv4",
            signingName: config.signingName || config.defaultSigningName,
            signingRegion: await normalizeProvider2(config.region)(),
            properties: {}
          }, authScheme);
          const signingRegion = authScheme.signingRegion;
          const signingService = authScheme.signingName;
          config.signingRegion = config.signingRegion || signingRegion;
          config.signingName = config.signingName || signingService || config.serviceId;
          const params = {
            ...config,
            credentials: config.credentials,
            region: config.signingRegion,
            service: config.signingName,
            sha256: sha2562,
            uriEscapePath: signingEscapePath
          };
          const SignerCtor = config.signerConstructor || SignatureV4;
          return new SignerCtor(params);
        };
      }
      const resolvedConfig = Object.assign(config, {
        systemClockOffset,
        signingEscapePath,
        signer
      });
      return resolvedConfig;
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js
var init_aws_sdk = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js"() {
    "use strict";
    init_AwsSdkSigV4Signer();
    init_NODE_AUTH_SCHEME_PREFERENCE_OPTIONS();
    init_resolveAwsSdkSigV4AConfig();
    init_resolveAwsSdkSigV4Config();
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js
var init_httpAuthSchemes2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js"() {
    "use strict";
    init_aws_sdk();
    init_getBearerTokenEnvKey();
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js
var init_coercing_serializers = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+middleware-stack@4.0.4/node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js
var getAllAliases, getMiddlewareNameWithAliases, constructStack, stepWeights, priorityWeights;
var init_MiddlewareStack = __esm({
  "../node_modules/.pnpm/@smithy+middleware-stack@4.0.4/node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js"() {
    "use strict";
    getAllAliases = (name, aliases) => {
      const _aliases = [];
      if (name) {
        _aliases.push(name);
      }
      if (aliases) {
        for (const alias of aliases) {
          _aliases.push(alias);
        }
      }
      return _aliases;
    };
    getMiddlewareNameWithAliases = (name, aliases) => {
      return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`;
    };
    constructStack = () => {
      let absoluteEntries = [];
      let relativeEntries = [];
      let identifyOnResolve = false;
      const entriesNameSet = /* @__PURE__ */ new Set();
      const sort = (entries) => entries.sort((a5, b5) => stepWeights[b5.step] - stepWeights[a5.step] || priorityWeights[b5.priority || "normal"] - priorityWeights[a5.priority || "normal"]);
      const removeByName = (toRemove) => {
        let isRemoved = false;
        const filterCb = (entry) => {
          const aliases = getAllAliases(entry.name, entry.aliases);
          if (aliases.includes(toRemove)) {
            isRemoved = true;
            for (const alias of aliases) {
              entriesNameSet.delete(alias);
            }
            return false;
          }
          return true;
        };
        absoluteEntries = absoluteEntries.filter(filterCb);
        relativeEntries = relativeEntries.filter(filterCb);
        return isRemoved;
      };
      const removeByReference = (toRemove) => {
        let isRemoved = false;
        const filterCb = (entry) => {
          if (entry.middleware === toRemove) {
            isRemoved = true;
            for (const alias of getAllAliases(entry.name, entry.aliases)) {
              entriesNameSet.delete(alias);
            }
            return false;
          }
          return true;
        };
        absoluteEntries = absoluteEntries.filter(filterCb);
        relativeEntries = relativeEntries.filter(filterCb);
        return isRemoved;
      };
      const cloneTo = (toStack) => {
        absoluteEntries.forEach((entry) => {
          toStack.add(entry.middleware, { ...entry });
        });
        relativeEntries.forEach((entry) => {
          toStack.addRelativeTo(entry.middleware, { ...entry });
        });
        toStack.identifyOnResolve?.(stack.identifyOnResolve());
        return toStack;
      };
      const expandRelativeMiddlewareList = (from) => {
        const expandedMiddlewareList = [];
        from.before.forEach((entry) => {
          if (entry.before.length === 0 && entry.after.length === 0) {
            expandedMiddlewareList.push(entry);
          } else {
            expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry));
          }
        });
        expandedMiddlewareList.push(from);
        from.after.reverse().forEach((entry) => {
          if (entry.before.length === 0 && entry.after.length === 0) {
            expandedMiddlewareList.push(entry);
          } else {
            expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry));
          }
        });
        return expandedMiddlewareList;
      };
      const getMiddlewareList = (debug = false) => {
        const normalizedAbsoluteEntries = [];
        const normalizedRelativeEntries = [];
        const normalizedEntriesNameMap = {};
        absoluteEntries.forEach((entry) => {
          const normalizedEntry = {
            ...entry,
            before: [],
            after: []
          };
          for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) {
            normalizedEntriesNameMap[alias] = normalizedEntry;
          }
          normalizedAbsoluteEntries.push(normalizedEntry);
        });
        relativeEntries.forEach((entry) => {
          const normalizedEntry = {
            ...entry,
            before: [],
            after: []
          };
          for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) {
            normalizedEntriesNameMap[alias] = normalizedEntry;
          }
          normalizedRelativeEntries.push(normalizedEntry);
        });
        normalizedRelativeEntries.forEach((entry) => {
          if (entry.toMiddleware) {
            const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware];
            if (toMiddleware === void 0) {
              if (debug) {
                return;
              }
              throw new Error(`${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name, entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}`);
            }
            if (entry.relation === "after") {
              toMiddleware.after.push(entry);
            }
            if (entry.relation === "before") {
              toMiddleware.before.push(entry);
            }
          }
        });
        const mainChain = sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce((wholeList, expandedMiddlewareList) => {
          wholeList.push(...expandedMiddlewareList);
          return wholeList;
        }, []);
        return mainChain;
      };
      const stack = {
        add: (middleware, options = {}) => {
          const { name, override, aliases: _aliases } = options;
          const entry = {
            step: "initialize",
            priority: "normal",
            middleware,
            ...options
          };
          const aliases = getAllAliases(name, _aliases);
          if (aliases.length > 0) {
            if (aliases.some((alias) => entriesNameSet.has(alias))) {
              if (!override)
                throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`);
              for (const alias of aliases) {
                const toOverrideIndex = absoluteEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a5) => a5 === alias));
                if (toOverrideIndex === -1) {
                  continue;
                }
                const toOverride = absoluteEntries[toOverrideIndex];
                if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) {
                  throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.`);
                }
                absoluteEntries.splice(toOverrideIndex, 1);
              }
            }
            for (const alias of aliases) {
              entriesNameSet.add(alias);
            }
          }
          absoluteEntries.push(entry);
        },
        addRelativeTo: (middleware, options) => {
          const { name, override, aliases: _aliases } = options;
          const entry = {
            middleware,
            ...options
          };
          const aliases = getAllAliases(name, _aliases);
          if (aliases.length > 0) {
            if (aliases.some((alias) => entriesNameSet.has(alias))) {
              if (!override)
                throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`);
              for (const alias of aliases) {
                const toOverrideIndex = relativeEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a5) => a5 === alias));
                if (toOverrideIndex === -1) {
                  continue;
                }
                const toOverride = relativeEntries[toOverrideIndex];
                if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) {
                  throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.`);
                }
                relativeEntries.splice(toOverrideIndex, 1);
              }
            }
            for (const alias of aliases) {
              entriesNameSet.add(alias);
            }
          }
          relativeEntries.push(entry);
        },
        clone: () => cloneTo(constructStack()),
        use: (plugin) => {
          plugin.applyToStack(stack);
        },
        remove: (toRemove) => {
          if (typeof toRemove === "string")
            return removeByName(toRemove);
          else
            return removeByReference(toRemove);
        },
        removeByTag: (toRemove) => {
          let isRemoved = false;
          const filterCb = (entry) => {
            const { tags, name, aliases: _aliases } = entry;
            if (tags && tags.includes(toRemove)) {
              const aliases = getAllAliases(name, _aliases);
              for (const alias of aliases) {
                entriesNameSet.delete(alias);
              }
              isRemoved = true;
              return false;
            }
            return true;
          };
          absoluteEntries = absoluteEntries.filter(filterCb);
          relativeEntries = relativeEntries.filter(filterCb);
          return isRemoved;
        },
        concat: (from) => {
          const cloned = cloneTo(constructStack());
          cloned.use(from);
          cloned.identifyOnResolve(identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false));
          return cloned;
        },
        applyToStack: cloneTo,
        identify: () => {
          return getMiddlewareList(true).map((mw) => {
            const step = mw.step ?? mw.relation + " " + mw.toMiddleware;
            return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step;
          });
        },
        identifyOnResolve(toggle) {
          if (typeof toggle === "boolean")
            identifyOnResolve = toggle;
          return identifyOnResolve;
        },
        resolve: (handler, context) => {
          for (const middleware of getMiddlewareList().map((entry) => entry.middleware).reverse()) {
            handler = middleware(handler, context);
          }
          if (identifyOnResolve) {
            console.log(stack.identify());
          }
          return handler;
        }
      };
      return stack;
    };
    stepWeights = {
      initialize: 5,
      serialize: 4,
      build: 3,
      finalizeRequest: 2,
      deserialize: 1
    };
    priorityWeights = {
      high: 3,
      normal: 2,
      low: 1
    };
  }
});

// ../node_modules/.pnpm/@smithy+middleware-stack@4.0.4/node_modules/@smithy/middleware-stack/dist-es/index.js
var init_dist_es23 = __esm({
  "../node_modules/.pnpm/@smithy+middleware-stack@4.0.4/node_modules/@smithy/middleware-stack/dist-es/index.js"() {
    "use strict";
    init_MiddlewareStack();
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/client.js
var Client;
var init_client3 = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/client.js"() {
    "use strict";
    init_dist_es23();
    Client = class {
      constructor(config) {
        this.config = config;
        this.middlewareStack = constructStack();
      }
      send(command, optionsOrCb, cb) {
        const options = typeof optionsOrCb !== "function" ? optionsOrCb : void 0;
        const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb;
        const useHandlerCache = options === void 0 && this.config.cacheMiddleware === true;
        let handler;
        if (useHandlerCache) {
          if (!this.handlers) {
            this.handlers = /* @__PURE__ */ new WeakMap();
          }
          const handlers = this.handlers;
          if (handlers.has(command.constructor)) {
            handler = handlers.get(command.constructor);
          } else {
            handler = command.resolveMiddleware(this.middlewareStack, this.config, options);
            handlers.set(command.constructor, handler);
          }
        } else {
          delete this.handlers;
          handler = command.resolveMiddleware(this.middlewareStack, this.config, options);
        }
        if (callback) {
          handler(command).then((result) => callback(null, result.output), (err2) => callback(err2)).catch(() => {
          });
        } else {
          return handler(command).then((result) => result.output);
        }
      }
      destroy() {
        this.config?.requestHandler?.destroy?.();
        delete this.handlers;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/collect-stream-body.js
var init_collect_stream_body2 = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/collect-stream-body.js"() {
    "use strict";
    init_protocols();
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/command.js
var Command, ClassBuilder;
var init_command2 = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/command.js"() {
    "use strict";
    init_dist_es23();
    init_dist_es();
    Command = class {
      constructor() {
        this.middlewareStack = constructStack();
      }
      static classBuilder() {
        return new ClassBuilder();
      }
      resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor }) {
        for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) {
          this.middlewareStack.use(mw);
        }
        const stack = clientStack.concat(this.middlewareStack);
        const { logger: logger2 } = configuration;
        const handlerExecutionContext = {
          logger: logger2,
          clientName,
          commandName,
          inputFilterSensitiveLog,
          outputFilterSensitiveLog,
          [SMITHY_CONTEXT_KEY]: {
            commandInstance: this,
            ...smithyContext
          },
          ...additionalContext
        };
        const { requestHandler } = configuration;
        return stack.resolve((request2) => requestHandler.handle(request2.request, options || {}), handlerExecutionContext);
      }
    };
    ClassBuilder = class {
      constructor() {
        this._init = () => {
        };
        this._ep = {};
        this._middlewareFn = () => [];
        this._commandName = "";
        this._clientName = "";
        this._additionalContext = {};
        this._smithyContext = {};
        this._inputFilterSensitiveLog = (_3) => _3;
        this._outputFilterSensitiveLog = (_3) => _3;
        this._serializer = null;
        this._deserializer = null;
      }
      init(cb) {
        this._init = cb;
      }
      ep(endpointParameterInstructions) {
        this._ep = endpointParameterInstructions;
        return this;
      }
      m(middlewareSupplier) {
        this._middlewareFn = middlewareSupplier;
        return this;
      }
      s(service, operation, smithyContext = {}) {
        this._smithyContext = {
          service,
          operation,
          ...smithyContext
        };
        return this;
      }
      c(additionalContext = {}) {
        this._additionalContext = additionalContext;
        return this;
      }
      n(clientName, commandName) {
        this._clientName = clientName;
        this._commandName = commandName;
        return this;
      }
      f(inputFilter = (_3) => _3, outputFilter = (_3) => _3) {
        this._inputFilterSensitiveLog = inputFilter;
        this._outputFilterSensitiveLog = outputFilter;
        return this;
      }
      ser(serializer) {
        this._serializer = serializer;
        return this;
      }
      de(deserializer) {
        this._deserializer = deserializer;
        return this;
      }
      sc(operation) {
        this._operationSchema = operation;
        this._smithyContext.operationSchema = operation;
        return this;
      }
      build() {
        const closure = this;
        let CommandRef;
        return CommandRef = class extends Command {
          static getEndpointParameterInstructions() {
            return closure._ep;
          }
          constructor(...[input]) {
            super();
            this.serialize = closure._serializer;
            this.deserialize = closure._deserializer;
            this.input = input ?? {};
            closure._init(this);
            this.schema = closure._operationSchema;
          }
          resolveMiddleware(stack, configuration, options) {
            return this.resolveMiddlewareWithContext(stack, configuration, options, {
              CommandCtor: CommandRef,
              middlewareFn: closure._middlewareFn,
              clientName: closure._clientName,
              commandName: closure._commandName,
              inputFilterSensitiveLog: closure._inputFilterSensitiveLog,
              outputFilterSensitiveLog: closure._outputFilterSensitiveLog,
              smithyContext: closure._smithyContext,
              additionalContext: closure._additionalContext
            });
          }
        };
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/constants.js
var SENSITIVE_STRING;
var init_constants4 = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/constants.js"() {
    "use strict";
    SENSITIVE_STRING = "***SensitiveInformation***";
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/create-aggregated-client.js
var createAggregatedClient;
var init_create_aggregated_client = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/create-aggregated-client.js"() {
    "use strict";
    createAggregatedClient = (commands5, Client2) => {
      for (const command of Object.keys(commands5)) {
        const CommandCtor = commands5[command];
        const methodImpl = async function(args, optionsOrCb, cb) {
          const command2 = new CommandCtor(args);
          if (typeof optionsOrCb === "function") {
            this.send(command2, optionsOrCb);
          } else if (typeof cb === "function") {
            if (typeof optionsOrCb !== "object")
              throw new Error(`Expected http options but got ${typeof optionsOrCb}`);
            this.send(command2, optionsOrCb || {}, cb);
          } else {
            return this.send(command2, optionsOrCb);
          }
        };
        const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, "");
        Client2.prototype[methodName] = methodImpl;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/exceptions.js
var ServiceException, decorateServiceException;
var init_exceptions = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/exceptions.js"() {
    "use strict";
    ServiceException = class _ServiceException extends Error {
      constructor(options) {
        super(options.message);
        Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype);
        this.name = options.name;
        this.$fault = options.$fault;
        this.$metadata = options.$metadata;
      }
      static isInstance(value) {
        if (!value)
          return false;
        const candidate = value;
        return _ServiceException.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server");
      }
      static [Symbol.hasInstance](instance) {
        if (!instance)
          return false;
        const candidate = instance;
        if (this === _ServiceException) {
          return _ServiceException.isInstance(instance);
        }
        if (_ServiceException.isInstance(instance)) {
          if (candidate.name && this.name) {
            return this.prototype.isPrototypeOf(instance) || candidate.name === this.name;
          }
          return this.prototype.isPrototypeOf(instance);
        }
        return false;
      }
    };
    decorateServiceException = (exception, additions = {}) => {
      Object.entries(additions).filter(([, v6]) => v6 !== void 0).forEach(([k5, v6]) => {
        if (exception[k5] == void 0 || exception[k5] === "") {
          exception[k5] = v6;
        }
      });
      const message = exception.message || exception.Message || "UnknownError";
      exception.message = message;
      delete exception.Message;
      return exception;
    };
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/default-error-handler.js
var throwDefaultError, withBaseException, deserializeMetadata;
var init_default_error_handler = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/default-error-handler.js"() {
    "use strict";
    init_exceptions();
    throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => {
      const $metadata = deserializeMetadata(output);
      const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : void 0;
      const response = new exceptionCtor({
        name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError",
        $fault: "client",
        $metadata
      });
      throw decorateServiceException(response, parsedBody);
    };
    withBaseException = (ExceptionCtor) => {
      return ({ output, parsedBody, errorCode }) => {
        throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode });
      };
    };
    deserializeMetadata = (output) => ({
      httpStatusCode: output.statusCode,
      requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
      extendedRequestId: output.headers["x-amz-id-2"],
      cfId: output.headers["x-amz-cf-id"]
    });
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/defaults-mode.js
var loadConfigsForDefaultMode;
var init_defaults_mode = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/defaults-mode.js"() {
    "use strict";
    loadConfigsForDefaultMode = (mode) => {
      switch (mode) {
        case "standard":
          return {
            retryMode: "standard",
            connectionTimeout: 3100
          };
        case "in-region":
          return {
            retryMode: "standard",
            connectionTimeout: 1100
          };
        case "cross-region":
          return {
            retryMode: "standard",
            connectionTimeout: 3100
          };
        case "mobile":
          return {
            retryMode: "standard",
            connectionTimeout: 3e4
          };
        default:
          return {};
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/emitWarningIfUnsupportedVersion.js
var warningEmitted, emitWarningIfUnsupportedVersion2;
var init_emitWarningIfUnsupportedVersion2 = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/emitWarningIfUnsupportedVersion.js"() {
    "use strict";
    warningEmitted = false;
    emitWarningIfUnsupportedVersion2 = (version) => {
      if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) {
        warningEmitted = true;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extended-encode-uri-component.js
var init_extended_encode_uri_component2 = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extended-encode-uri-component.js"() {
    "use strict";
    init_protocols();
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js
var getChecksumConfiguration2, resolveChecksumRuntimeConfig2;
var init_checksum3 = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js"() {
    "use strict";
    init_dist_es();
    getChecksumConfiguration2 = (runtimeConfig) => {
      const checksumAlgorithms = [];
      for (const id in AlgorithmId) {
        const algorithmId = AlgorithmId[id];
        if (runtimeConfig[algorithmId] === void 0) {
          continue;
        }
        checksumAlgorithms.push({
          algorithmId: () => algorithmId,
          checksumConstructor: () => runtimeConfig[algorithmId]
        });
      }
      return {
        addChecksumAlgorithm(algo) {
          checksumAlgorithms.push(algo);
        },
        checksumAlgorithms() {
          return checksumAlgorithms;
        }
      };
    };
    resolveChecksumRuntimeConfig2 = (clientConfig) => {
      const runtimeConfig = {};
      clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
        runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
      });
      return runtimeConfig;
    };
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/retry.js
var getRetryConfiguration, resolveRetryRuntimeConfig;
var init_retry2 = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/retry.js"() {
    "use strict";
    getRetryConfiguration = (runtimeConfig) => {
      return {
        setRetryStrategy(retryStrategy) {
          runtimeConfig.retryStrategy = retryStrategy;
        },
        retryStrategy() {
          return runtimeConfig.retryStrategy;
        }
      };
    };
    resolveRetryRuntimeConfig = (retryStrategyConfiguration) => {
      const runtimeConfig = {};
      runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy();
      return runtimeConfig;
    };
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js
var getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig;
var init_defaultExtensionConfiguration2 = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js"() {
    "use strict";
    init_checksum3();
    init_retry2();
    getDefaultExtensionConfiguration = (runtimeConfig) => {
      return Object.assign(getChecksumConfiguration2(runtimeConfig), getRetryConfiguration(runtimeConfig));
    };
    resolveDefaultRuntimeConfig = (config) => {
      return Object.assign(resolveChecksumRuntimeConfig2(config), resolveRetryRuntimeConfig(config));
    };
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/index.js
var init_extensions3 = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/index.js"() {
    "use strict";
    init_defaultExtensionConfiguration2();
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/get-array-if-single-item.js
var init_get_array_if_single_item = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/get-array-if-single-item.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/get-value-from-text-node.js
var getValueFromTextNode;
var init_get_value_from_text_node = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/get-value-from-text-node.js"() {
    "use strict";
    getValueFromTextNode = (obj) => {
      const textNodeName = "#text";
      for (const key in obj) {
        if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== void 0) {
          obj[key] = obj[key][textNodeName];
        } else if (typeof obj[key] === "object" && obj[key] !== null) {
          obj[key] = getValueFromTextNode(obj[key]);
        }
      }
      return obj;
    };
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/is-serializable-header-value.js
var isSerializableHeaderValue;
var init_is_serializable_header_value = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/is-serializable-header-value.js"() {
    "use strict";
    isSerializableHeaderValue = (value) => {
      return value != null;
    };
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js
var NoOpLogger;
var init_NoOpLogger = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js"() {
    "use strict";
    NoOpLogger = class {
      trace() {
      }
      debug() {
      }
      info() {
      }
      warn() {
      }
      error() {
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/object-mapping.js
function map(arg0, arg1, arg2) {
  let target;
  let filter2;
  let instructions;
  if (typeof arg1 === "undefined" && typeof arg2 === "undefined") {
    target = {};
    instructions = arg0;
  } else {
    target = arg0;
    if (typeof arg1 === "function") {
      filter2 = arg1;
      instructions = arg2;
      return mapWithFilter(target, filter2, instructions);
    } else {
      instructions = arg1;
    }
  }
  for (const key of Object.keys(instructions)) {
    if (!Array.isArray(instructions[key])) {
      target[key] = instructions[key];
      continue;
    }
    applyInstruction(target, null, instructions, key);
  }
  return target;
}
var take, mapWithFilter, applyInstruction, nonNullish, pass;
var init_object_mapping = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/object-mapping.js"() {
    "use strict";
    take = (source, instructions) => {
      const out = {};
      for (const key in instructions) {
        applyInstruction(out, source, instructions, key);
      }
      return out;
    };
    mapWithFilter = (target, filter2, instructions) => {
      return map(target, Object.entries(instructions).reduce((_instructions, [key, value]) => {
        if (Array.isArray(value)) {
          _instructions[key] = value;
        } else {
          if (typeof value === "function") {
            _instructions[key] = [filter2, value()];
          } else {
            _instructions[key] = [filter2, value];
          }
        }
        return _instructions;
      }, {}));
    };
    applyInstruction = (target, source, instructions, targetKey) => {
      if (source !== null) {
        let instruction = instructions[targetKey];
        if (typeof instruction === "function") {
          instruction = [, instruction];
        }
        const [filter3 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction;
        if (typeof filter3 === "function" && filter3(source[sourceKey]) || typeof filter3 !== "function" && !!filter3) {
          target[targetKey] = valueFn(source[sourceKey]);
        }
        return;
      }
      let [filter2, value] = instructions[targetKey];
      if (typeof value === "function") {
        let _value;
        const defaultFilterPassed = filter2 === void 0 && (_value = value()) != null;
        const customFilterPassed = typeof filter2 === "function" && !!filter2(void 0) || typeof filter2 !== "function" && !!filter2;
        if (defaultFilterPassed) {
          target[targetKey] = _value;
        } else if (customFilterPassed) {
          target[targetKey] = value();
        }
      } else {
        const defaultFilterPassed = filter2 === void 0 && value != null;
        const customFilterPassed = typeof filter2 === "function" && !!filter2(value) || typeof filter2 !== "function" && !!filter2;
        if (defaultFilterPassed || customFilterPassed) {
          target[targetKey] = value;
        }
      }
    };
    nonNullish = (_3) => _3 != null;
    pass = (_3) => _3;
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/resolve-path.js
var init_resolve_path2 = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/resolve-path.js"() {
    "use strict";
    init_protocols();
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/ser-utils.js
var serializeFloat;
var init_ser_utils = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/ser-utils.js"() {
    "use strict";
    serializeFloat = (value) => {
      if (value !== value) {
        return "NaN";
      }
      switch (value) {
        case Infinity:
          return "Infinity";
        case -Infinity:
          return "-Infinity";
        default:
          return value;
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/serde-json.js
var _json;
var init_serde_json = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/serde-json.js"() {
    "use strict";
    _json = (obj) => {
      if (obj == null) {
        return {};
      }
      if (Array.isArray(obj)) {
        return obj.filter((_3) => _3 != null).map(_json);
      }
      if (typeof obj === "object") {
        const target = {};
        for (const key of Object.keys(obj)) {
          if (obj[key] == null) {
            continue;
          }
          target[key] = _json(obj[key]);
        }
        return target;
      }
      return obj;
    };
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/index.js
var init_dist_es24 = __esm({
  "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/index.js"() {
    "use strict";
    init_client3();
    init_collect_stream_body2();
    init_command2();
    init_constants4();
    init_create_aggregated_client();
    init_default_error_handler();
    init_defaults_mode();
    init_emitWarningIfUnsupportedVersion2();
    init_exceptions();
    init_extended_encode_uri_component2();
    init_extensions3();
    init_get_array_if_single_item();
    init_get_value_from_text_node();
    init_is_serializable_header_value();
    init_NoOpLogger();
    init_object_mapping();
    init_resolve_path2();
    init_ser_utils();
    init_serde_json();
    init_serde2();
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js
var awsExpectUnion;
var init_awsExpectUnion = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js"() {
    "use strict";
    init_dist_es24();
    awsExpectUnion = (value) => {
      if (value == null) {
        return void 0;
      }
      if (typeof value === "object" && "__type" in value) {
        delete value.__type;
      }
      return expectUnion(value);
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js
var collectBodyString;
var init_common2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js"() {
    "use strict";
    init_dist_es24();
    collectBodyString = (streamBody, context) => collectBody(streamBody, context).then((body) => context.utf8Encoder(body));
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js
var parseJsonBody, parseJsonErrorBody, loadRestJsonErrorCode;
var init_parseJsonBody = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js"() {
    "use strict";
    init_common2();
    parseJsonBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => {
      if (encoded.length) {
        try {
          return JSON.parse(encoded);
        } catch (e6) {
          if (e6?.name === "SyntaxError") {
            Object.defineProperty(e6, "$responseBodyText", {
              value: encoded
            });
          }
          throw e6;
        }
      }
      return {};
    });
    parseJsonErrorBody = async (errorBody, context) => {
      const value = await parseJsonBody(errorBody, context);
      value.message = value.message ?? value.Message;
      return value;
    };
    loadRestJsonErrorCode = (output, data) => {
      const findKey = (object, key) => Object.keys(object).find((k5) => k5.toLowerCase() === key.toLowerCase());
      const sanitizeErrorCode = (rawValue) => {
        let cleanValue = rawValue;
        if (typeof cleanValue === "number") {
          cleanValue = cleanValue.toString();
        }
        if (cleanValue.indexOf(",") >= 0) {
          cleanValue = cleanValue.split(",")[0];
        }
        if (cleanValue.indexOf(":") >= 0) {
          cleanValue = cleanValue.split(":")[0];
        }
        if (cleanValue.indexOf("#") >= 0) {
          cleanValue = cleanValue.split("#")[1];
        }
        return cleanValue;
      };
      const headerKey = findKey(output.headers, "x-amzn-errortype");
      if (headerKey !== void 0) {
        return sanitizeErrorCode(output.headers[headerKey]);
      }
      if (data && typeof data === "object") {
        const codeKey = findKey(data, "code");
        if (codeKey && data[codeKey] !== void 0) {
          return sanitizeErrorCode(data[codeKey]);
        }
        if (data["__type"] !== void 0) {
          return sanitizeErrorCode(data["__type"]);
        }
      }
    };
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/util.js
var require_util2 = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/util.js"(exports2) {
    "use strict";
    var nameStartChar = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
    var nameChar = nameStartChar + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
    var nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*";
    var regexName = new RegExp("^" + nameRegexp + "$");
    var getAllMatches = function(string, regex) {
      const matches = [];
      let match2 = regex.exec(string);
      while (match2) {
        const allmatches = [];
        allmatches.startIndex = regex.lastIndex - match2[0].length;
        const len = match2.length;
        for (let index6 = 0; index6 < len; index6++) {
          allmatches.push(match2[index6]);
        }
        matches.push(allmatches);
        match2 = regex.exec(string);
      }
      return matches;
    };
    var isName = function(string) {
      const match2 = regexName.exec(string);
      return !(match2 === null || typeof match2 === "undefined");
    };
    exports2.isExist = function(v6) {
      return typeof v6 !== "undefined";
    };
    exports2.isEmptyObject = function(obj) {
      return Object.keys(obj).length === 0;
    };
    exports2.merge = function(target, a5, arrayMode) {
      if (a5) {
        const keys = Object.keys(a5);
        const len = keys.length;
        for (let i6 = 0; i6 < len; i6++) {
          if (arrayMode === "strict") {
            target[keys[i6]] = [a5[keys[i6]]];
          } else {
            target[keys[i6]] = a5[keys[i6]];
          }
        }
      }
    };
    exports2.getValue = function(v6) {
      if (exports2.isExist(v6)) {
        return v6;
      } else {
        return "";
      }
    };
    exports2.isName = isName;
    exports2.getAllMatches = getAllMatches;
    exports2.nameRegexp = nameRegexp;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/validator.js
var require_validator = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/validator.js"(exports2) {
    "use strict";
    var util2 = require_util2();
    var defaultOptions = {
      allowBooleanAttributes: false,
      //A tag can have attributes without any value
      unpairedTags: []
    };
    exports2.validate = function(xmlData, options) {
      options = Object.assign({}, defaultOptions, options);
      const tags = [];
      let tagFound = false;
      let reachedRoot = false;
      if (xmlData[0] === "\uFEFF") {
        xmlData = xmlData.substr(1);
      }
      for (let i6 = 0; i6 < xmlData.length; i6++) {
        if (xmlData[i6] === "<" && xmlData[i6 + 1] === "?") {
          i6 += 2;
          i6 = readPI(xmlData, i6);
          if (i6.err) return i6;
        } else if (xmlData[i6] === "<") {
          let tagStartPos = i6;
          i6++;
          if (xmlData[i6] === "!") {
            i6 = readCommentAndCDATA(xmlData, i6);
            continue;
          } else {
            let closingTag = false;
            if (xmlData[i6] === "/") {
              closingTag = true;
              i6++;
            }
            let tagName = "";
            for (; i6 < xmlData.length && xmlData[i6] !== ">" && xmlData[i6] !== " " && xmlData[i6] !== "	" && xmlData[i6] !== "\n" && xmlData[i6] !== "\r"; i6++) {
              tagName += xmlData[i6];
            }
            tagName = tagName.trim();
            if (tagName[tagName.length - 1] === "/") {
              tagName = tagName.substring(0, tagName.length - 1);
              i6--;
            }
            if (!validateTagName(tagName)) {
              let msg;
              if (tagName.trim().length === 0) {
                msg = "Invalid space after '<'.";
              } else {
                msg = "Tag '" + tagName + "' is an invalid name.";
              }
              return getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i6));
            }
            const result = readAttributeStr(xmlData, i6);
            if (result === false) {
              return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i6));
            }
            let attrStr = result.value;
            i6 = result.index;
            if (attrStr[attrStr.length - 1] === "/") {
              const attrStrStart = i6 - attrStr.length;
              attrStr = attrStr.substring(0, attrStr.length - 1);
              const isValid2 = validateAttributeString(attrStr, options);
              if (isValid2 === true) {
                tagFound = true;
              } else {
                return getErrorObject(isValid2.err.code, isValid2.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid2.err.line));
              }
            } else if (closingTag) {
              if (!result.tagClosed) {
                return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i6));
              } else if (attrStr.trim().length > 0) {
                return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
              } else if (tags.length === 0) {
                return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos));
              } else {
                const otg = tags.pop();
                if (tagName !== otg.tagName) {
                  let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
                  return getErrorObject(
                    "InvalidTag",
                    "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.",
                    getLineNumberForPosition(xmlData, tagStartPos)
                  );
                }
                if (tags.length == 0) {
                  reachedRoot = true;
                }
              }
            } else {
              const isValid2 = validateAttributeString(attrStr, options);
              if (isValid2 !== true) {
                return getErrorObject(isValid2.err.code, isValid2.err.msg, getLineNumberForPosition(xmlData, i6 - attrStr.length + isValid2.err.line));
              }
              if (reachedRoot === true) {
                return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i6));
              } else if (options.unpairedTags.indexOf(tagName) !== -1) {
              } else {
                tags.push({ tagName, tagStartPos });
              }
              tagFound = true;
            }
            for (i6++; i6 < xmlData.length; i6++) {
              if (xmlData[i6] === "<") {
                if (xmlData[i6 + 1] === "!") {
                  i6++;
                  i6 = readCommentAndCDATA(xmlData, i6);
                  continue;
                } else if (xmlData[i6 + 1] === "?") {
                  i6 = readPI(xmlData, ++i6);
                  if (i6.err) return i6;
                } else {
                  break;
                }
              } else if (xmlData[i6] === "&") {
                const afterAmp = validateAmpersand(xmlData, i6);
                if (afterAmp == -1)
                  return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i6));
                i6 = afterAmp;
              } else {
                if (reachedRoot === true && !isWhiteSpace(xmlData[i6])) {
                  return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i6));
                }
              }
            }
            if (xmlData[i6] === "<") {
              i6--;
            }
          }
        } else {
          if (isWhiteSpace(xmlData[i6])) {
            continue;
          }
          return getErrorObject("InvalidChar", "char '" + xmlData[i6] + "' is not expected.", getLineNumberForPosition(xmlData, i6));
        }
      }
      if (!tagFound) {
        return getErrorObject("InvalidXml", "Start tag expected.", 1);
      } else if (tags.length == 1) {
        return getErrorObject("InvalidTag", "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
      } else if (tags.length > 0) {
        return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags.map((t6) => t6.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 });
      }
      return true;
    };
    function isWhiteSpace(char) {
      return char === " " || char === "	" || char === "\n" || char === "\r";
    }
    function readPI(xmlData, i6) {
      const start = i6;
      for (; i6 < xmlData.length; i6++) {
        if (xmlData[i6] == "?" || xmlData[i6] == " ") {
          const tagname = xmlData.substr(start, i6 - start);
          if (i6 > 5 && tagname === "xml") {
            return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i6));
          } else if (xmlData[i6] == "?" && xmlData[i6 + 1] == ">") {
            i6++;
            break;
          } else {
            continue;
          }
        }
      }
      return i6;
    }
    function readCommentAndCDATA(xmlData, i6) {
      if (xmlData.length > i6 + 5 && xmlData[i6 + 1] === "-" && xmlData[i6 + 2] === "-") {
        for (i6 += 3; i6 < xmlData.length; i6++) {
          if (xmlData[i6] === "-" && xmlData[i6 + 1] === "-" && xmlData[i6 + 2] === ">") {
            i6 += 2;
            break;
          }
        }
      } else if (xmlData.length > i6 + 8 && xmlData[i6 + 1] === "D" && xmlData[i6 + 2] === "O" && xmlData[i6 + 3] === "C" && xmlData[i6 + 4] === "T" && xmlData[i6 + 5] === "Y" && xmlData[i6 + 6] === "P" && xmlData[i6 + 7] === "E") {
        let angleBracketsCount = 1;
        for (i6 += 8; i6 < xmlData.length; i6++) {
          if (xmlData[i6] === "<") {
            angleBracketsCount++;
          } else if (xmlData[i6] === ">") {
            angleBracketsCount--;
            if (angleBracketsCount === 0) {
              break;
            }
          }
        }
      } else if (xmlData.length > i6 + 9 && xmlData[i6 + 1] === "[" && xmlData[i6 + 2] === "C" && xmlData[i6 + 3] === "D" && xmlData[i6 + 4] === "A" && xmlData[i6 + 5] === "T" && xmlData[i6 + 6] === "A" && xmlData[i6 + 7] === "[") {
        for (i6 += 8; i6 < xmlData.length; i6++) {
          if (xmlData[i6] === "]" && xmlData[i6 + 1] === "]" && xmlData[i6 + 2] === ">") {
            i6 += 2;
            break;
          }
        }
      }
      return i6;
    }
    var doubleQuote = '"';
    var singleQuote = "'";
    function readAttributeStr(xmlData, i6) {
      let attrStr = "";
      let startChar = "";
      let tagClosed = false;
      for (; i6 < xmlData.length; i6++) {
        if (xmlData[i6] === doubleQuote || xmlData[i6] === singleQuote) {
          if (startChar === "") {
            startChar = xmlData[i6];
          } else if (startChar !== xmlData[i6]) {
          } else {
            startChar = "";
          }
        } else if (xmlData[i6] === ">") {
          if (startChar === "") {
            tagClosed = true;
            break;
          }
        }
        attrStr += xmlData[i6];
      }
      if (startChar !== "") {
        return false;
      }
      return {
        value: attrStr,
        index: i6,
        tagClosed
      };
    }
    var validAttrStrRegxp = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g");
    function validateAttributeString(attrStr, options) {
      const matches = util2.getAllMatches(attrStr, validAttrStrRegxp);
      const attrNames = {};
      for (let i6 = 0; i6 < matches.length; i6++) {
        if (matches[i6][1].length === 0) {
          return getErrorObject("InvalidAttr", "Attribute '" + matches[i6][2] + "' has no space in starting.", getPositionFromMatch(matches[i6]));
        } else if (matches[i6][3] !== void 0 && matches[i6][4] === void 0) {
          return getErrorObject("InvalidAttr", "Attribute '" + matches[i6][2] + "' is without value.", getPositionFromMatch(matches[i6]));
        } else if (matches[i6][3] === void 0 && !options.allowBooleanAttributes) {
          return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i6][2] + "' is not allowed.", getPositionFromMatch(matches[i6]));
        }
        const attrName = matches[i6][2];
        if (!validateAttrName(attrName)) {
          return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i6]));
        }
        if (!attrNames.hasOwnProperty(attrName)) {
          attrNames[attrName] = 1;
        } else {
          return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i6]));
        }
      }
      return true;
    }
    function validateNumberAmpersand(xmlData, i6) {
      let re = /\d/;
      if (xmlData[i6] === "x") {
        i6++;
        re = /[\da-fA-F]/;
      }
      for (; i6 < xmlData.length; i6++) {
        if (xmlData[i6] === ";")
          return i6;
        if (!xmlData[i6].match(re))
          break;
      }
      return -1;
    }
    function validateAmpersand(xmlData, i6) {
      i6++;
      if (xmlData[i6] === ";")
        return -1;
      if (xmlData[i6] === "#") {
        i6++;
        return validateNumberAmpersand(xmlData, i6);
      }
      let count = 0;
      for (; i6 < xmlData.length; i6++, count++) {
        if (xmlData[i6].match(/\w/) && count < 20)
          continue;
        if (xmlData[i6] === ";")
          break;
        return -1;
      }
      return i6;
    }
    function getErrorObject(code, message, lineNumber) {
      return {
        err: {
          code,
          msg: message,
          line: lineNumber.line || lineNumber,
          col: lineNumber.col
        }
      };
    }
    function validateAttrName(attrName) {
      return util2.isName(attrName);
    }
    function validateTagName(tagname) {
      return util2.isName(tagname);
    }
    function getLineNumberForPosition(xmlData, index6) {
      const lines = xmlData.substring(0, index6).split(/\r?\n/);
      return {
        line: lines.length,
        // column number is last line's length + 1, because column numbering starts at 1:
        col: lines[lines.length - 1].length + 1
      };
    }
    function getPositionFromMatch(match2) {
      return match2.startIndex + match2[1].length;
    }
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js
var require_OptionsBuilder = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(exports2) {
    "use strict";
    var defaultOptions = {
      preserveOrder: false,
      attributeNamePrefix: "@_",
      attributesGroupName: false,
      textNodeName: "#text",
      ignoreAttributes: true,
      removeNSPrefix: false,
      // remove NS from tag name or attribute name if true
      allowBooleanAttributes: false,
      //a tag can have attributes without any value
      //ignoreRootElement : false,
      parseTagValue: true,
      parseAttributeValue: false,
      trimValues: true,
      //Trim string values of tag and attributes
      cdataPropName: false,
      numberParseOptions: {
        hex: true,
        leadingZeros: true,
        eNotation: true
      },
      tagValueProcessor: function(tagName, val2) {
        return val2;
      },
      attributeValueProcessor: function(attrName, val2) {
        return val2;
      },
      stopNodes: [],
      //nested tags will not be parsed even for errors
      alwaysCreateTextNode: false,
      isArray: () => false,
      commentPropName: false,
      unpairedTags: [],
      processEntities: true,
      htmlEntities: false,
      ignoreDeclaration: false,
      ignorePiTags: false,
      transformTagName: false,
      transformAttributeName: false,
      updateTag: function(tagName, jPath, attrs) {
        return tagName;
      }
      // skipEmptyListItem: false
    };
    var buildOptions = function(options) {
      return Object.assign({}, defaultOptions, options);
    };
    exports2.buildOptions = buildOptions;
    exports2.defaultOptions = defaultOptions;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js
var require_xmlNode = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(exports2, module2) {
    "use strict";
    var XmlNode = class {
      constructor(tagname) {
        this.tagname = tagname;
        this.child = [];
        this[":@"] = {};
      }
      add(key, val2) {
        if (key === "__proto__") key = "#__proto__";
        this.child.push({ [key]: val2 });
      }
      addChild(node) {
        if (node.tagname === "__proto__") node.tagname = "#__proto__";
        if (node[":@"] && Object.keys(node[":@"]).length > 0) {
          this.child.push({ [node.tagname]: node.child, [":@"]: node[":@"] });
        } else {
          this.child.push({ [node.tagname]: node.child });
        }
      }
    };
    module2.exports = XmlNode;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js
var require_DocTypeReader = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(exports2, module2) {
    "use strict";
    var util2 = require_util2();
    function readDocType(xmlData, i6) {
      const entities = {};
      if (xmlData[i6 + 3] === "O" && xmlData[i6 + 4] === "C" && xmlData[i6 + 5] === "T" && xmlData[i6 + 6] === "Y" && xmlData[i6 + 7] === "P" && xmlData[i6 + 8] === "E") {
        i6 = i6 + 9;
        let angleBracketsCount = 1;
        let hasBody = false, comment = false;
        let exp = "";
        for (; i6 < xmlData.length; i6++) {
          if (xmlData[i6] === "<" && !comment) {
            if (hasBody && isEntity(xmlData, i6)) {
              i6 += 7;
              [entityName, val, i6] = readEntityExp(xmlData, i6 + 1);
              if (val.indexOf("&") === -1)
                entities[validateEntityName(entityName)] = {
                  regx: RegExp(`&${entityName};`, "g"),
                  val
                };
            } else if (hasBody && isElement(xmlData, i6)) i6 += 8;
            else if (hasBody && isAttlist(xmlData, i6)) i6 += 8;
            else if (hasBody && isNotation(xmlData, i6)) i6 += 9;
            else if (isComment) comment = true;
            else throw new Error("Invalid DOCTYPE");
            angleBracketsCount++;
            exp = "";
          } else if (xmlData[i6] === ">") {
            if (comment) {
              if (xmlData[i6 - 1] === "-" && xmlData[i6 - 2] === "-") {
                comment = false;
                angleBracketsCount--;
              }
            } else {
              angleBracketsCount--;
            }
            if (angleBracketsCount === 0) {
              break;
            }
          } else if (xmlData[i6] === "[") {
            hasBody = true;
          } else {
            exp += xmlData[i6];
          }
        }
        if (angleBracketsCount !== 0) {
          throw new Error(`Unclosed DOCTYPE`);
        }
      } else {
        throw new Error(`Invalid Tag instead of DOCTYPE`);
      }
      return { entities, i: i6 };
    }
    function readEntityExp(xmlData, i6) {
      let entityName2 = "";
      for (; i6 < xmlData.length && (xmlData[i6] !== "'" && xmlData[i6] !== '"'); i6++) {
        entityName2 += xmlData[i6];
      }
      entityName2 = entityName2.trim();
      if (entityName2.indexOf(" ") !== -1) throw new Error("External entites are not supported");
      const startChar = xmlData[i6++];
      let val2 = "";
      for (; i6 < xmlData.length && xmlData[i6] !== startChar; i6++) {
        val2 += xmlData[i6];
      }
      return [entityName2, val2, i6];
    }
    function isComment(xmlData, i6) {
      if (xmlData[i6 + 1] === "!" && xmlData[i6 + 2] === "-" && xmlData[i6 + 3] === "-") return true;
      return false;
    }
    function isEntity(xmlData, i6) {
      if (xmlData[i6 + 1] === "!" && xmlData[i6 + 2] === "E" && xmlData[i6 + 3] === "N" && xmlData[i6 + 4] === "T" && xmlData[i6 + 5] === "I" && xmlData[i6 + 6] === "T" && xmlData[i6 + 7] === "Y") return true;
      return false;
    }
    function isElement(xmlData, i6) {
      if (xmlData[i6 + 1] === "!" && xmlData[i6 + 2] === "E" && xmlData[i6 + 3] === "L" && xmlData[i6 + 4] === "E" && xmlData[i6 + 5] === "M" && xmlData[i6 + 6] === "E" && xmlData[i6 + 7] === "N" && xmlData[i6 + 8] === "T") return true;
      return false;
    }
    function isAttlist(xmlData, i6) {
      if (xmlData[i6 + 1] === "!" && xmlData[i6 + 2] === "A" && xmlData[i6 + 3] === "T" && xmlData[i6 + 4] === "T" && xmlData[i6 + 5] === "L" && xmlData[i6 + 6] === "I" && xmlData[i6 + 7] === "S" && xmlData[i6 + 8] === "T") return true;
      return false;
    }
    function isNotation(xmlData, i6) {
      if (xmlData[i6 + 1] === "!" && xmlData[i6 + 2] === "N" && xmlData[i6 + 3] === "O" && xmlData[i6 + 4] === "T" && xmlData[i6 + 5] === "A" && xmlData[i6 + 6] === "T" && xmlData[i6 + 7] === "I" && xmlData[i6 + 8] === "O" && xmlData[i6 + 9] === "N") return true;
      return false;
    }
    function validateEntityName(name) {
      if (util2.isName(name))
        return name;
      else
        throw new Error(`Invalid entity name ${name}`);
    }
    module2.exports = readDocType;
  }
});

// ../node_modules/.pnpm/strnum@1.1.2/node_modules/strnum/strnum.js
var require_strnum = __commonJS({
  "../node_modules/.pnpm/strnum@1.1.2/node_modules/strnum/strnum.js"(exports2, module2) {
    "use strict";
    var hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;
    var numRegex = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/;
    var consider = {
      hex: true,
      // oct: false,
      leadingZeros: true,
      decimalPoint: ".",
      eNotation: true
      //skipLike: /regex/
    };
    function toNumber(str, options = {}) {
      options = Object.assign({}, consider, options);
      if (!str || typeof str !== "string") return str;
      let trimmedStr = str.trim();
      if (options.skipLike !== void 0 && options.skipLike.test(trimmedStr)) return str;
      else if (str === "0") return 0;
      else if (options.hex && hexRegex.test(trimmedStr)) {
        return parse_int(trimmedStr, 16);
      } else if (trimmedStr.search(/[eE]/) !== -1) {
        const notation = trimmedStr.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/);
        if (notation) {
          if (options.leadingZeros) {
            trimmedStr = (notation[1] || "") + notation[3];
          } else {
            if (notation[2] === "0" && notation[3][0] === ".") {
            } else {
              return str;
            }
          }
          return options.eNotation ? Number(trimmedStr) : str;
        } else {
          return str;
        }
      } else {
        const match2 = numRegex.exec(trimmedStr);
        if (match2) {
          const sign = match2[1];
          const leadingZeros = match2[2];
          let numTrimmedByZeros = trimZeros(match2[3]);
          if (!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str;
          else if (!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str;
          else if (options.leadingZeros && leadingZeros === str) return 0;
          else {
            const num = Number(trimmedStr);
            const numStr = "" + num;
            if (numStr.search(/[eE]/) !== -1) {
              if (options.eNotation) return num;
              else return str;
            } else if (trimmedStr.indexOf(".") !== -1) {
              if (numStr === "0" && numTrimmedByZeros === "") return num;
              else if (numStr === numTrimmedByZeros) return num;
              else if (sign && numStr === "-" + numTrimmedByZeros) return num;
              else return str;
            }
            if (leadingZeros) {
              return numTrimmedByZeros === numStr || sign + numTrimmedByZeros === numStr ? num : str;
            } else {
              return trimmedStr === numStr || trimmedStr === sign + numStr ? num : str;
            }
          }
        } else {
          return str;
        }
      }
    }
    function trimZeros(numStr) {
      if (numStr && numStr.indexOf(".") !== -1) {
        numStr = numStr.replace(/0+$/, "");
        if (numStr === ".") numStr = "0";
        else if (numStr[0] === ".") numStr = "0" + numStr;
        else if (numStr[numStr.length - 1] === ".") numStr = numStr.substr(0, numStr.length - 1);
        return numStr;
      }
      return numStr;
    }
    function parse_int(numStr, base) {
      if (parseInt) return parseInt(numStr, base);
      else if (Number.parseInt) return Number.parseInt(numStr, base);
      else if (window && window.parseInt) return window.parseInt(numStr, base);
      else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported");
    }
    module2.exports = toNumber;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js
var require_OrderedObjParser = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(exports2, module2) {
    "use strict";
    var util2 = require_util2();
    var xmlNode = require_xmlNode();
    var readDocType = require_DocTypeReader();
    var toNumber = require_strnum();
    var OrderedObjParser = class {
      constructor(options) {
        this.options = options;
        this.currentNode = null;
        this.tagsNodeStack = [];
        this.docTypeEntities = {};
        this.lastEntities = {
          "apos": { regex: /&(apos|#39|#x27);/g, val: "'" },
          "gt": { regex: /&(gt|#62|#x3E);/g, val: ">" },
          "lt": { regex: /&(lt|#60|#x3C);/g, val: "<" },
          "quot": { regex: /&(quot|#34|#x22);/g, val: '"' }
        };
        this.ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" };
        this.htmlEntities = {
          "space": { regex: /&(nbsp|#160);/g, val: " " },
          // "lt" : { regex: /&(lt|#60);/g, val: "<" },
          // "gt" : { regex: /&(gt|#62);/g, val: ">" },
          // "amp" : { regex: /&(amp|#38);/g, val: "&" },
          // "quot" : { regex: /&(quot|#34);/g, val: "\"" },
          // "apos" : { regex: /&(apos|#39);/g, val: "'" },
          "cent": { regex: /&(cent|#162);/g, val: "\xA2" },
          "pound": { regex: /&(pound|#163);/g, val: "\xA3" },
          "yen": { regex: /&(yen|#165);/g, val: "\xA5" },
          "euro": { regex: /&(euro|#8364);/g, val: "\u20AC" },
          "copyright": { regex: /&(copy|#169);/g, val: "\xA9" },
          "reg": { regex: /&(reg|#174);/g, val: "\xAE" },
          "inr": { regex: /&(inr|#8377);/g, val: "\u20B9" },
          "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_3, str) => String.fromCharCode(Number.parseInt(str, 10)) },
          "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_3, str) => String.fromCharCode(Number.parseInt(str, 16)) }
        };
        this.addExternalEntities = addExternalEntities;
        this.parseXml = parseXml;
        this.parseTextData = parseTextData;
        this.resolveNameSpace = resolveNameSpace;
        this.buildAttributesMap = buildAttributesMap;
        this.isItStopNode = isItStopNode;
        this.replaceEntitiesValue = replaceEntitiesValue;
        this.readStopNodeData = readStopNodeData;
        this.saveTextToParentTag = saveTextToParentTag;
        this.addChild = addChild;
      }
    };
    function addExternalEntities(externalEntities) {
      const entKeys = Object.keys(externalEntities);
      for (let i6 = 0; i6 < entKeys.length; i6++) {
        const ent = entKeys[i6];
        this.lastEntities[ent] = {
          regex: new RegExp("&" + ent + ";", "g"),
          val: externalEntities[ent]
        };
      }
    }
    function parseTextData(val2, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
      if (val2 !== void 0) {
        if (this.options.trimValues && !dontTrim) {
          val2 = val2.trim();
        }
        if (val2.length > 0) {
          if (!escapeEntities) val2 = this.replaceEntitiesValue(val2);
          const newval = this.options.tagValueProcessor(tagName, val2, jPath, hasAttributes, isLeafNode);
          if (newval === null || newval === void 0) {
            return val2;
          } else if (typeof newval !== typeof val2 || newval !== val2) {
            return newval;
          } else if (this.options.trimValues) {
            return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions);
          } else {
            const trimmedVal = val2.trim();
            if (trimmedVal === val2) {
              return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions);
            } else {
              return val2;
            }
          }
        }
      }
    }
    function resolveNameSpace(tagname) {
      if (this.options.removeNSPrefix) {
        const tags = tagname.split(":");
        const prefix2 = tagname.charAt(0) === "/" ? "/" : "";
        if (tags[0] === "xmlns") {
          return "";
        }
        if (tags.length === 2) {
          tagname = prefix2 + tags[1];
        }
      }
      return tagname;
    }
    var attrsRegx = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm");
    function buildAttributesMap(attrStr, jPath, tagName) {
      if (!this.options.ignoreAttributes && typeof attrStr === "string") {
        const matches = util2.getAllMatches(attrStr, attrsRegx);
        const len = matches.length;
        const attrs = {};
        for (let i6 = 0; i6 < len; i6++) {
          const attrName = this.resolveNameSpace(matches[i6][1]);
          let oldVal = matches[i6][4];
          let aName = this.options.attributeNamePrefix + attrName;
          if (attrName.length) {
            if (this.options.transformAttributeName) {
              aName = this.options.transformAttributeName(aName);
            }
            if (aName === "__proto__") aName = "#__proto__";
            if (oldVal !== void 0) {
              if (this.options.trimValues) {
                oldVal = oldVal.trim();
              }
              oldVal = this.replaceEntitiesValue(oldVal);
              const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);
              if (newVal === null || newVal === void 0) {
                attrs[aName] = oldVal;
              } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) {
                attrs[aName] = newVal;
              } else {
                attrs[aName] = parseValue(
                  oldVal,
                  this.options.parseAttributeValue,
                  this.options.numberParseOptions
                );
              }
            } else if (this.options.allowBooleanAttributes) {
              attrs[aName] = true;
            }
          }
        }
        if (!Object.keys(attrs).length) {
          return;
        }
        if (this.options.attributesGroupName) {
          const attrCollection = {};
          attrCollection[this.options.attributesGroupName] = attrs;
          return attrCollection;
        }
        return attrs;
      }
    }
    var parseXml = function(xmlData) {
      xmlData = xmlData.replace(/\r\n?/g, "\n");
      const xmlObj = new xmlNode("!xml");
      let currentNode = xmlObj;
      let textData = "";
      let jPath = "";
      for (let i6 = 0; i6 < xmlData.length; i6++) {
        const ch = xmlData[i6];
        if (ch === "<") {
          if (xmlData[i6 + 1] === "/") {
            const closeIndex = findClosingIndex(xmlData, ">", i6, "Closing Tag is not closed.");
            let tagName = xmlData.substring(i6 + 2, closeIndex).trim();
            if (this.options.removeNSPrefix) {
              const colonIndex = tagName.indexOf(":");
              if (colonIndex !== -1) {
                tagName = tagName.substr(colonIndex + 1);
              }
            }
            if (this.options.transformTagName) {
              tagName = this.options.transformTagName(tagName);
            }
            if (currentNode) {
              textData = this.saveTextToParentTag(textData, currentNode, jPath);
            }
            const lastTagName = jPath.substring(jPath.lastIndexOf(".") + 1);
            if (tagName && this.options.unpairedTags.indexOf(tagName) !== -1) {
              throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);
            }
            let propIndex = 0;
            if (lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1) {
              propIndex = jPath.lastIndexOf(".", jPath.lastIndexOf(".") - 1);
              this.tagsNodeStack.pop();
            } else {
              propIndex = jPath.lastIndexOf(".");
            }
            jPath = jPath.substring(0, propIndex);
            currentNode = this.tagsNodeStack.pop();
            textData = "";
            i6 = closeIndex;
          } else if (xmlData[i6 + 1] === "?") {
            let tagData = readTagExp(xmlData, i6, false, "?>");
            if (!tagData) throw new Error("Pi Tag is not closed.");
            textData = this.saveTextToParentTag(textData, currentNode, jPath);
            if (this.options.ignoreDeclaration && tagData.tagName === "?xml" || this.options.ignorePiTags) {
            } else {
              const childNode = new xmlNode(tagData.tagName);
              childNode.add(this.options.textNodeName, "");
              if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent) {
                childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName);
              }
              this.addChild(currentNode, childNode, jPath);
            }
            i6 = tagData.closeIndex + 1;
          } else if (xmlData.substr(i6 + 1, 3) === "!--") {
            const endIndex = findClosingIndex(xmlData, "-->", i6 + 4, "Comment is not closed.");
            if (this.options.commentPropName) {
              const comment = xmlData.substring(i6 + 4, endIndex - 2);
              textData = this.saveTextToParentTag(textData, currentNode, jPath);
              currentNode.add(this.options.commentPropName, [{ [this.options.textNodeName]: comment }]);
            }
            i6 = endIndex;
          } else if (xmlData.substr(i6 + 1, 2) === "!D") {
            const result = readDocType(xmlData, i6);
            this.docTypeEntities = result.entities;
            i6 = result.i;
          } else if (xmlData.substr(i6 + 1, 2) === "![") {
            const closeIndex = findClosingIndex(xmlData, "]]>", i6, "CDATA is not closed.") - 2;
            const tagExp = xmlData.substring(i6 + 9, closeIndex);
            textData = this.saveTextToParentTag(textData, currentNode, jPath);
            let val2 = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true);
            if (val2 == void 0) val2 = "";
            if (this.options.cdataPropName) {
              currentNode.add(this.options.cdataPropName, [{ [this.options.textNodeName]: tagExp }]);
            } else {
              currentNode.add(this.options.textNodeName, val2);
            }
            i6 = closeIndex + 2;
          } else {
            let result = readTagExp(xmlData, i6, this.options.removeNSPrefix);
            let tagName = result.tagName;
            const rawTagName = result.rawTagName;
            let tagExp = result.tagExp;
            let attrExpPresent = result.attrExpPresent;
            let closeIndex = result.closeIndex;
            if (this.options.transformTagName) {
              tagName = this.options.transformTagName(tagName);
            }
            if (currentNode && textData) {
              if (currentNode.tagname !== "!xml") {
                textData = this.saveTextToParentTag(textData, currentNode, jPath, false);
              }
            }
            const lastTag = currentNode;
            if (lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1) {
              currentNode = this.tagsNodeStack.pop();
              jPath = jPath.substring(0, jPath.lastIndexOf("."));
            }
            if (tagName !== xmlObj.tagname) {
              jPath += jPath ? "." + tagName : tagName;
            }
            if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) {
              let tagContent = "";
              if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
                if (tagName[tagName.length - 1] === "/") {
                  tagName = tagName.substr(0, tagName.length - 1);
                  jPath = jPath.substr(0, jPath.length - 1);
                  tagExp = tagName;
                } else {
                  tagExp = tagExp.substr(0, tagExp.length - 1);
                }
                i6 = result.closeIndex;
              } else if (this.options.unpairedTags.indexOf(tagName) !== -1) {
                i6 = result.closeIndex;
              } else {
                const result2 = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
                if (!result2) throw new Error(`Unexpected end of ${rawTagName}`);
                i6 = result2.i;
                tagContent = result2.tagContent;
              }
              const childNode = new xmlNode(tagName);
              if (tagName !== tagExp && attrExpPresent) {
                childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
              }
              if (tagContent) {
                tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true);
              }
              jPath = jPath.substr(0, jPath.lastIndexOf("."));
              childNode.add(this.options.textNodeName, tagContent);
              this.addChild(currentNode, childNode, jPath);
            } else {
              if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
                if (tagName[tagName.length - 1] === "/") {
                  tagName = tagName.substr(0, tagName.length - 1);
                  jPath = jPath.substr(0, jPath.length - 1);
                  tagExp = tagName;
                } else {
                  tagExp = tagExp.substr(0, tagExp.length - 1);
                }
                if (this.options.transformTagName) {
                  tagName = this.options.transformTagName(tagName);
                }
                const childNode = new xmlNode(tagName);
                if (tagName !== tagExp && attrExpPresent) {
                  childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
                }
                this.addChild(currentNode, childNode, jPath);
                jPath = jPath.substr(0, jPath.lastIndexOf("."));
              } else {
                const childNode = new xmlNode(tagName);
                this.tagsNodeStack.push(currentNode);
                if (tagName !== tagExp && attrExpPresent) {
                  childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
                }
                this.addChild(currentNode, childNode, jPath);
                currentNode = childNode;
              }
              textData = "";
              i6 = closeIndex;
            }
          }
        } else {
          textData += xmlData[i6];
        }
      }
      return xmlObj.child;
    };
    function addChild(currentNode, childNode, jPath) {
      const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]);
      if (result === false) {
      } else if (typeof result === "string") {
        childNode.tagname = result;
        currentNode.addChild(childNode);
      } else {
        currentNode.addChild(childNode);
      }
    }
    var replaceEntitiesValue = function(val2) {
      if (this.options.processEntities) {
        for (let entityName2 in this.docTypeEntities) {
          const entity = this.docTypeEntities[entityName2];
          val2 = val2.replace(entity.regx, entity.val);
        }
        for (let entityName2 in this.lastEntities) {
          const entity = this.lastEntities[entityName2];
          val2 = val2.replace(entity.regex, entity.val);
        }
        if (this.options.htmlEntities) {
          for (let entityName2 in this.htmlEntities) {
            const entity = this.htmlEntities[entityName2];
            val2 = val2.replace(entity.regex, entity.val);
          }
        }
        val2 = val2.replace(this.ampEntity.regex, this.ampEntity.val);
      }
      return val2;
    };
    function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) {
      if (textData) {
        if (isLeafNode === void 0) isLeafNode = Object.keys(currentNode.child).length === 0;
        textData = this.parseTextData(
          textData,
          currentNode.tagname,
          jPath,
          false,
          currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false,
          isLeafNode
        );
        if (textData !== void 0 && textData !== "")
          currentNode.add(this.options.textNodeName, textData);
        textData = "";
      }
      return textData;
    }
    function isItStopNode(stopNodes, jPath, currentTagName) {
      const allNodesExp = "*." + currentTagName;
      for (const stopNodePath in stopNodes) {
        const stopNodeExp = stopNodes[stopNodePath];
        if (allNodesExp === stopNodeExp || jPath === stopNodeExp) return true;
      }
      return false;
    }
    function tagExpWithClosingIndex(xmlData, i6, closingChar = ">") {
      let attrBoundary;
      let tagExp = "";
      for (let index6 = i6; index6 < xmlData.length; index6++) {
        let ch = xmlData[index6];
        if (attrBoundary) {
          if (ch === attrBoundary) attrBoundary = "";
        } else if (ch === '"' || ch === "'") {
          attrBoundary = ch;
        } else if (ch === closingChar[0]) {
          if (closingChar[1]) {
            if (xmlData[index6 + 1] === closingChar[1]) {
              return {
                data: tagExp,
                index: index6
              };
            }
          } else {
            return {
              data: tagExp,
              index: index6
            };
          }
        } else if (ch === "	") {
          ch = " ";
        }
        tagExp += ch;
      }
    }
    function findClosingIndex(xmlData, str, i6, errMsg) {
      const closingIndex = xmlData.indexOf(str, i6);
      if (closingIndex === -1) {
        throw new Error(errMsg);
      } else {
        return closingIndex + str.length - 1;
      }
    }
    function readTagExp(xmlData, i6, removeNSPrefix, closingChar = ">") {
      const result = tagExpWithClosingIndex(xmlData, i6 + 1, closingChar);
      if (!result) return;
      let tagExp = result.data;
      const closeIndex = result.index;
      const separatorIndex = tagExp.search(/\s/);
      let tagName = tagExp;
      let attrExpPresent = true;
      if (separatorIndex !== -1) {
        tagName = tagExp.substring(0, separatorIndex);
        tagExp = tagExp.substring(separatorIndex + 1).trimStart();
      }
      const rawTagName = tagName;
      if (removeNSPrefix) {
        const colonIndex = tagName.indexOf(":");
        if (colonIndex !== -1) {
          tagName = tagName.substr(colonIndex + 1);
          attrExpPresent = tagName !== result.data.substr(colonIndex + 1);
        }
      }
      return {
        tagName,
        tagExp,
        closeIndex,
        attrExpPresent,
        rawTagName
      };
    }
    function readStopNodeData(xmlData, tagName, i6) {
      const startIndex = i6;
      let openTagCount = 1;
      for (; i6 < xmlData.length; i6++) {
        if (xmlData[i6] === "<") {
          if (xmlData[i6 + 1] === "/") {
            const closeIndex = findClosingIndex(xmlData, ">", i6, `${tagName} is not closed`);
            let closeTagName = xmlData.substring(i6 + 2, closeIndex).trim();
            if (closeTagName === tagName) {
              openTagCount--;
              if (openTagCount === 0) {
                return {
                  tagContent: xmlData.substring(startIndex, i6),
                  i: closeIndex
                };
              }
            }
            i6 = closeIndex;
          } else if (xmlData[i6 + 1] === "?") {
            const closeIndex = findClosingIndex(xmlData, "?>", i6 + 1, "StopNode is not closed.");
            i6 = closeIndex;
          } else if (xmlData.substr(i6 + 1, 3) === "!--") {
            const closeIndex = findClosingIndex(xmlData, "-->", i6 + 3, "StopNode is not closed.");
            i6 = closeIndex;
          } else if (xmlData.substr(i6 + 1, 2) === "![") {
            const closeIndex = findClosingIndex(xmlData, "]]>", i6, "StopNode is not closed.") - 2;
            i6 = closeIndex;
          } else {
            const tagData = readTagExp(xmlData, i6, ">");
            if (tagData) {
              const openTagName = tagData && tagData.tagName;
              if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") {
                openTagCount++;
              }
              i6 = tagData.closeIndex;
            }
          }
        }
      }
    }
    function parseValue(val2, shouldParse, options) {
      if (shouldParse && typeof val2 === "string") {
        const newval = val2.trim();
        if (newval === "true") return true;
        else if (newval === "false") return false;
        else return toNumber(val2, options);
      } else {
        if (util2.isExist(val2)) {
          return val2;
        } else {
          return "";
        }
      }
    }
    module2.exports = OrderedObjParser;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/node2json.js
var require_node2json = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/node2json.js"(exports2) {
    "use strict";
    function prettify(node, options) {
      return compress2(node, options);
    }
    function compress2(arr, options, jPath) {
      let text;
      const compressedObj = {};
      for (let i6 = 0; i6 < arr.length; i6++) {
        const tagObj = arr[i6];
        const property = propName(tagObj);
        let newJpath = "";
        if (jPath === void 0) newJpath = property;
        else newJpath = jPath + "." + property;
        if (property === options.textNodeName) {
          if (text === void 0) text = tagObj[property];
          else text += "" + tagObj[property];
        } else if (property === void 0) {
          continue;
        } else if (tagObj[property]) {
          let val2 = compress2(tagObj[property], options, newJpath);
          const isLeaf = isLeafTag(val2, options);
          if (tagObj[":@"]) {
            assignAttributes(val2, tagObj[":@"], newJpath, options);
          } else if (Object.keys(val2).length === 1 && val2[options.textNodeName] !== void 0 && !options.alwaysCreateTextNode) {
            val2 = val2[options.textNodeName];
          } else if (Object.keys(val2).length === 0) {
            if (options.alwaysCreateTextNode) val2[options.textNodeName] = "";
            else val2 = "";
          }
          if (compressedObj[property] !== void 0 && compressedObj.hasOwnProperty(property)) {
            if (!Array.isArray(compressedObj[property])) {
              compressedObj[property] = [compressedObj[property]];
            }
            compressedObj[property].push(val2);
          } else {
            if (options.isArray(property, newJpath, isLeaf)) {
              compressedObj[property] = [val2];
            } else {
              compressedObj[property] = val2;
            }
          }
        }
      }
      if (typeof text === "string") {
        if (text.length > 0) compressedObj[options.textNodeName] = text;
      } else if (text !== void 0) compressedObj[options.textNodeName] = text;
      return compressedObj;
    }
    function propName(obj) {
      const keys = Object.keys(obj);
      for (let i6 = 0; i6 < keys.length; i6++) {
        const key = keys[i6];
        if (key !== ":@") return key;
      }
    }
    function assignAttributes(obj, attrMap, jpath, options) {
      if (attrMap) {
        const keys = Object.keys(attrMap);
        const len = keys.length;
        for (let i6 = 0; i6 < len; i6++) {
          const atrrName = keys[i6];
          if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) {
            obj[atrrName] = [attrMap[atrrName]];
          } else {
            obj[atrrName] = attrMap[atrrName];
          }
        }
      }
    }
    function isLeafTag(obj, options) {
      const { textNodeName } = options;
      const propCount = Object.keys(obj).length;
      if (propCount === 0) {
        return true;
      }
      if (propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)) {
        return true;
      }
      return false;
    }
    exports2.prettify = prettify;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js
var require_XMLParser = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(exports2, module2) {
    "use strict";
    var { buildOptions } = require_OptionsBuilder();
    var OrderedObjParser = require_OrderedObjParser();
    var { prettify } = require_node2json();
    var validator2 = require_validator();
    var XMLParser2 = class {
      constructor(options) {
        this.externalEntities = {};
        this.options = buildOptions(options);
      }
      /**
       * Parse XML dats to JS object 
       * @param {string|Buffer} xmlData 
       * @param {boolean|Object} validationOption 
       */
      parse(xmlData, validationOption) {
        if (typeof xmlData === "string") {
        } else if (xmlData.toString) {
          xmlData = xmlData.toString();
        } else {
          throw new Error("XML data is accepted in String or Bytes[] form.");
        }
        if (validationOption) {
          if (validationOption === true) validationOption = {};
          const result = validator2.validate(xmlData, validationOption);
          if (result !== true) {
            throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`);
          }
        }
        const orderedObjParser = new OrderedObjParser(this.options);
        orderedObjParser.addExternalEntities(this.externalEntities);
        const orderedResult = orderedObjParser.parseXml(xmlData);
        if (this.options.preserveOrder || orderedResult === void 0) return orderedResult;
        else return prettify(orderedResult, this.options);
      }
      /**
       * Add Entity which is not by default supported by this library
       * @param {string} key 
       * @param {string} value 
       */
      addEntity(key, value) {
        if (value.indexOf("&") !== -1) {
          throw new Error("Entity value can't have '&'");
        } else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) {
          throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");
        } else if (value === "&") {
          throw new Error("An entity with value '&' is not permitted");
        } else {
          this.externalEntities[key] = value;
        }
      }
    };
    module2.exports = XMLParser2;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js
var require_orderedJs2Xml = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(exports2, module2) {
    "use strict";
    var EOL = "\n";
    function toXml(jArray, options) {
      let indentation = "";
      if (options.format && options.indentBy.length > 0) {
        indentation = EOL;
      }
      return arrToStr(jArray, options, "", indentation);
    }
    function arrToStr(arr, options, jPath, indentation) {
      let xmlStr = "";
      let isPreviousElementTag = false;
      for (let i6 = 0; i6 < arr.length; i6++) {
        const tagObj = arr[i6];
        const tagName = propName(tagObj);
        if (tagName === void 0) continue;
        let newJPath = "";
        if (jPath.length === 0) newJPath = tagName;
        else newJPath = `${jPath}.${tagName}`;
        if (tagName === options.textNodeName) {
          let tagText = tagObj[tagName];
          if (!isStopNode(newJPath, options)) {
            tagText = options.tagValueProcessor(tagName, tagText);
            tagText = replaceEntitiesValue(tagText, options);
          }
          if (isPreviousElementTag) {
            xmlStr += indentation;
          }
          xmlStr += tagText;
          isPreviousElementTag = false;
          continue;
        } else if (tagName === options.cdataPropName) {
          if (isPreviousElementTag) {
            xmlStr += indentation;
          }
          xmlStr += `<![CDATA[${tagObj[tagName][0][options.textNodeName]}]]>`;
          isPreviousElementTag = false;
          continue;
        } else if (tagName === options.commentPropName) {
          xmlStr += indentation + `<!--${tagObj[tagName][0][options.textNodeName]}-->`;
          isPreviousElementTag = true;
          continue;
        } else if (tagName[0] === "?") {
          const attStr2 = attr_to_str(tagObj[":@"], options);
          const tempInd = tagName === "?xml" ? "" : indentation;
          let piTextNodeName = tagObj[tagName][0][options.textNodeName];
          piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : "";
          xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr2}?>`;
          isPreviousElementTag = true;
          continue;
        }
        let newIdentation = indentation;
        if (newIdentation !== "") {
          newIdentation += options.indentBy;
        }
        const attStr = attr_to_str(tagObj[":@"], options);
        const tagStart = indentation + `<${tagName}${attStr}`;
        const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation);
        if (options.unpairedTags.indexOf(tagName) !== -1) {
          if (options.suppressUnpairedNode) xmlStr += tagStart + ">";
          else xmlStr += tagStart + "/>";
        } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {
          xmlStr += tagStart + "/>";
        } else if (tagValue && tagValue.endsWith(">")) {
          xmlStr += tagStart + `>${tagValue}${indentation}</${tagName}>`;
        } else {
          xmlStr += tagStart + ">";
          if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("</"))) {
            xmlStr += indentation + options.indentBy + tagValue + indentation;
          } else {
            xmlStr += tagValue;
          }
          xmlStr += `</${tagName}>`;
        }
        isPreviousElementTag = true;
      }
      return xmlStr;
    }
    function propName(obj) {
      const keys = Object.keys(obj);
      for (let i6 = 0; i6 < keys.length; i6++) {
        const key = keys[i6];
        if (!obj.hasOwnProperty(key)) continue;
        if (key !== ":@") return key;
      }
    }
    function attr_to_str(attrMap, options) {
      let attrStr = "";
      if (attrMap && !options.ignoreAttributes) {
        for (let attr in attrMap) {
          if (!attrMap.hasOwnProperty(attr)) continue;
          let attrVal = options.attributeValueProcessor(attr, attrMap[attr]);
          attrVal = replaceEntitiesValue(attrVal, options);
          if (attrVal === true && options.suppressBooleanAttributes) {
            attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;
          } else {
            attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`;
          }
        }
      }
      return attrStr;
    }
    function isStopNode(jPath, options) {
      jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1);
      let tagName = jPath.substr(jPath.lastIndexOf(".") + 1);
      for (let index6 in options.stopNodes) {
        if (options.stopNodes[index6] === jPath || options.stopNodes[index6] === "*." + tagName) return true;
      }
      return false;
    }
    function replaceEntitiesValue(textValue, options) {
      if (textValue && textValue.length > 0 && options.processEntities) {
        for (let i6 = 0; i6 < options.entities.length; i6++) {
          const entity = options.entities[i6];
          textValue = textValue.replace(entity.regex, entity.val);
        }
      }
      return textValue;
    }
    module2.exports = toXml;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js
var require_json2xml = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(exports2, module2) {
    "use strict";
    var buildFromOrderedJs = require_orderedJs2Xml();
    var defaultOptions = {
      attributeNamePrefix: "@_",
      attributesGroupName: false,
      textNodeName: "#text",
      ignoreAttributes: true,
      cdataPropName: false,
      format: false,
      indentBy: "  ",
      suppressEmptyNode: false,
      suppressUnpairedNode: true,
      suppressBooleanAttributes: true,
      tagValueProcessor: function(key, a5) {
        return a5;
      },
      attributeValueProcessor: function(attrName, a5) {
        return a5;
      },
      preserveOrder: false,
      commentPropName: false,
      unpairedTags: [],
      entities: [
        { regex: new RegExp("&", "g"), val: "&amp;" },
        //it must be on top
        { regex: new RegExp(">", "g"), val: "&gt;" },
        { regex: new RegExp("<", "g"), val: "&lt;" },
        { regex: new RegExp("'", "g"), val: "&apos;" },
        { regex: new RegExp('"', "g"), val: "&quot;" }
      ],
      processEntities: true,
      stopNodes: [],
      // transformTagName: false,
      // transformAttributeName: false,
      oneListGroup: false
    };
    function Builder(options) {
      this.options = Object.assign({}, defaultOptions, options);
      if (this.options.ignoreAttributes || this.options.attributesGroupName) {
        this.isAttribute = function() {
          return false;
        };
      } else {
        this.attrPrefixLen = this.options.attributeNamePrefix.length;
        this.isAttribute = isAttribute;
      }
      this.processTextOrObjNode = processTextOrObjNode;
      if (this.options.format) {
        this.indentate = indentate;
        this.tagEndChar = ">\n";
        this.newLine = "\n";
      } else {
        this.indentate = function() {
          return "";
        };
        this.tagEndChar = ">";
        this.newLine = "";
      }
    }
    Builder.prototype.build = function(jObj) {
      if (this.options.preserveOrder) {
        return buildFromOrderedJs(jObj, this.options);
      } else {
        if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) {
          jObj = {
            [this.options.arrayNodeName]: jObj
          };
        }
        return this.j2x(jObj, 0).val;
      }
    };
    Builder.prototype.j2x = function(jObj, level) {
      let attrStr = "";
      let val2 = "";
      for (let key in jObj) {
        if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue;
        if (typeof jObj[key] === "undefined") {
          if (this.isAttribute(key)) {
            val2 += "";
          }
        } else if (jObj[key] === null) {
          if (this.isAttribute(key)) {
            val2 += "";
          } else if (key[0] === "?") {
            val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar;
          } else {
            val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar;
          }
        } else if (jObj[key] instanceof Date) {
          val2 += this.buildTextValNode(jObj[key], key, "", level);
        } else if (typeof jObj[key] !== "object") {
          const attr = this.isAttribute(key);
          if (attr) {
            attrStr += this.buildAttrPairStr(attr, "" + jObj[key]);
          } else {
            if (key === this.options.textNodeName) {
              let newval = this.options.tagValueProcessor(key, "" + jObj[key]);
              val2 += this.replaceEntitiesValue(newval);
            } else {
              val2 += this.buildTextValNode(jObj[key], key, "", level);
            }
          }
        } else if (Array.isArray(jObj[key])) {
          const arrLen = jObj[key].length;
          let listTagVal = "";
          let listTagAttr = "";
          for (let j5 = 0; j5 < arrLen; j5++) {
            const item = jObj[key][j5];
            if (typeof item === "undefined") {
            } else if (item === null) {
              if (key[0] === "?") val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar;
              else val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar;
            } else if (typeof item === "object") {
              if (this.options.oneListGroup) {
                const result = this.j2x(item, level + 1);
                listTagVal += result.val;
                if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) {
                  listTagAttr += result.attrStr;
                }
              } else {
                listTagVal += this.processTextOrObjNode(item, key, level);
              }
            } else {
              if (this.options.oneListGroup) {
                let textValue = this.options.tagValueProcessor(key, item);
                textValue = this.replaceEntitiesValue(textValue);
                listTagVal += textValue;
              } else {
                listTagVal += this.buildTextValNode(item, key, "", level);
              }
            }
          }
          if (this.options.oneListGroup) {
            listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level);
          }
          val2 += listTagVal;
        } else {
          if (this.options.attributesGroupName && key === this.options.attributesGroupName) {
            const Ks = Object.keys(jObj[key]);
            const L = Ks.length;
            for (let j5 = 0; j5 < L; j5++) {
              attrStr += this.buildAttrPairStr(Ks[j5], "" + jObj[key][Ks[j5]]);
            }
          } else {
            val2 += this.processTextOrObjNode(jObj[key], key, level);
          }
        }
      }
      return { attrStr, val: val2 };
    };
    Builder.prototype.buildAttrPairStr = function(attrName, val2) {
      val2 = this.options.attributeValueProcessor(attrName, "" + val2);
      val2 = this.replaceEntitiesValue(val2);
      if (this.options.suppressBooleanAttributes && val2 === "true") {
        return " " + attrName;
      } else return " " + attrName + '="' + val2 + '"';
    };
    function processTextOrObjNode(object, key, level) {
      const result = this.j2x(object, level + 1);
      if (object[this.options.textNodeName] !== void 0 && Object.keys(object).length === 1) {
        return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level);
      } else {
        return this.buildObjectNode(result.val, key, result.attrStr, level);
      }
    }
    Builder.prototype.buildObjectNode = function(val2, key, attrStr, level) {
      if (val2 === "") {
        if (key[0] === "?") return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar;
        else {
          return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar;
        }
      } else {
        let tagEndExp = "</" + key + this.tagEndChar;
        let piClosingChar = "";
        if (key[0] === "?") {
          piClosingChar = "?";
          tagEndExp = "";
        }
        if ((attrStr || attrStr === "") && val2.indexOf("<") === -1) {
          return this.indentate(level) + "<" + key + attrStr + piClosingChar + ">" + val2 + tagEndExp;
        } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {
          return this.indentate(level) + `<!--${val2}-->` + this.newLine;
        } else {
          return this.indentate(level) + "<" + key + attrStr + piClosingChar + this.tagEndChar + val2 + this.indentate(level) + tagEndExp;
        }
      }
    };
    Builder.prototype.closeTag = function(key) {
      let closeTag = "";
      if (this.options.unpairedTags.indexOf(key) !== -1) {
        if (!this.options.suppressUnpairedNode) closeTag = "/";
      } else if (this.options.suppressEmptyNode) {
        closeTag = "/";
      } else {
        closeTag = `></${key}`;
      }
      return closeTag;
    };
    Builder.prototype.buildTextValNode = function(val2, key, attrStr, level) {
      if (this.options.cdataPropName !== false && key === this.options.cdataPropName) {
        return this.indentate(level) + `<![CDATA[${val2}]]>` + this.newLine;
      } else if (this.options.commentPropName !== false && key === this.options.commentPropName) {
        return this.indentate(level) + `<!--${val2}-->` + this.newLine;
      } else if (key[0] === "?") {
        return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar;
      } else {
        let textValue = this.options.tagValueProcessor(key, val2);
        textValue = this.replaceEntitiesValue(textValue);
        if (textValue === "") {
          return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar;
        } else {
          return this.indentate(level) + "<" + key + attrStr + ">" + textValue + "</" + key + this.tagEndChar;
        }
      }
    };
    Builder.prototype.replaceEntitiesValue = function(textValue) {
      if (textValue && textValue.length > 0 && this.options.processEntities) {
        for (let i6 = 0; i6 < this.options.entities.length; i6++) {
          const entity = this.options.entities[i6];
          textValue = textValue.replace(entity.regex, entity.val);
        }
      }
      return textValue;
    };
    function indentate(level) {
      return this.options.indentBy.repeat(level);
    }
    function isAttribute(name) {
      if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) {
        return name.substr(this.attrPrefixLen);
      } else {
        return false;
      }
    }
    module2.exports = Builder;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/fxp.js
var require_fxp = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/fxp.js"(exports2, module2) {
    "use strict";
    var validator2 = require_validator();
    var XMLParser2 = require_XMLParser();
    var XMLBuilder = require_json2xml();
    module2.exports = {
      XMLParser: XMLParser2,
      XMLValidator: validator2,
      XMLBuilder
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js
var import_fast_xml_parser, parseXmlBody, parseXmlErrorBody;
var init_parseXmlBody = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js"() {
    "use strict";
    init_dist_es24();
    import_fast_xml_parser = __toESM(require_fxp());
    init_common2();
    parseXmlBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => {
      if (encoded.length) {
        const parser = new import_fast_xml_parser.XMLParser({
          attributeNamePrefix: "",
          htmlEntities: true,
          ignoreAttributes: false,
          ignoreDeclaration: true,
          parseTagValue: false,
          trimValues: false,
          tagValueProcessor: (_3, val2) => val2.trim() === "" && val2.includes("\n") ? "" : void 0
        });
        parser.addEntity("#xD", "\r");
        parser.addEntity("#10", "\n");
        let parsedObj;
        try {
          parsedObj = parser.parse(encoded, true);
        } catch (e6) {
          if (e6 && typeof e6 === "object") {
            Object.defineProperty(e6, "$responseBodyText", {
              value: encoded
            });
          }
          throw e6;
        }
        const textNodeName = "#text";
        const key = Object.keys(parsedObj)[0];
        const parsedObjToReturn = parsedObj[key];
        if (parsedObjToReturn[textNodeName]) {
          parsedObjToReturn[key] = parsedObjToReturn[textNodeName];
          delete parsedObjToReturn[textNodeName];
        }
        return getValueFromTextNode(parsedObjToReturn);
      }
      return {};
    });
    parseXmlErrorBody = async (errorBody, context) => {
      const value = await parseXmlBody(errorBody, context);
      if (value.Error) {
        value.Error.message = value.Error.message ?? value.Error.Message;
      }
      return value;
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js
var init_protocols2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js"() {
    "use strict";
    init_coercing_serializers();
    init_awsExpectUnion();
    init_parseJsonBody();
    init_parseXmlBody();
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/index.js
var init_dist_es25 = __esm({
  "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/index.js"() {
    "use strict";
    init_client2();
    init_httpAuthSchemes2();
    init_protocols2();
  }
});

// ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/check-features.js
async function checkFeatures(context, config, args) {
  const request2 = args.request;
  if (request2?.headers?.["smithy-protocol"] === "rpc-v2-cbor") {
    setFeature2(context, "PROTOCOL_RPC_V2_CBOR", "M");
  }
  if (typeof config.retryStrategy === "function") {
    const retryStrategy = await config.retryStrategy();
    if (typeof retryStrategy.acquireInitialRetryToken === "function") {
      if (retryStrategy.constructor?.name?.includes("Adaptive")) {
        setFeature2(context, "RETRY_MODE_ADAPTIVE", "F");
      } else {
        setFeature2(context, "RETRY_MODE_STANDARD", "E");
      }
    } else {
      setFeature2(context, "RETRY_MODE_LEGACY", "D");
    }
  }
  if (typeof config.accountIdEndpointMode === "function") {
    const endpointV2 = context.endpointV2;
    if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) {
      setFeature2(context, "ACCOUNT_ID_ENDPOINT", "O");
    }
    switch (await config.accountIdEndpointMode?.()) {
      case "disabled":
        setFeature2(context, "ACCOUNT_ID_MODE_DISABLED", "Q");
        break;
      case "preferred":
        setFeature2(context, "ACCOUNT_ID_MODE_PREFERRED", "P");
        break;
      case "required":
        setFeature2(context, "ACCOUNT_ID_MODE_REQUIRED", "R");
        break;
    }
  }
  const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity;
  if (identity?.$source) {
    const credentials2 = identity;
    if (credentials2.accountId) {
      setFeature2(context, "RESOLVED_ACCOUNT_ID", "T");
    }
    for (const [key, value] of Object.entries(credentials2.$source ?? {})) {
      setFeature2(context, key, value);
    }
  }
}
var ACCOUNT_ID_ENDPOINT_REGEX;
var init_check_features = __esm({
  "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/check-features.js"() {
    "use strict";
    init_dist_es25();
    ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/;
  }
});

// ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/constants.js
var USER_AGENT, X_AMZ_USER_AGENT, SPACE2, UA_NAME_SEPARATOR, UA_NAME_ESCAPE_REGEX, UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR;
var init_constants5 = __esm({
  "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/constants.js"() {
    "use strict";
    USER_AGENT = "user-agent";
    X_AMZ_USER_AGENT = "x-amz-user-agent";
    SPACE2 = " ";
    UA_NAME_SEPARATOR = "/";
    UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g;
    UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;
    UA_ESCAPE_CHAR = "-";
  }
});

// ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/encode-features.js
function encodeFeatures(features) {
  let buffer = "";
  for (const key in features) {
    const val2 = features[key];
    if (buffer.length + val2.length + 1 <= BYTE_LIMIT) {
      if (buffer.length) {
        buffer += "," + val2;
      } else {
        buffer += val2;
      }
      continue;
    }
    break;
  }
  return buffer;
}
var BYTE_LIMIT;
var init_encode_features = __esm({
  "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/encode-features.js"() {
    "use strict";
    BYTE_LIMIT = 1024;
  }
});

// ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/user-agent-middleware.js
var userAgentMiddleware, escapeUserAgent, getUserAgentMiddlewareOptions, getUserAgentPlugin;
var init_user_agent_middleware = __esm({
  "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/user-agent-middleware.js"() {
    "use strict";
    init_dist_es20();
    init_dist_es2();
    init_check_features();
    init_constants5();
    init_encode_features();
    userAgentMiddleware = (options) => (next, context) => async (args) => {
      const { request: request2 } = args;
      if (!HttpRequest.isInstance(request2)) {
        return next(args);
      }
      const { headers } = request2;
      const userAgent = context?.userAgent?.map(escapeUserAgent) || [];
      const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent);
      await checkFeatures(context, options, args);
      const awsContext = context;
      defaultUserAgent.push(`m/${encodeFeatures(Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features))}`);
      const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || [];
      const appId = await options.userAgentAppId();
      if (appId) {
        defaultUserAgent.push(escapeUserAgent([`app/${appId}`]));
      }
      const prefix2 = getUserAgentPrefix();
      const sdkUserAgentValue = (prefix2 ? [prefix2] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE2);
      const normalUAValue = [
        ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")),
        ...customUserAgent
      ].join(SPACE2);
      if (options.runtime !== "browser") {
        if (normalUAValue) {
          headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT]} ${normalUAValue}` : normalUAValue;
        }
        headers[USER_AGENT] = sdkUserAgentValue;
      } else {
        headers[X_AMZ_USER_AGENT] = sdkUserAgentValue;
      }
      return next({
        ...args,
        request: request2
      });
    };
    escapeUserAgent = (userAgentPair) => {
      const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR);
      const version = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR);
      const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR);
      const prefix2 = name.substring(0, prefixSeparatorIndex);
      let uaName = name.substring(prefixSeparatorIndex + 1);
      if (prefix2 === "api") {
        uaName = uaName.toLowerCase();
      }
      return [prefix2, uaName, version].filter((item) => item && item.length > 0).reduce((acc, item, index6) => {
        switch (index6) {
          case 0:
            return item;
          case 1:
            return `${acc}/${item}`;
          default:
            return `${acc}#${item}`;
        }
      }, "");
    };
    getUserAgentMiddlewareOptions = {
      name: "getUserAgentMiddleware",
      step: "build",
      priority: "low",
      tags: ["SET_USER_AGENT", "USER_AGENT"],
      override: true
    };
    getUserAgentPlugin = (config) => ({
      applyToStack: (clientStack) => {
        clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions);
      }
    });
  }
});

// ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/index.js
var init_dist_es26 = __esm({
  "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/index.js"() {
    "use strict";
    init_configurations();
    init_user_agent_middleware();
  }
});

// ../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/booleanSelector.js
var booleanSelector;
var init_booleanSelector = __esm({
  "../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/booleanSelector.js"() {
    "use strict";
    booleanSelector = (obj, key, type) => {
      if (!(key in obj))
        return void 0;
      if (obj[key] === "true")
        return true;
      if (obj[key] === "false")
        return false;
      throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`);
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/numberSelector.js
var init_numberSelector = __esm({
  "../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/numberSelector.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/types.js
var SelectorType;
var init_types5 = __esm({
  "../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/types.js"() {
    "use strict";
    (function(SelectorType2) {
      SelectorType2["ENV"] = "env";
      SelectorType2["CONFIG"] = "shared config entry";
    })(SelectorType || (SelectorType = {}));
  }
});

// ../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/index.js
var init_dist_es27 = __esm({
  "../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/index.js"() {
    "use strict";
    init_booleanSelector();
    init_numberSelector();
    init_types5();
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseDualstackEndpointConfigOptions.js
var ENV_USE_DUALSTACK_ENDPOINT, CONFIG_USE_DUALSTACK_ENDPOINT, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS;
var init_NodeUseDualstackEndpointConfigOptions = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseDualstackEndpointConfigOptions.js"() {
    "use strict";
    init_dist_es27();
    ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT";
    CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint";
    NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = {
      environmentVariableSelector: (env4) => booleanSelector(env4, ENV_USE_DUALSTACK_ENDPOINT, SelectorType.ENV),
      configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, SelectorType.CONFIG),
      default: false
    };
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseFipsEndpointConfigOptions.js
var ENV_USE_FIPS_ENDPOINT, CONFIG_USE_FIPS_ENDPOINT, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS;
var init_NodeUseFipsEndpointConfigOptions = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseFipsEndpointConfigOptions.js"() {
    "use strict";
    init_dist_es27();
    ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT";
    CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint";
    NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = {
      environmentVariableSelector: (env4) => booleanSelector(env4, ENV_USE_FIPS_ENDPOINT, SelectorType.ENV),
      configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, SelectorType.CONFIG),
      default: false
    };
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveCustomEndpointsConfig.js
var init_resolveCustomEndpointsConfig = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveCustomEndpointsConfig.js"() {
    "use strict";
    init_dist_es6();
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/utils/getEndpointFromRegion.js
var init_getEndpointFromRegion = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/utils/getEndpointFromRegion.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveEndpointsConfig.js
var init_resolveEndpointsConfig = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveEndpointsConfig.js"() {
    "use strict";
    init_dist_es6();
    init_getEndpointFromRegion();
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/index.js
var init_endpointsConfig = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/index.js"() {
    "use strict";
    init_NodeUseDualstackEndpointConfigOptions();
    init_NodeUseFipsEndpointConfigOptions();
    init_resolveCustomEndpointsConfig();
    init_resolveEndpointsConfig();
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/config.js
var REGION_ENV_NAME, REGION_INI_NAME, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS;
var init_config2 = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/config.js"() {
    "use strict";
    REGION_ENV_NAME = "AWS_REGION";
    REGION_INI_NAME = "region";
    NODE_REGION_CONFIG_OPTIONS = {
      environmentVariableSelector: (env4) => env4[REGION_ENV_NAME],
      configFileSelector: (profile) => profile[REGION_INI_NAME],
      default: () => {
        throw new Error("Region is missing");
      }
    };
    NODE_REGION_CONFIG_FILE_OPTIONS = {
      preferredFile: "credentials"
    };
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/isFipsRegion.js
var isFipsRegion;
var init_isFipsRegion = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/isFipsRegion.js"() {
    "use strict";
    isFipsRegion = (region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips"));
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/getRealRegion.js
var getRealRegion;
var init_getRealRegion = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/getRealRegion.js"() {
    "use strict";
    init_isFipsRegion();
    getRealRegion = (region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region;
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/resolveRegionConfig.js
var resolveRegionConfig;
var init_resolveRegionConfig = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/resolveRegionConfig.js"() {
    "use strict";
    init_getRealRegion();
    init_isFipsRegion();
    resolveRegionConfig = (input) => {
      const { region, useFipsEndpoint } = input;
      if (!region) {
        throw new Error("Region is missing");
      }
      return Object.assign(input, {
        region: async () => {
          if (typeof region === "string") {
            return getRealRegion(region);
          }
          const providedRegion = await region();
          return getRealRegion(providedRegion);
        },
        useFipsEndpoint: async () => {
          const providedRegion = typeof region === "string" ? region : await region();
          if (isFipsRegion(providedRegion)) {
            return true;
          }
          return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint();
        }
      });
    };
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/index.js
var init_regionConfig = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/index.js"() {
    "use strict";
    init_config2();
    init_resolveRegionConfig();
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/PartitionHash.js
var init_PartitionHash = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/PartitionHash.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/RegionHash.js
var init_RegionHash = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/RegionHash.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getHostnameFromVariants.js
var init_getHostnameFromVariants = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getHostnameFromVariants.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedHostname.js
var init_getResolvedHostname = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedHostname.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedPartition.js
var init_getResolvedPartition = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedPartition.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedSigningRegion.js
var init_getResolvedSigningRegion = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedSigningRegion.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getRegionInfo.js
var init_getRegionInfo = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getRegionInfo.js"() {
    "use strict";
    init_getHostnameFromVariants();
    init_getResolvedHostname();
    init_getResolvedPartition();
    init_getResolvedSigningRegion();
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/index.js
var init_regionInfo = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/index.js"() {
    "use strict";
    init_PartitionHash();
    init_RegionHash();
    init_getRegionInfo();
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/index.js
var init_dist_es28 = __esm({
  "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/index.js"() {
    "use strict";
    init_endpointsConfig();
    init_regionConfig();
    init_regionInfo();
  }
});

// ../node_modules/.pnpm/@smithy+middleware-content-length@4.0.4/node_modules/@smithy/middleware-content-length/dist-es/index.js
function contentLengthMiddleware(bodyLengthChecker) {
  return (next) => async (args) => {
    const request2 = args.request;
    if (HttpRequest.isInstance(request2)) {
      const { body, headers } = request2;
      if (body && Object.keys(headers).map((str) => str.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER) === -1) {
        try {
          const length = bodyLengthChecker(body);
          request2.headers = {
            ...request2.headers,
            [CONTENT_LENGTH_HEADER]: String(length)
          };
        } catch (error2) {
        }
      }
    }
    return next({
      ...args,
      request: request2
    });
  };
}
var CONTENT_LENGTH_HEADER, contentLengthMiddlewareOptions, getContentLengthPlugin;
var init_dist_es29 = __esm({
  "../node_modules/.pnpm/@smithy+middleware-content-length@4.0.4/node_modules/@smithy/middleware-content-length/dist-es/index.js"() {
    "use strict";
    init_dist_es2();
    CONTENT_LENGTH_HEADER = "content-length";
    contentLengthMiddlewareOptions = {
      step: "build",
      tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"],
      name: "contentLengthMiddleware",
      override: true
    };
    getContentLengthPlugin = (options) => ({
      applyToStack: (clientStack) => {
        clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions);
      }
    });
  }
});

// ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/s3.js
var resolveParamsForS3, DOMAIN_PATTERN, IP_ADDRESS_PATTERN, DOTS_PATTERN, isDnsCompatibleBucketName, isArnBucketName;
var init_s3 = __esm({
  "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/s3.js"() {
    "use strict";
    resolveParamsForS3 = async (endpointParams) => {
      const bucket = endpointParams?.Bucket || "";
      if (typeof endpointParams.Bucket === "string") {
        endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?"));
      }
      if (isArnBucketName(bucket)) {
        if (endpointParams.ForcePathStyle === true) {
          throw new Error("Path-style addressing cannot be used with ARN buckets");
        }
      } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) {
        endpointParams.ForcePathStyle = true;
      }
      if (endpointParams.DisableMultiRegionAccessPoints) {
        endpointParams.disableMultiRegionAccessPoints = true;
        endpointParams.DisableMRAP = true;
      }
      return endpointParams;
    };
    DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/;
    IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/;
    DOTS_PATTERN = /\.\./;
    isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName);
    isArnBucketName = (bucketName) => {
      const [arn, partition2, service, , , bucket] = bucketName.split(":");
      const isArn = arn === "arn" && bucketName.split(":").length >= 6;
      const isValidArn = Boolean(isArn && partition2 && service && bucket);
      if (isArn && !isValidArn) {
        throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`);
      }
      return isValidArn;
    };
  }
});

// ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/index.js
var init_service_customizations = __esm({
  "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/index.js"() {
    "use strict";
    init_s3();
  }
});

// ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/createConfigValueProvider.js
var createConfigValueProvider;
var init_createConfigValueProvider = __esm({
  "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/createConfigValueProvider.js"() {
    "use strict";
    createConfigValueProvider = (configKey, canonicalEndpointParamKey, config) => {
      const configProvider = async () => {
        const configValue = config[configKey] ?? config[canonicalEndpointParamKey];
        if (typeof configValue === "function") {
          return configValue();
        }
        return configValue;
      };
      if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") {
        return async () => {
          const credentials2 = typeof config.credentials === "function" ? await config.credentials() : config.credentials;
          const configValue = credentials2?.credentialScope ?? credentials2?.CredentialScope;
          return configValue;
        };
      }
      if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") {
        return async () => {
          const credentials2 = typeof config.credentials === "function" ? await config.credentials() : config.credentials;
          const configValue = credentials2?.accountId ?? credentials2?.AccountId;
          return configValue;
        };
      }
      if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") {
        return async () => {
          const endpoint = await configProvider();
          if (endpoint && typeof endpoint === "object") {
            if ("url" in endpoint) {
              return endpoint.url.href;
            }
            if ("hostname" in endpoint) {
              const { protocol, hostname, port, path: path3 } = endpoint;
              return `${protocol}//${hostname}${port ? ":" + port : ""}${path3}`;
            }
          }
          return endpoint;
        };
      }
      return configProvider;
    };
  }
});

// ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/getSelectorName.js
function getSelectorName(functionString) {
  try {
    const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? []));
    constants.delete("CONFIG");
    constants.delete("CONFIG_PREFIX_SEPARATOR");
    constants.delete("ENV");
    return [...constants].join(", ");
  } catch (e6) {
    return functionString;
  }
}
var init_getSelectorName = __esm({
  "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/getSelectorName.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/fromEnv.js
var fromEnv;
var init_fromEnv = __esm({
  "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/fromEnv.js"() {
    "use strict";
    init_dist_es21();
    init_getSelectorName();
    fromEnv = (envVarSelector, options) => async () => {
      try {
        const config = envVarSelector(process.env, options);
        if (config === void 0) {
          throw new Error();
        }
        return config;
      } catch (e6) {
        throw new CredentialsProviderError(e6.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, { logger: options?.logger });
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getHomeDir.js
var import_os, import_path3, homeDirCache, getHomeDirCacheKey, getHomeDir;
var init_getHomeDir = __esm({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getHomeDir.js"() {
    "use strict";
    import_os = require("os");
    import_path3 = require("path");
    homeDirCache = {};
    getHomeDirCacheKey = () => {
      if (process && process.geteuid) {
        return `${process.geteuid()}`;
      }
      return "DEFAULT";
    };
    getHomeDir = () => {
      const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${import_path3.sep}` } = process.env;
      if (HOME)
        return HOME;
      if (USERPROFILE)
        return USERPROFILE;
      if (HOMEPATH)
        return `${HOMEDRIVE}${HOMEPATH}`;
      const homeDirCacheKey = getHomeDirCacheKey();
      if (!homeDirCache[homeDirCacheKey])
        homeDirCache[homeDirCacheKey] = (0, import_os.homedir)();
      return homeDirCache[homeDirCacheKey];
    };
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getProfileName.js
var ENV_PROFILE, DEFAULT_PROFILE, getProfileName;
var init_getProfileName = __esm({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getProfileName.js"() {
    "use strict";
    ENV_PROFILE = "AWS_PROFILE";
    DEFAULT_PROFILE = "default";
    getProfileName = (init2) => init2.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE;
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getSSOTokenFilepath.js
var import_crypto3, import_path4, getSSOTokenFilepath;
var init_getSSOTokenFilepath = __esm({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getSSOTokenFilepath.js"() {
    "use strict";
    import_crypto3 = require("crypto");
    import_path4 = require("path");
    init_getHomeDir();
    getSSOTokenFilepath = (id) => {
      const hasher = (0, import_crypto3.createHash)("sha1");
      const cacheName = hasher.update(id).digest("hex");
      return (0, import_path4.join)(getHomeDir(), ".aws", "sso", "cache", `${cacheName}.json`);
    };
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getSSOTokenFromFile.js
var import_fs3, readFile2, getSSOTokenFromFile;
var init_getSSOTokenFromFile = __esm({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getSSOTokenFromFile.js"() {
    "use strict";
    import_fs3 = require("fs");
    init_getSSOTokenFilepath();
    ({ readFile: readFile2 } = import_fs3.promises);
    getSSOTokenFromFile = async (id) => {
      const ssoTokenFilepath = getSSOTokenFilepath(id);
      const ssoTokenText = await readFile2(ssoTokenFilepath, "utf8");
      return JSON.parse(ssoTokenText);
    };
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getConfigData.js
var getConfigData;
var init_getConfigData = __esm({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getConfigData.js"() {
    "use strict";
    init_dist_es();
    init_loadSharedConfigFiles();
    getConfigData = (data) => Object.entries(data).filter(([key]) => {
      const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);
      if (indexOfSeparator === -1) {
        return false;
      }
      return Object.values(IniSectionType).includes(key.substring(0, indexOfSeparator));
    }).reduce((acc, [key, value]) => {
      const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);
      const updatedKey = key.substring(0, indexOfSeparator) === IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key;
      acc[updatedKey] = value;
      return acc;
    }, {
      ...data.default && { default: data.default }
    });
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getConfigFilepath.js
var import_path5, ENV_CONFIG_PATH, getConfigFilepath;
var init_getConfigFilepath = __esm({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getConfigFilepath.js"() {
    "use strict";
    import_path5 = require("path");
    init_getHomeDir();
    ENV_CONFIG_PATH = "AWS_CONFIG_FILE";
    getConfigFilepath = () => process.env[ENV_CONFIG_PATH] || (0, import_path5.join)(getHomeDir(), ".aws", "config");
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getCredentialsFilepath.js
var import_path6, ENV_CREDENTIALS_PATH, getCredentialsFilepath;
var init_getCredentialsFilepath = __esm({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getCredentialsFilepath.js"() {
    "use strict";
    import_path6 = require("path");
    init_getHomeDir();
    ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE";
    getCredentialsFilepath = () => process.env[ENV_CREDENTIALS_PATH] || (0, import_path6.join)(getHomeDir(), ".aws", "credentials");
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/parseIni.js
var prefixKeyRegex, profileNameBlockList, parseIni;
var init_parseIni = __esm({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/parseIni.js"() {
    "use strict";
    init_dist_es();
    init_loadSharedConfigFiles();
    prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/;
    profileNameBlockList = ["__proto__", "profile __proto__"];
    parseIni = (iniData) => {
      const map2 = {};
      let currentSection;
      let currentSubSection;
      for (const iniLine of iniData.split(/\r?\n/)) {
        const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim();
        const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]";
        if (isSection) {
          currentSection = void 0;
          currentSubSection = void 0;
          const sectionName = trimmedLine.substring(1, trimmedLine.length - 1);
          const matches = prefixKeyRegex.exec(sectionName);
          if (matches) {
            const [, prefix2, , name] = matches;
            if (Object.values(IniSectionType).includes(prefix2)) {
              currentSection = [prefix2, name].join(CONFIG_PREFIX_SEPARATOR);
            }
          } else {
            currentSection = sectionName;
          }
          if (profileNameBlockList.includes(sectionName)) {
            throw new Error(`Found invalid profile name "${sectionName}"`);
          }
        } else if (currentSection) {
          const indexOfEqualsSign = trimmedLine.indexOf("=");
          if (![0, -1].includes(indexOfEqualsSign)) {
            const [name, value] = [
              trimmedLine.substring(0, indexOfEqualsSign).trim(),
              trimmedLine.substring(indexOfEqualsSign + 1).trim()
            ];
            if (value === "") {
              currentSubSection = name;
            } else {
              if (currentSubSection && iniLine.trimStart() === iniLine) {
                currentSubSection = void 0;
              }
              map2[currentSection] = map2[currentSection] || {};
              const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name;
              map2[currentSection][key] = value;
            }
          }
        }
      }
      return map2;
    };
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/slurpFile.js
var import_fs4, readFile3, filePromisesHash, slurpFile;
var init_slurpFile = __esm({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/slurpFile.js"() {
    "use strict";
    import_fs4 = require("fs");
    ({ readFile: readFile3 } = import_fs4.promises);
    filePromisesHash = {};
    slurpFile = (path3, options) => {
      if (!filePromisesHash[path3] || options?.ignoreCache) {
        filePromisesHash[path3] = readFile3(path3, "utf8");
      }
      return filePromisesHash[path3];
    };
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/loadSharedConfigFiles.js
var import_path7, swallowError, CONFIG_PREFIX_SEPARATOR, loadSharedConfigFiles;
var init_loadSharedConfigFiles = __esm({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/loadSharedConfigFiles.js"() {
    "use strict";
    import_path7 = require("path");
    init_getConfigData();
    init_getConfigFilepath();
    init_getCredentialsFilepath();
    init_getHomeDir();
    init_parseIni();
    init_slurpFile();
    swallowError = () => ({});
    CONFIG_PREFIX_SEPARATOR = ".";
    loadSharedConfigFiles = async (init2 = {}) => {
      const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init2;
      const homeDir = getHomeDir();
      const relativeHomeDirPrefix = "~/";
      let resolvedFilepath = filepath;
      if (filepath.startsWith(relativeHomeDirPrefix)) {
        resolvedFilepath = (0, import_path7.join)(homeDir, filepath.slice(2));
      }
      let resolvedConfigFilepath = configFilepath;
      if (configFilepath.startsWith(relativeHomeDirPrefix)) {
        resolvedConfigFilepath = (0, import_path7.join)(homeDir, configFilepath.slice(2));
      }
      const parsedFiles = await Promise.all([
        slurpFile(resolvedConfigFilepath, {
          ignoreCache: init2.ignoreCache
        }).then(parseIni).then(getConfigData).catch(swallowError),
        slurpFile(resolvedFilepath, {
          ignoreCache: init2.ignoreCache
        }).then(parseIni).catch(swallowError)
      ]);
      return {
        configFile: parsedFiles[0],
        credentialsFile: parsedFiles[1]
      };
    };
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getSsoSessionData.js
var getSsoSessionData;
var init_getSsoSessionData = __esm({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getSsoSessionData.js"() {
    "use strict";
    init_dist_es();
    init_loadSharedConfigFiles();
    getSsoSessionData = (data) => Object.entries(data).filter(([key]) => key.startsWith(IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {});
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/loadSsoSessionData.js
var swallowError2, loadSsoSessionData;
var init_loadSsoSessionData = __esm({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/loadSsoSessionData.js"() {
    "use strict";
    init_getConfigFilepath();
    init_getSsoSessionData();
    init_parseIni();
    init_slurpFile();
    swallowError2 = () => ({});
    loadSsoSessionData = async (init2 = {}) => slurpFile(init2.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2);
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/mergeConfigFiles.js
var mergeConfigFiles;
var init_mergeConfigFiles = __esm({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/mergeConfigFiles.js"() {
    "use strict";
    mergeConfigFiles = (...files) => {
      const merged = {};
      for (const file of files) {
        for (const [key, values] of Object.entries(file)) {
          if (merged[key] !== void 0) {
            Object.assign(merged[key], values);
          } else {
            merged[key] = values;
          }
        }
      }
      return merged;
    };
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/parseKnownFiles.js
var parseKnownFiles;
var init_parseKnownFiles = __esm({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/parseKnownFiles.js"() {
    "use strict";
    init_loadSharedConfigFiles();
    init_mergeConfigFiles();
    parseKnownFiles = async (init2) => {
      const parsedFiles = await loadSharedConfigFiles(init2);
      return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile);
    };
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/types.js
var init_types6 = __esm({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/types.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/index.js
var init_dist_es30 = __esm({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/index.js"() {
    "use strict";
    init_getHomeDir();
    init_getProfileName();
    init_getSSOTokenFilepath();
    init_getSSOTokenFromFile();
    init_loadSharedConfigFiles();
    init_loadSsoSessionData();
    init_parseKnownFiles();
    init_types6();
  }
});

// ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/fromSharedConfigFiles.js
var fromSharedConfigFiles;
var init_fromSharedConfigFiles = __esm({
  "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/fromSharedConfigFiles.js"() {
    "use strict";
    init_dist_es21();
    init_dist_es30();
    init_getSelectorName();
    fromSharedConfigFiles = (configSelector, { preferredFile = "config", ...init2 } = {}) => async () => {
      const profile = getProfileName(init2);
      const { configFile, credentialsFile } = await loadSharedConfigFiles(init2);
      const profileFromCredentials = credentialsFile[profile] || {};
      const profileFromConfig = configFile[profile] || {};
      const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials };
      try {
        const cfgFile = preferredFile === "config" ? configFile : credentialsFile;
        const configValue = configSelector(mergedProfile, cfgFile);
        if (configValue === void 0) {
          throw new Error();
        }
        return configValue;
      } catch (e6) {
        throw new CredentialsProviderError(e6.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, { logger: init2.logger });
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/fromStatic.js
var isFunction, fromStatic2;
var init_fromStatic2 = __esm({
  "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/fromStatic.js"() {
    "use strict";
    init_dist_es21();
    isFunction = (func) => typeof func === "function";
    fromStatic2 = (defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : fromStatic(defaultValue);
  }
});

// ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/configLoader.js
var loadConfig;
var init_configLoader = __esm({
  "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/configLoader.js"() {
    "use strict";
    init_dist_es21();
    init_fromEnv();
    init_fromSharedConfigFiles();
    init_fromStatic2();
    loadConfig = ({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => {
      const { signingName, logger: logger2 } = configuration;
      const envOptions = { signingName, logger: logger2 };
      return memoize(chain(fromEnv(environmentVariableSelector, envOptions), fromSharedConfigFiles(configFileSelector, configuration), fromStatic2(defaultValue)));
    };
  }
});

// ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/index.js
var init_dist_es31 = __esm({
  "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/index.js"() {
    "use strict";
    init_configLoader();
  }
});

// ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointUrlConfig.js
var ENV_ENDPOINT_URL, CONFIG_ENDPOINT_URL, getEndpointUrlConfig;
var init_getEndpointUrlConfig = __esm({
  "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointUrlConfig.js"() {
    "use strict";
    init_dist_es30();
    ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL";
    CONFIG_ENDPOINT_URL = "endpoint_url";
    getEndpointUrlConfig = (serviceId) => ({
      environmentVariableSelector: (env4) => {
        const serviceSuffixParts = serviceId.split(" ").map((w4) => w4.toUpperCase());
        const serviceEndpointUrl = env4[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")];
        if (serviceEndpointUrl)
          return serviceEndpointUrl;
        const endpointUrl = env4[ENV_ENDPOINT_URL];
        if (endpointUrl)
          return endpointUrl;
        return void 0;
      },
      configFileSelector: (profile, config) => {
        if (config && profile.services) {
          const servicesSection = config[["services", profile.services].join(CONFIG_PREFIX_SEPARATOR)];
          if (servicesSection) {
            const servicePrefixParts = serviceId.split(" ").map((w4) => w4.toLowerCase());
            const endpointUrl2 = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(CONFIG_PREFIX_SEPARATOR)];
            if (endpointUrl2)
              return endpointUrl2;
          }
        }
        const endpointUrl = profile[CONFIG_ENDPOINT_URL];
        if (endpointUrl)
          return endpointUrl;
        return void 0;
      },
      default: void 0
    });
  }
});

// ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromConfig.js
var getEndpointFromConfig;
var init_getEndpointFromConfig = __esm({
  "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromConfig.js"() {
    "use strict";
    init_dist_es31();
    init_getEndpointUrlConfig();
    getEndpointFromConfig = async (serviceId) => loadConfig(getEndpointUrlConfig(serviceId ?? ""))();
  }
});

// ../node_modules/.pnpm/@smithy+querystring-parser@4.0.4/node_modules/@smithy/querystring-parser/dist-es/index.js
function parseQueryString(querystring) {
  const query = {};
  querystring = querystring.replace(/^\?/, "");
  if (querystring) {
    for (const pair of querystring.split("&")) {
      let [key, value = null] = pair.split("=");
      key = decodeURIComponent(key);
      if (value) {
        value = decodeURIComponent(value);
      }
      if (!(key in query)) {
        query[key] = value;
      } else if (Array.isArray(query[key])) {
        query[key].push(value);
      } else {
        query[key] = [query[key], value];
      }
    }
  }
  return query;
}
var init_dist_es32 = __esm({
  "../node_modules/.pnpm/@smithy+querystring-parser@4.0.4/node_modules/@smithy/querystring-parser/dist-es/index.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+url-parser@4.0.4/node_modules/@smithy/url-parser/dist-es/index.js
var parseUrl;
var init_dist_es33 = __esm({
  "../node_modules/.pnpm/@smithy+url-parser@4.0.4/node_modules/@smithy/url-parser/dist-es/index.js"() {
    "use strict";
    init_dist_es32();
    parseUrl = (url) => {
      if (typeof url === "string") {
        return parseUrl(new URL(url));
      }
      const { hostname, pathname, port, protocol, search } = url;
      let query;
      if (search) {
        query = parseQueryString(search);
      }
      return {
        hostname,
        port: port ? parseInt(port) : void 0,
        protocol,
        path: pathname,
        query
      };
    };
  }
});

// ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/toEndpointV1.js
var toEndpointV1;
var init_toEndpointV1 = __esm({
  "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/toEndpointV1.js"() {
    "use strict";
    init_dist_es33();
    toEndpointV1 = (endpoint) => {
      if (typeof endpoint === "object") {
        if ("url" in endpoint) {
          return parseUrl(endpoint.url);
        }
        return endpoint;
      }
      return parseUrl(endpoint);
    };
  }
});

// ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromInstructions.js
var getEndpointFromInstructions, resolveParams;
var init_getEndpointFromInstructions = __esm({
  "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromInstructions.js"() {
    "use strict";
    init_service_customizations();
    init_createConfigValueProvider();
    init_getEndpointFromConfig();
    init_toEndpointV1();
    getEndpointFromInstructions = async (commandInput, instructionsSupplier, clientConfig, context) => {
      if (!clientConfig.endpoint) {
        let endpointFromConfig;
        if (clientConfig.serviceConfiguredEndpoint) {
          endpointFromConfig = await clientConfig.serviceConfiguredEndpoint();
        } else {
          endpointFromConfig = await getEndpointFromConfig(clientConfig.serviceId);
        }
        if (endpointFromConfig) {
          clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig));
        }
      }
      const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig);
      if (typeof clientConfig.endpointProvider !== "function") {
        throw new Error("config.endpointProvider is not set.");
      }
      const endpoint = clientConfig.endpointProvider(endpointParams, context);
      return endpoint;
    };
    resolveParams = async (commandInput, instructionsSupplier, clientConfig) => {
      const endpointParams = {};
      const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {};
      for (const [name, instruction] of Object.entries(instructions)) {
        switch (instruction.type) {
          case "staticContextParams":
            endpointParams[name] = instruction.value;
            break;
          case "contextParams":
            endpointParams[name] = commandInput[instruction.name];
            break;
          case "clientContextParams":
          case "builtInParams":
            endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig)();
            break;
          case "operationContextParams":
            endpointParams[name] = instruction.get(commandInput);
            break;
          default:
            throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction));
        }
      }
      if (Object.keys(instructions).length === 0) {
        Object.assign(endpointParams, clientConfig);
      }
      if (String(clientConfig.serviceId).toLowerCase() === "s3") {
        await resolveParamsForS3(endpointParams);
      }
      return endpointParams;
    };
  }
});

// ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/index.js
var init_adaptors = __esm({
  "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/index.js"() {
    "use strict";
    init_getEndpointFromInstructions();
    init_toEndpointV1();
  }
});

// ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/endpointMiddleware.js
var endpointMiddleware;
var init_endpointMiddleware = __esm({
  "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/endpointMiddleware.js"() {
    "use strict";
    init_dist_es18();
    init_dist_es6();
    init_getEndpointFromInstructions();
    endpointMiddleware = ({ config, instructions }) => {
      return (next, context) => async (args) => {
        if (config.endpoint) {
          setFeature(context, "ENDPOINT_OVERRIDE", "N");
        }
        const endpoint = await getEndpointFromInstructions(args.input, {
          getEndpointParameterInstructions() {
            return instructions;
          }
        }, { ...config }, context);
        context.endpointV2 = endpoint;
        context.authSchemes = endpoint.properties?.authSchemes;
        const authScheme = context.authSchemes?.[0];
        if (authScheme) {
          context["signing_region"] = authScheme.signingRegion;
          context["signing_service"] = authScheme.signingName;
          const smithyContext = getSmithyContext(context);
          const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption;
          if (httpAuthOption) {
            httpAuthOption.signingProperties = Object.assign(httpAuthOption.signingProperties || {}, {
              signing_region: authScheme.signingRegion,
              signingRegion: authScheme.signingRegion,
              signing_service: authScheme.signingName,
              signingName: authScheme.signingName,
              signingRegionSet: authScheme.signingRegionSet
            }, authScheme.properties);
          }
        }
        return next({
          ...args
        });
      };
    };
  }
});

// ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/getEndpointPlugin.js
var endpointMiddlewareOptions, getEndpointPlugin;
var init_getEndpointPlugin = __esm({
  "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/getEndpointPlugin.js"() {
    "use strict";
    init_dist_es7();
    init_endpointMiddleware();
    endpointMiddlewareOptions = {
      step: "serialize",
      tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"],
      name: "endpointV2Middleware",
      override: true,
      relation: "before",
      toMiddleware: serializerMiddlewareOption.name
    };
    getEndpointPlugin = (config, instructions) => ({
      applyToStack: (clientStack) => {
        clientStack.addRelativeTo(endpointMiddleware({
          config,
          instructions
        }), endpointMiddlewareOptions);
      }
    });
  }
});

// ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/resolveEndpointConfig.js
var resolveEndpointConfig;
var init_resolveEndpointConfig = __esm({
  "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/resolveEndpointConfig.js"() {
    "use strict";
    init_dist_es6();
    init_getEndpointFromConfig();
    init_toEndpointV1();
    resolveEndpointConfig = (input) => {
      const tls = input.tls ?? true;
      const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input;
      const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await normalizeProvider(endpoint)()) : void 0;
      const isCustomEndpoint = !!endpoint;
      const resolvedConfig = Object.assign(input, {
        endpoint: customEndpointProvider,
        tls,
        isCustomEndpoint,
        useDualstackEndpoint: normalizeProvider(useDualstackEndpoint ?? false),
        useFipsEndpoint: normalizeProvider(useFipsEndpoint ?? false)
      });
      let configuredEndpointPromise = void 0;
      resolvedConfig.serviceConfiguredEndpoint = async () => {
        if (input.serviceId && !configuredEndpointPromise) {
          configuredEndpointPromise = getEndpointFromConfig(input.serviceId);
        }
        return configuredEndpointPromise;
      };
      return resolvedConfig;
    };
  }
});

// ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/types.js
var init_types7 = __esm({
  "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/types.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/index.js
var init_dist_es34 = __esm({
  "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/index.js"() {
    "use strict";
    init_adaptors();
    init_endpointMiddleware();
    init_getEndpointPlugin();
    init_resolveEndpointConfig();
    init_types7();
  }
});

// ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/config.js
var RETRY_MODES, DEFAULT_MAX_ATTEMPTS, DEFAULT_RETRY_MODE;
var init_config3 = __esm({
  "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/config.js"() {
    "use strict";
    (function(RETRY_MODES2) {
      RETRY_MODES2["STANDARD"] = "standard";
      RETRY_MODES2["ADAPTIVE"] = "adaptive";
    })(RETRY_MODES || (RETRY_MODES = {}));
    DEFAULT_MAX_ATTEMPTS = 3;
    DEFAULT_RETRY_MODE = RETRY_MODES.STANDARD;
  }
});

// ../node_modules/.pnpm/@smithy+service-error-classification@4.0.5/node_modules/@smithy/service-error-classification/dist-es/constants.js
var THROTTLING_ERROR_CODES, TRANSIENT_ERROR_CODES, TRANSIENT_ERROR_STATUS_CODES, NODEJS_TIMEOUT_ERROR_CODES2;
var init_constants6 = __esm({
  "../node_modules/.pnpm/@smithy+service-error-classification@4.0.5/node_modules/@smithy/service-error-classification/dist-es/constants.js"() {
    "use strict";
    THROTTLING_ERROR_CODES = [
      "BandwidthLimitExceeded",
      "EC2ThrottledException",
      "LimitExceededException",
      "PriorRequestNotComplete",
      "ProvisionedThroughputExceededException",
      "RequestLimitExceeded",
      "RequestThrottled",
      "RequestThrottledException",
      "SlowDown",
      "ThrottledException",
      "Throttling",
      "ThrottlingException",
      "TooManyRequestsException",
      "TransactionInProgressException"
    ];
    TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"];
    TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504];
    NODEJS_TIMEOUT_ERROR_CODES2 = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"];
  }
});

// ../node_modules/.pnpm/@smithy+service-error-classification@4.0.5/node_modules/@smithy/service-error-classification/dist-es/index.js
var isClockSkewCorrectedError, isBrowserNetworkError, isThrottlingError, isTransientError, isServerError;
var init_dist_es35 = __esm({
  "../node_modules/.pnpm/@smithy+service-error-classification@4.0.5/node_modules/@smithy/service-error-classification/dist-es/index.js"() {
    "use strict";
    init_constants6();
    isClockSkewCorrectedError = (error2) => error2.$metadata?.clockSkewCorrected;
    isBrowserNetworkError = (error2) => {
      const errorMessages = /* @__PURE__ */ new Set([
        "Failed to fetch",
        "NetworkError when attempting to fetch resource",
        "The Internet connection appears to be offline",
        "Load failed",
        "Network request failed"
      ]);
      const isValid2 = error2 && error2 instanceof TypeError;
      if (!isValid2) {
        return false;
      }
      return errorMessages.has(error2.message);
    };
    isThrottlingError = (error2) => error2.$metadata?.httpStatusCode === 429 || THROTTLING_ERROR_CODES.includes(error2.name) || error2.$retryable?.throttling == true;
    isTransientError = (error2, depth = 0) => isClockSkewCorrectedError(error2) || TRANSIENT_ERROR_CODES.includes(error2.name) || NODEJS_TIMEOUT_ERROR_CODES2.includes(error2?.code || "") || TRANSIENT_ERROR_STATUS_CODES.includes(error2.$metadata?.httpStatusCode || 0) || isBrowserNetworkError(error2) || error2.cause !== void 0 && depth <= 10 && isTransientError(error2.cause, depth + 1);
    isServerError = (error2) => {
      if (error2.$metadata?.httpStatusCode !== void 0) {
        const statusCode = error2.$metadata.httpStatusCode;
        if (500 <= statusCode && statusCode <= 599 && !isTransientError(error2)) {
          return true;
        }
        return false;
      }
      return false;
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/DefaultRateLimiter.js
var DefaultRateLimiter;
var init_DefaultRateLimiter = __esm({
  "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/DefaultRateLimiter.js"() {
    "use strict";
    init_dist_es35();
    DefaultRateLimiter = class _DefaultRateLimiter {
      constructor(options) {
        this.currentCapacity = 0;
        this.enabled = false;
        this.lastMaxRate = 0;
        this.measuredTxRate = 0;
        this.requestCount = 0;
        this.lastTimestamp = 0;
        this.timeWindow = 0;
        this.beta = options?.beta ?? 0.7;
        this.minCapacity = options?.minCapacity ?? 1;
        this.minFillRate = options?.minFillRate ?? 0.5;
        this.scaleConstant = options?.scaleConstant ?? 0.4;
        this.smooth = options?.smooth ?? 0.8;
        const currentTimeInSeconds = this.getCurrentTimeInSeconds();
        this.lastThrottleTime = currentTimeInSeconds;
        this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds());
        this.fillRate = this.minFillRate;
        this.maxCapacity = this.minCapacity;
      }
      getCurrentTimeInSeconds() {
        return Date.now() / 1e3;
      }
      async getSendToken() {
        return this.acquireTokenBucket(1);
      }
      async acquireTokenBucket(amount) {
        if (!this.enabled) {
          return;
        }
        this.refillTokenBucket();
        if (amount > this.currentCapacity) {
          const delay = (amount - this.currentCapacity) / this.fillRate * 1e3;
          await new Promise((resolve) => _DefaultRateLimiter.setTimeoutFn(resolve, delay));
        }
        this.currentCapacity = this.currentCapacity - amount;
      }
      refillTokenBucket() {
        const timestamp = this.getCurrentTimeInSeconds();
        if (!this.lastTimestamp) {
          this.lastTimestamp = timestamp;
          return;
        }
        const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate;
        this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + fillAmount);
        this.lastTimestamp = timestamp;
      }
      updateClientSendingRate(response) {
        let calculatedRate;
        this.updateMeasuredRate();
        if (isThrottlingError(response)) {
          const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate);
          this.lastMaxRate = rateToUse;
          this.calculateTimeWindow();
          this.lastThrottleTime = this.getCurrentTimeInSeconds();
          calculatedRate = this.cubicThrottle(rateToUse);
          this.enableTokenBucket();
        } else {
          this.calculateTimeWindow();
          calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds());
        }
        const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate);
        this.updateTokenBucketRate(newRate);
      }
      calculateTimeWindow() {
        this.timeWindow = this.getPrecise(Math.pow(this.lastMaxRate * (1 - this.beta) / this.scaleConstant, 1 / 3));
      }
      cubicThrottle(rateToUse) {
        return this.getPrecise(rateToUse * this.beta);
      }
      cubicSuccess(timestamp) {
        return this.getPrecise(this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate);
      }
      enableTokenBucket() {
        this.enabled = true;
      }
      updateTokenBucketRate(newRate) {
        this.refillTokenBucket();
        this.fillRate = Math.max(newRate, this.minFillRate);
        this.maxCapacity = Math.max(newRate, this.minCapacity);
        this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity);
      }
      updateMeasuredRate() {
        const t6 = this.getCurrentTimeInSeconds();
        const timeBucket = Math.floor(t6 * 2) / 2;
        this.requestCount++;
        if (timeBucket > this.lastTxRateBucket) {
          const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket);
          this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth));
          this.requestCount = 0;
          this.lastTxRateBucket = timeBucket;
        }
      }
      getPrecise(num) {
        return parseFloat(num.toFixed(8));
      }
    };
    DefaultRateLimiter.setTimeoutFn = setTimeout;
  }
});

// ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/constants.js
var DEFAULT_RETRY_DELAY_BASE, MAXIMUM_RETRY_DELAY, THROTTLING_RETRY_DELAY_BASE, INITIAL_RETRY_TOKENS, RETRY_COST, TIMEOUT_RETRY_COST, NO_RETRY_INCREMENT, INVOCATION_ID_HEADER, REQUEST_HEADER;
var init_constants7 = __esm({
  "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/constants.js"() {
    "use strict";
    DEFAULT_RETRY_DELAY_BASE = 100;
    MAXIMUM_RETRY_DELAY = 20 * 1e3;
    THROTTLING_RETRY_DELAY_BASE = 500;
    INITIAL_RETRY_TOKENS = 500;
    RETRY_COST = 5;
    TIMEOUT_RETRY_COST = 10;
    NO_RETRY_INCREMENT = 1;
    INVOCATION_ID_HEADER = "amz-sdk-invocation-id";
    REQUEST_HEADER = "amz-sdk-request";
  }
});

// ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/defaultRetryBackoffStrategy.js
var getDefaultRetryBackoffStrategy;
var init_defaultRetryBackoffStrategy = __esm({
  "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/defaultRetryBackoffStrategy.js"() {
    "use strict";
    init_constants7();
    getDefaultRetryBackoffStrategy = () => {
      let delayBase = DEFAULT_RETRY_DELAY_BASE;
      const computeNextBackoffDelay = (attempts) => {
        return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase));
      };
      const setDelayBase = (delay) => {
        delayBase = delay;
      };
      return {
        computeNextBackoffDelay,
        setDelayBase
      };
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/defaultRetryToken.js
var createDefaultRetryToken;
var init_defaultRetryToken = __esm({
  "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/defaultRetryToken.js"() {
    "use strict";
    init_constants7();
    createDefaultRetryToken = ({ retryDelay, retryCount, retryCost }) => {
      const getRetryCount = () => retryCount;
      const getRetryDelay = () => Math.min(MAXIMUM_RETRY_DELAY, retryDelay);
      const getRetryCost = () => retryCost;
      return {
        getRetryCount,
        getRetryDelay,
        getRetryCost
      };
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/StandardRetryStrategy.js
var StandardRetryStrategy;
var init_StandardRetryStrategy = __esm({
  "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/StandardRetryStrategy.js"() {
    "use strict";
    init_config3();
    init_constants7();
    init_defaultRetryBackoffStrategy();
    init_defaultRetryToken();
    StandardRetryStrategy = class {
      constructor(maxAttempts) {
        this.maxAttempts = maxAttempts;
        this.mode = RETRY_MODES.STANDARD;
        this.capacity = INITIAL_RETRY_TOKENS;
        this.retryBackoffStrategy = getDefaultRetryBackoffStrategy();
        this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts;
      }
      async acquireInitialRetryToken(retryTokenScope) {
        return createDefaultRetryToken({
          retryDelay: DEFAULT_RETRY_DELAY_BASE,
          retryCount: 0
        });
      }
      async refreshRetryTokenForRetry(token, errorInfo) {
        const maxAttempts = await this.getMaxAttempts();
        if (this.shouldRetry(token, errorInfo, maxAttempts)) {
          const errorType = errorInfo.errorType;
          this.retryBackoffStrategy.setDelayBase(errorType === "THROTTLING" ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE);
          const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount());
          const retryDelay = errorInfo.retryAfterHint ? Math.max(errorInfo.retryAfterHint.getTime() - Date.now() || 0, delayFromErrorType) : delayFromErrorType;
          const capacityCost = this.getCapacityCost(errorType);
          this.capacity -= capacityCost;
          return createDefaultRetryToken({
            retryDelay,
            retryCount: token.getRetryCount() + 1,
            retryCost: capacityCost
          });
        }
        throw new Error("No retry token available");
      }
      recordSuccess(token) {
        this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT));
      }
      getCapacity() {
        return this.capacity;
      }
      async getMaxAttempts() {
        try {
          return await this.maxAttemptsProvider();
        } catch (error2) {
          console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`);
          return DEFAULT_MAX_ATTEMPTS;
        }
      }
      shouldRetry(tokenToRenew, errorInfo, maxAttempts) {
        const attempts = tokenToRenew.getRetryCount() + 1;
        return attempts < maxAttempts && this.capacity >= this.getCapacityCost(errorInfo.errorType) && this.isRetryableError(errorInfo.errorType);
      }
      getCapacityCost(errorType) {
        return errorType === "TRANSIENT" ? TIMEOUT_RETRY_COST : RETRY_COST;
      }
      isRetryableError(errorType) {
        return errorType === "THROTTLING" || errorType === "TRANSIENT";
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/AdaptiveRetryStrategy.js
var AdaptiveRetryStrategy;
var init_AdaptiveRetryStrategy = __esm({
  "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/AdaptiveRetryStrategy.js"() {
    "use strict";
    init_config3();
    init_DefaultRateLimiter();
    init_StandardRetryStrategy();
    AdaptiveRetryStrategy = class {
      constructor(maxAttemptsProvider, options) {
        this.maxAttemptsProvider = maxAttemptsProvider;
        this.mode = RETRY_MODES.ADAPTIVE;
        const { rateLimiter } = options ?? {};
        this.rateLimiter = rateLimiter ?? new DefaultRateLimiter();
        this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider);
      }
      async acquireInitialRetryToken(retryTokenScope) {
        await this.rateLimiter.getSendToken();
        return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope);
      }
      async refreshRetryTokenForRetry(tokenToRenew, errorInfo) {
        this.rateLimiter.updateClientSendingRate(errorInfo);
        return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo);
      }
      recordSuccess(token) {
        this.rateLimiter.updateClientSendingRate({});
        this.standardRetryStrategy.recordSuccess(token);
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/ConfiguredRetryStrategy.js
var init_ConfiguredRetryStrategy = __esm({
  "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/ConfiguredRetryStrategy.js"() {
    "use strict";
    init_constants7();
    init_StandardRetryStrategy();
  }
});

// ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/types.js
var init_types8 = __esm({
  "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/types.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/index.js
var init_dist_es36 = __esm({
  "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/index.js"() {
    "use strict";
    init_AdaptiveRetryStrategy();
    init_ConfiguredRetryStrategy();
    init_DefaultRateLimiter();
    init_StandardRetryStrategy();
    init_config3();
    init_constants7();
    init_types8();
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/rng.js
function rng() {
  if (poolPtr > rnds8Pool.length - 16) {
    import_crypto4.default.randomFillSync(rnds8Pool);
    poolPtr = 0;
  }
  return rnds8Pool.slice(poolPtr, poolPtr += 16);
}
var import_crypto4, rnds8Pool, poolPtr;
var init_rng = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/rng.js"() {
    "use strict";
    import_crypto4 = __toESM(require("crypto"));
    rnds8Pool = new Uint8Array(256);
    poolPtr = rnds8Pool.length;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/stringify.js
function unsafeStringify(arr, offset = 0) {
  return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
}
var byteToHex;
var init_stringify = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/stringify.js"() {
    "use strict";
    byteToHex = [];
    for (let i6 = 0; i6 < 256; ++i6) {
      byteToHex.push((i6 + 256).toString(16).slice(1));
    }
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/native.js
var import_crypto5, native_default;
var init_native = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/native.js"() {
    "use strict";
    import_crypto5 = __toESM(require("crypto"));
    native_default = {
      randomUUID: import_crypto5.default.randomUUID
    };
  }
});

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

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/index.js
var init_esm_node = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/index.js"() {
    "use strict";
    init_v4();
  }
});

// ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/defaultRetryQuota.js
var init_defaultRetryQuota = __esm({
  "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/defaultRetryQuota.js"() {
    "use strict";
    init_dist_es36();
  }
});

// ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/delayDecider.js
var init_delayDecider = __esm({
  "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/delayDecider.js"() {
    "use strict";
    init_dist_es36();
  }
});

// ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/retryDecider.js
var init_retryDecider = __esm({
  "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/retryDecider.js"() {
    "use strict";
    init_dist_es35();
  }
});

// ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/util.js
var asSdkError;
var init_util3 = __esm({
  "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/util.js"() {
    "use strict";
    asSdkError = (error2) => {
      if (error2 instanceof Error)
        return error2;
      if (error2 instanceof Object)
        return Object.assign(new Error(), error2);
      if (typeof error2 === "string")
        return new Error(error2);
      return new Error(`AWS SDK error wrapper for ${error2}`);
    };
  }
});

// ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/StandardRetryStrategy.js
var init_StandardRetryStrategy2 = __esm({
  "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/StandardRetryStrategy.js"() {
    "use strict";
    init_dist_es2();
    init_dist_es35();
    init_dist_es36();
    init_defaultRetryQuota();
    init_delayDecider();
    init_retryDecider();
    init_util3();
  }
});

// ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/AdaptiveRetryStrategy.js
var init_AdaptiveRetryStrategy2 = __esm({
  "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/AdaptiveRetryStrategy.js"() {
    "use strict";
    init_dist_es36();
    init_StandardRetryStrategy2();
  }
});

// ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/configurations.js
var ENV_MAX_ATTEMPTS, CONFIG_MAX_ATTEMPTS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, ENV_RETRY_MODE, CONFIG_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS;
var init_configurations2 = __esm({
  "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/configurations.js"() {
    "use strict";
    init_dist_es6();
    init_dist_es36();
    ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS";
    CONFIG_MAX_ATTEMPTS = "max_attempts";
    NODE_MAX_ATTEMPT_CONFIG_OPTIONS = {
      environmentVariableSelector: (env4) => {
        const value = env4[ENV_MAX_ATTEMPTS];
        if (!value)
          return void 0;
        const maxAttempt = parseInt(value);
        if (Number.isNaN(maxAttempt)) {
          throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`);
        }
        return maxAttempt;
      },
      configFileSelector: (profile) => {
        const value = profile[CONFIG_MAX_ATTEMPTS];
        if (!value)
          return void 0;
        const maxAttempt = parseInt(value);
        if (Number.isNaN(maxAttempt)) {
          throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`);
        }
        return maxAttempt;
      },
      default: DEFAULT_MAX_ATTEMPTS
    };
    resolveRetryConfig = (input) => {
      const { retryStrategy, retryMode: _retryMode, maxAttempts: _maxAttempts } = input;
      const maxAttempts = normalizeProvider(_maxAttempts ?? DEFAULT_MAX_ATTEMPTS);
      return Object.assign(input, {
        maxAttempts,
        retryStrategy: async () => {
          if (retryStrategy) {
            return retryStrategy;
          }
          const retryMode = await normalizeProvider(_retryMode)();
          if (retryMode === RETRY_MODES.ADAPTIVE) {
            return new AdaptiveRetryStrategy(maxAttempts);
          }
          return new StandardRetryStrategy(maxAttempts);
        }
      });
    };
    ENV_RETRY_MODE = "AWS_RETRY_MODE";
    CONFIG_RETRY_MODE = "retry_mode";
    NODE_RETRY_MODE_CONFIG_OPTIONS = {
      environmentVariableSelector: (env4) => env4[ENV_RETRY_MODE],
      configFileSelector: (profile) => profile[CONFIG_RETRY_MODE],
      default: DEFAULT_RETRY_MODE
    };
  }
});

// ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/omitRetryHeadersMiddleware.js
var init_omitRetryHeadersMiddleware = __esm({
  "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/omitRetryHeadersMiddleware.js"() {
    "use strict";
    init_dist_es2();
    init_dist_es36();
  }
});

// ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/isStreamingPayload/isStreamingPayload.js
var import_stream6, isStreamingPayload;
var init_isStreamingPayload = __esm({
  "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/isStreamingPayload/isStreamingPayload.js"() {
    "use strict";
    import_stream6 = require("stream");
    isStreamingPayload = (request2) => request2?.body instanceof import_stream6.Readable || typeof ReadableStream !== "undefined" && request2?.body instanceof ReadableStream;
  }
});

// ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/retryMiddleware.js
var retryMiddleware, isRetryStrategyV2, getRetryErrorInfo, getRetryErrorType, retryMiddlewareOptions, getRetryPlugin, getRetryAfterHint;
var init_retryMiddleware = __esm({
  "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/retryMiddleware.js"() {
    "use strict";
    init_dist_es2();
    init_dist_es35();
    init_dist_es24();
    init_dist_es36();
    init_esm_node();
    init_isStreamingPayload();
    init_util3();
    retryMiddleware = (options) => (next, context) => async (args) => {
      let retryStrategy = await options.retryStrategy();
      const maxAttempts = await options.maxAttempts();
      if (isRetryStrategyV2(retryStrategy)) {
        retryStrategy = retryStrategy;
        let retryToken = await retryStrategy.acquireInitialRetryToken(context["partition_id"]);
        let lastError = new Error();
        let attempts = 0;
        let totalRetryDelay = 0;
        const { request: request2 } = args;
        const isRequest2 = HttpRequest.isInstance(request2);
        if (isRequest2) {
          request2.headers[INVOCATION_ID_HEADER] = v4_default();
        }
        while (true) {
          try {
            if (isRequest2) {
              request2.headers[REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`;
            }
            const { response, output } = await next(args);
            retryStrategy.recordSuccess(retryToken);
            output.$metadata.attempts = attempts + 1;
            output.$metadata.totalRetryDelay = totalRetryDelay;
            return { response, output };
          } catch (e6) {
            const retryErrorInfo = getRetryErrorInfo(e6);
            lastError = asSdkError(e6);
            if (isRequest2 && isStreamingPayload(request2)) {
              (context.logger instanceof NoOpLogger ? console : context.logger)?.warn("An error was encountered in a non-retryable streaming request.");
              throw lastError;
            }
            try {
              retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo);
            } catch (refreshError) {
              if (!lastError.$metadata) {
                lastError.$metadata = {};
              }
              lastError.$metadata.attempts = attempts + 1;
              lastError.$metadata.totalRetryDelay = totalRetryDelay;
              throw lastError;
            }
            attempts = retryToken.getRetryCount();
            const delay = retryToken.getRetryDelay();
            totalRetryDelay += delay;
            await new Promise((resolve) => setTimeout(resolve, delay));
          }
        }
      } else {
        retryStrategy = retryStrategy;
        if (retryStrategy?.mode)
          context.userAgent = [...context.userAgent || [], ["cfg/retry-mode", retryStrategy.mode]];
        return retryStrategy.retry(next, args);
      }
    };
    isRetryStrategyV2 = (retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined";
    getRetryErrorInfo = (error2) => {
      const errorInfo = {
        error: error2,
        errorType: getRetryErrorType(error2)
      };
      const retryAfterHint = getRetryAfterHint(error2.$response);
      if (retryAfterHint) {
        errorInfo.retryAfterHint = retryAfterHint;
      }
      return errorInfo;
    };
    getRetryErrorType = (error2) => {
      if (isThrottlingError(error2))
        return "THROTTLING";
      if (isTransientError(error2))
        return "TRANSIENT";
      if (isServerError(error2))
        return "SERVER_ERROR";
      return "CLIENT_ERROR";
    };
    retryMiddlewareOptions = {
      name: "retryMiddleware",
      tags: ["RETRY"],
      step: "finalizeRequest",
      priority: "high",
      override: true
    };
    getRetryPlugin = (options) => ({
      applyToStack: (clientStack) => {
        clientStack.add(retryMiddleware(options), retryMiddlewareOptions);
      }
    });
    getRetryAfterHint = (response) => {
      if (!HttpResponse.isInstance(response))
        return;
      const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after");
      if (!retryAfterHeaderName)
        return;
      const retryAfter = response.headers[retryAfterHeaderName];
      const retryAfterSeconds = Number(retryAfter);
      if (!Number.isNaN(retryAfterSeconds))
        return new Date(retryAfterSeconds * 1e3);
      const retryAfterDate = new Date(retryAfter);
      return retryAfterDate;
    };
  }
});

// ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/index.js
var init_dist_es37 = __esm({
  "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/index.js"() {
    "use strict";
    init_AdaptiveRetryStrategy2();
    init_StandardRetryStrategy2();
    init_configurations2();
    init_delayDecider();
    init_omitRetryHeadersMiddleware();
    init_retryDecider();
    init_retryMiddleware();
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/auth/httpAuthSchemeProvider.js
function createAwsAuthSigv4HttpAuthOption(authParameters) {
  return {
    schemeId: "aws.auth#sigv4",
    signingProperties: {
      name: "rds-data",
      region: authParameters.region
    },
    propertiesExtractor: (config, context) => ({
      signingProperties: {
        config,
        context
      }
    })
  };
}
var defaultRDSDataHttpAuthSchemeParametersProvider, defaultRDSDataHttpAuthSchemeProvider, resolveHttpAuthSchemeConfig;
var init_httpAuthSchemeProvider = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/auth/httpAuthSchemeProvider.js"() {
    "use strict";
    init_dist_es25();
    init_dist_es6();
    defaultRDSDataHttpAuthSchemeParametersProvider = async (config, context, input) => {
      return {
        operation: getSmithyContext(context).operation,
        region: await normalizeProvider(config.region)() || (() => {
          throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
        })()
      };
    };
    defaultRDSDataHttpAuthSchemeProvider = (authParameters) => {
      const options = [];
      switch (authParameters.operation) {
        default: {
          options.push(createAwsAuthSigv4HttpAuthOption(authParameters));
        }
      }
      return options;
    };
    resolveHttpAuthSchemeConfig = (config) => {
      const config_0 = resolveAwsSdkSigV4Config(config);
      return Object.assign(config_0, {
        authSchemePreference: normalizeProvider(config.authSchemePreference ?? [])
      });
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/endpoint/EndpointParameters.js
var resolveClientEndpointParameters, commonParams;
var init_EndpointParameters = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/endpoint/EndpointParameters.js"() {
    "use strict";
    resolveClientEndpointParameters = (options) => {
      return Object.assign(options, {
        useDualstackEndpoint: options.useDualstackEndpoint ?? false,
        useFipsEndpoint: options.useFipsEndpoint ?? false,
        defaultSigningName: "rds-data"
      });
    };
    commonParams = {
      UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
      Endpoint: { type: "builtInParams", name: "endpoint" },
      Region: { type: "builtInParams", name: "region" },
      UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/package.json
var package_default;
var init_package = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/package.json"() {
    package_default = {
      name: "@aws-sdk/client-rds-data",
      description: "AWS SDK for JavaScript Rds Data Client for Node.js, Browser and React Native",
      version: "3.817.0",
      scripts: {
        build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
        "build:cjs": "node ../../scripts/compilation/inline client-rds-data",
        "build:es": "tsc -p tsconfig.es.json",
        "build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
        "build:types": "tsc -p tsconfig.types.json",
        "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
        clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
        "extract:docs": "api-extractor run --local",
        "generate:client": "node ../../scripts/generate-clients/single-service --solo rds-data"
      },
      main: "./dist-cjs/index.js",
      types: "./dist-types/index.d.ts",
      module: "./dist-es/index.js",
      sideEffects: false,
      dependencies: {
        "@aws-crypto/sha256-browser": "5.2.0",
        "@aws-crypto/sha256-js": "5.2.0",
        "@aws-sdk/core": "3.816.0",
        "@aws-sdk/credential-provider-node": "3.817.0",
        "@aws-sdk/middleware-host-header": "3.804.0",
        "@aws-sdk/middleware-logger": "3.804.0",
        "@aws-sdk/middleware-recursion-detection": "3.804.0",
        "@aws-sdk/middleware-user-agent": "3.816.0",
        "@aws-sdk/region-config-resolver": "3.808.0",
        "@aws-sdk/types": "3.804.0",
        "@aws-sdk/util-endpoints": "3.808.0",
        "@aws-sdk/util-user-agent-browser": "3.804.0",
        "@aws-sdk/util-user-agent-node": "3.816.0",
        "@smithy/config-resolver": "^4.1.2",
        "@smithy/core": "^3.3.3",
        "@smithy/fetch-http-handler": "^5.0.2",
        "@smithy/hash-node": "^4.0.2",
        "@smithy/invalid-dependency": "^4.0.2",
        "@smithy/middleware-content-length": "^4.0.2",
        "@smithy/middleware-endpoint": "^4.1.6",
        "@smithy/middleware-retry": "^4.1.7",
        "@smithy/middleware-serde": "^4.0.5",
        "@smithy/middleware-stack": "^4.0.2",
        "@smithy/node-config-provider": "^4.1.1",
        "@smithy/node-http-handler": "^4.0.4",
        "@smithy/protocol-http": "^5.1.0",
        "@smithy/smithy-client": "^4.2.6",
        "@smithy/types": "^4.2.0",
        "@smithy/url-parser": "^4.0.2",
        "@smithy/util-base64": "^4.0.0",
        "@smithy/util-body-length-browser": "^4.0.0",
        "@smithy/util-body-length-node": "^4.0.0",
        "@smithy/util-defaults-mode-browser": "^4.0.14",
        "@smithy/util-defaults-mode-node": "^4.0.14",
        "@smithy/util-endpoints": "^3.0.4",
        "@smithy/util-middleware": "^4.0.2",
        "@smithy/util-retry": "^4.0.3",
        "@smithy/util-utf8": "^4.0.0",
        tslib: "^2.6.2"
      },
      devDependencies: {
        "@tsconfig/node18": "18.2.4",
        "@types/node": "^18.19.69",
        concurrently: "7.0.0",
        "downlevel-dts": "0.10.1",
        rimraf: "3.0.2",
        typescript: "~5.8.3"
      },
      engines: {
        node: ">=18.0.0"
      },
      typesVersions: {
        "<4.0": {
          "dist-types/*": [
            "dist-types/ts3.4/*"
          ]
        }
      },
      files: [
        "dist-*/**"
      ],
      author: {
        name: "AWS SDK for JavaScript Team",
        url: "https://aws.amazon.com/javascript/"
      },
      license: "Apache-2.0",
      browser: {
        "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser"
      },
      "react-native": {
        "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native"
      },
      homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-rds-data",
      repository: {
        type: "git",
        url: "https://github.com/aws/aws-sdk-js-v3.git",
        directory: "clients/client-rds-data"
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.816.0/node_modules/@aws-sdk/credential-provider-env/dist-es/fromEnv.js
var ENV_KEY, ENV_SECRET, ENV_SESSION, ENV_EXPIRATION, ENV_CREDENTIAL_SCOPE, ENV_ACCOUNT_ID, fromEnv2;
var init_fromEnv2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.816.0/node_modules/@aws-sdk/credential-provider-env/dist-es/fromEnv.js"() {
    "use strict";
    init_client2();
    init_dist_es21();
    ENV_KEY = "AWS_ACCESS_KEY_ID";
    ENV_SECRET = "AWS_SECRET_ACCESS_KEY";
    ENV_SESSION = "AWS_SESSION_TOKEN";
    ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION";
    ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE";
    ENV_ACCOUNT_ID = "AWS_ACCOUNT_ID";
    fromEnv2 = (init2) => async () => {
      init2?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv");
      const accessKeyId = process.env[ENV_KEY];
      const secretAccessKey = process.env[ENV_SECRET];
      const sessionToken = process.env[ENV_SESSION];
      const expiry = process.env[ENV_EXPIRATION];
      const credentialScope = process.env[ENV_CREDENTIAL_SCOPE];
      const accountId = process.env[ENV_ACCOUNT_ID];
      if (accessKeyId && secretAccessKey) {
        const credentials2 = {
          accessKeyId,
          secretAccessKey,
          ...sessionToken && { sessionToken },
          ...expiry && { expiration: new Date(expiry) },
          ...credentialScope && { credentialScope },
          ...accountId && { accountId }
        };
        setCredentialFeature(credentials2, "CREDENTIALS_ENV_VARS", "g");
        return credentials2;
      }
      throw new CredentialsProviderError("Unable to find environment variable credentials.", { logger: init2?.logger });
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.816.0/node_modules/@aws-sdk/credential-provider-env/dist-es/index.js
var dist_es_exports = {};
__export(dist_es_exports, {
  ENV_ACCOUNT_ID: () => ENV_ACCOUNT_ID,
  ENV_CREDENTIAL_SCOPE: () => ENV_CREDENTIAL_SCOPE,
  ENV_EXPIRATION: () => ENV_EXPIRATION,
  ENV_KEY: () => ENV_KEY,
  ENV_SECRET: () => ENV_SECRET,
  ENV_SESSION: () => ENV_SESSION,
  fromEnv: () => fromEnv2
});
var init_dist_es38 = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.816.0/node_modules/@aws-sdk/credential-provider-env/dist-es/index.js"() {
    "use strict";
    init_fromEnv2();
  }
});

// ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/httpRequest.js
function httpRequest(options) {
  return new Promise((resolve, reject) => {
    const req = (0, import_http4.request)({
      method: "GET",
      ...options,
      hostname: options.hostname?.replace(/^\[(.+)\]$/, "$1")
    });
    req.on("error", (err2) => {
      reject(Object.assign(new ProviderError("Unable to connect to instance metadata service"), err2));
      req.destroy();
    });
    req.on("timeout", () => {
      reject(new ProviderError("TimeoutError from instance metadata service"));
      req.destroy();
    });
    req.on("response", (res) => {
      const { statusCode = 400 } = res;
      if (statusCode < 200 || 300 <= statusCode) {
        reject(Object.assign(new ProviderError("Error response received from instance metadata service"), { statusCode }));
        req.destroy();
      }
      const chunks = [];
      res.on("data", (chunk) => {
        chunks.push(chunk);
      });
      res.on("end", () => {
        resolve(import_buffer3.Buffer.concat(chunks));
        req.destroy();
      });
    });
    req.end();
  });
}
var import_buffer3, import_http4;
var init_httpRequest2 = __esm({
  "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/httpRequest.js"() {
    "use strict";
    init_dist_es21();
    import_buffer3 = require("buffer");
    import_http4 = require("http");
  }
});

// ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/ImdsCredentials.js
var isImdsCredentials, fromImdsCredentials;
var init_ImdsCredentials = __esm({
  "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/ImdsCredentials.js"() {
    "use strict";
    isImdsCredentials = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.AccessKeyId === "string" && typeof arg.SecretAccessKey === "string" && typeof arg.Token === "string" && typeof arg.Expiration === "string";
    fromImdsCredentials = (creds) => ({
      accessKeyId: creds.AccessKeyId,
      secretAccessKey: creds.SecretAccessKey,
      sessionToken: creds.Token,
      expiration: new Date(creds.Expiration),
      ...creds.AccountId && { accountId: creds.AccountId }
    });
  }
});

// ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/RemoteProviderInit.js
var DEFAULT_TIMEOUT, DEFAULT_MAX_RETRIES, providerConfigFromInit;
var init_RemoteProviderInit = __esm({
  "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/RemoteProviderInit.js"() {
    "use strict";
    DEFAULT_TIMEOUT = 1e3;
    DEFAULT_MAX_RETRIES = 0;
    providerConfigFromInit = ({ maxRetries = DEFAULT_MAX_RETRIES, timeout = DEFAULT_TIMEOUT }) => ({ maxRetries, timeout });
  }
});

// ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/retry.js
var retry;
var init_retry3 = __esm({
  "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/retry.js"() {
    "use strict";
    retry = (toRetry, maxRetries) => {
      let promise = toRetry();
      for (let i6 = 0; i6 < maxRetries; i6++) {
        promise = promise.catch(toRetry);
      }
      return promise;
    };
  }
});

// ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/fromContainerMetadata.js
var import_url8, ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, ENV_CMDS_AUTH_TOKEN, fromContainerMetadata, requestFromEcsImds, CMDS_IP, GREENGRASS_HOSTS, GREENGRASS_PROTOCOLS, getCmdsUri;
var init_fromContainerMetadata = __esm({
  "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/fromContainerMetadata.js"() {
    "use strict";
    init_dist_es21();
    import_url8 = require("url");
    init_httpRequest2();
    init_ImdsCredentials();
    init_RemoteProviderInit();
    init_retry3();
    ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI";
    ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI";
    ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN";
    fromContainerMetadata = (init2 = {}) => {
      const { timeout, maxRetries } = providerConfigFromInit(init2);
      return () => retry(async () => {
        const requestOptions = await getCmdsUri({ logger: init2.logger });
        const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions));
        if (!isImdsCredentials(credsResponse)) {
          throw new CredentialsProviderError("Invalid response received from instance metadata service.", {
            logger: init2.logger
          });
        }
        return fromImdsCredentials(credsResponse);
      }, maxRetries);
    };
    requestFromEcsImds = async (timeout, options) => {
      if (process.env[ENV_CMDS_AUTH_TOKEN]) {
        options.headers = {
          ...options.headers,
          Authorization: process.env[ENV_CMDS_AUTH_TOKEN]
        };
      }
      const buffer = await httpRequest({
        ...options,
        timeout
      });
      return buffer.toString();
    };
    CMDS_IP = "169.254.170.2";
    GREENGRASS_HOSTS = {
      localhost: true,
      "127.0.0.1": true
    };
    GREENGRASS_PROTOCOLS = {
      "http:": true,
      "https:": true
    };
    getCmdsUri = async ({ logger: logger2 }) => {
      if (process.env[ENV_CMDS_RELATIVE_URI]) {
        return {
          hostname: CMDS_IP,
          path: process.env[ENV_CMDS_RELATIVE_URI]
        };
      }
      if (process.env[ENV_CMDS_FULL_URI]) {
        const parsed = (0, import_url8.parse)(process.env[ENV_CMDS_FULL_URI]);
        if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) {
          throw new CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, {
            tryNextLink: false,
            logger: logger2
          });
        }
        if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) {
          throw new CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, {
            tryNextLink: false,
            logger: logger2
          });
        }
        return {
          ...parsed,
          port: parsed.port ? parseInt(parsed.port, 10) : void 0
        };
      }
      throw new CredentialsProviderError(`The container metadata credential provider cannot be used unless the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment variable is set`, {
        tryNextLink: false,
        logger: logger2
      });
    };
  }
});

// ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/error/InstanceMetadataV1FallbackError.js
var InstanceMetadataV1FallbackError;
var init_InstanceMetadataV1FallbackError = __esm({
  "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/error/InstanceMetadataV1FallbackError.js"() {
    "use strict";
    init_dist_es21();
    InstanceMetadataV1FallbackError = class _InstanceMetadataV1FallbackError extends CredentialsProviderError {
      constructor(message, tryNextLink = true) {
        super(message, tryNextLink);
        this.tryNextLink = tryNextLink;
        this.name = "InstanceMetadataV1FallbackError";
        Object.setPrototypeOf(this, _InstanceMetadataV1FallbackError.prototype);
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/Endpoint.js
var Endpoint;
var init_Endpoint = __esm({
  "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/Endpoint.js"() {
    "use strict";
    (function(Endpoint2) {
      Endpoint2["IPv4"] = "http://169.254.169.254";
      Endpoint2["IPv6"] = "http://[fd00:ec2::254]";
    })(Endpoint || (Endpoint = {}));
  }
});

// ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointConfigOptions.js
var ENV_ENDPOINT_NAME, CONFIG_ENDPOINT_NAME, ENDPOINT_CONFIG_OPTIONS;
var init_EndpointConfigOptions = __esm({
  "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointConfigOptions.js"() {
    "use strict";
    ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT";
    CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint";
    ENDPOINT_CONFIG_OPTIONS = {
      environmentVariableSelector: (env4) => env4[ENV_ENDPOINT_NAME],
      configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME],
      default: void 0
    };
  }
});

// ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointMode.js
var EndpointMode;
var init_EndpointMode = __esm({
  "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointMode.js"() {
    "use strict";
    (function(EndpointMode2) {
      EndpointMode2["IPv4"] = "IPv4";
      EndpointMode2["IPv6"] = "IPv6";
    })(EndpointMode || (EndpointMode = {}));
  }
});

// ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointModeConfigOptions.js
var ENV_ENDPOINT_MODE_NAME, CONFIG_ENDPOINT_MODE_NAME, ENDPOINT_MODE_CONFIG_OPTIONS;
var init_EndpointModeConfigOptions = __esm({
  "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointModeConfigOptions.js"() {
    "use strict";
    init_EndpointMode();
    ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE";
    CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode";
    ENDPOINT_MODE_CONFIG_OPTIONS = {
      environmentVariableSelector: (env4) => env4[ENV_ENDPOINT_MODE_NAME],
      configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME],
      default: EndpointMode.IPv4
    };
  }
});

// ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/utils/getInstanceMetadataEndpoint.js
var getInstanceMetadataEndpoint, getFromEndpointConfig, getFromEndpointModeConfig;
var init_getInstanceMetadataEndpoint = __esm({
  "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/utils/getInstanceMetadataEndpoint.js"() {
    "use strict";
    init_dist_es31();
    init_dist_es33();
    init_Endpoint();
    init_EndpointConfigOptions();
    init_EndpointMode();
    init_EndpointModeConfigOptions();
    getInstanceMetadataEndpoint = async () => parseUrl(await getFromEndpointConfig() || await getFromEndpointModeConfig());
    getFromEndpointConfig = async () => loadConfig(ENDPOINT_CONFIG_OPTIONS)();
    getFromEndpointModeConfig = async () => {
      const endpointMode = await loadConfig(ENDPOINT_MODE_CONFIG_OPTIONS)();
      switch (endpointMode) {
        case EndpointMode.IPv4:
          return Endpoint.IPv4;
        case EndpointMode.IPv6:
          return Endpoint.IPv6;
        default:
          throw new Error(`Unsupported endpoint mode: ${endpointMode}. Select from ${Object.values(EndpointMode)}`);
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/utils/getExtendedInstanceMetadataCredentials.js
var STATIC_STABILITY_REFRESH_INTERVAL_SECONDS, STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS, STATIC_STABILITY_DOC_URL, getExtendedInstanceMetadataCredentials;
var init_getExtendedInstanceMetadataCredentials = __esm({
  "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/utils/getExtendedInstanceMetadataCredentials.js"() {
    "use strict";
    STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60;
    STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60;
    STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html";
    getExtendedInstanceMetadataCredentials = (credentials2, logger2) => {
      const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS + Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS);
      const newExpiration = new Date(Date.now() + refreshInterval * 1e3);
      logger2.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(newExpiration)}.
For more information, please visit: ` + STATIC_STABILITY_DOC_URL);
      const originalExpiration = credentials2.originalExpiration ?? credentials2.expiration;
      return {
        ...credentials2,
        ...originalExpiration ? { originalExpiration } : {},
        expiration: newExpiration
      };
    };
  }
});

// ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/utils/staticStabilityProvider.js
var staticStabilityProvider;
var init_staticStabilityProvider = __esm({
  "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/utils/staticStabilityProvider.js"() {
    "use strict";
    init_getExtendedInstanceMetadataCredentials();
    staticStabilityProvider = (provider, options = {}) => {
      const logger2 = options?.logger || console;
      let pastCredentials;
      return async () => {
        let credentials2;
        try {
          credentials2 = await provider();
          if (credentials2.expiration && credentials2.expiration.getTime() < Date.now()) {
            credentials2 = getExtendedInstanceMetadataCredentials(credentials2, logger2);
          }
        } catch (e6) {
          if (pastCredentials) {
            logger2.warn("Credential renew failed: ", e6);
            credentials2 = getExtendedInstanceMetadataCredentials(pastCredentials, logger2);
          } else {
            throw e6;
          }
        }
        pastCredentials = credentials2;
        return credentials2;
      };
    };
  }
});

// ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/fromInstanceMetadata.js
var IMDS_PATH, IMDS_TOKEN_PATH, AWS_EC2_METADATA_V1_DISABLED, PROFILE_AWS_EC2_METADATA_V1_DISABLED, X_AWS_EC2_METADATA_TOKEN, fromInstanceMetadata, getInstanceMetadataProvider, getMetadataToken, getProfile, getCredentialsFromProfile;
var init_fromInstanceMetadata = __esm({
  "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/fromInstanceMetadata.js"() {
    "use strict";
    init_dist_es31();
    init_dist_es21();
    init_InstanceMetadataV1FallbackError();
    init_httpRequest2();
    init_ImdsCredentials();
    init_RemoteProviderInit();
    init_retry3();
    init_getInstanceMetadataEndpoint();
    init_staticStabilityProvider();
    IMDS_PATH = "/latest/meta-data/iam/security-credentials/";
    IMDS_TOKEN_PATH = "/latest/api/token";
    AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED";
    PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled";
    X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token";
    fromInstanceMetadata = (init2 = {}) => staticStabilityProvider(getInstanceMetadataProvider(init2), { logger: init2.logger });
    getInstanceMetadataProvider = (init2 = {}) => {
      let disableFetchToken = false;
      const { logger: logger2, profile } = init2;
      const { timeout, maxRetries } = providerConfigFromInit(init2);
      const getCredentials2 = async (maxRetries2, options) => {
        const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null;
        if (isImdsV1Fallback) {
          let fallbackBlockedFromProfile = false;
          let fallbackBlockedFromProcessEnv = false;
          const configValue = await loadConfig({
            environmentVariableSelector: (env4) => {
              const envValue = env4[AWS_EC2_METADATA_V1_DISABLED];
              fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false";
              if (envValue === void 0) {
                throw new CredentialsProviderError(`${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, { logger: init2.logger });
              }
              return fallbackBlockedFromProcessEnv;
            },
            configFileSelector: (profile2) => {
              const profileValue = profile2[PROFILE_AWS_EC2_METADATA_V1_DISABLED];
              fallbackBlockedFromProfile = !!profileValue && profileValue !== "false";
              return fallbackBlockedFromProfile;
            },
            default: false
          }, {
            profile
          })();
          if (init2.ec2MetadataV1Disabled || configValue) {
            const causes = [];
            if (init2.ec2MetadataV1Disabled)
              causes.push("credential provider initialization (runtime option ec2MetadataV1Disabled)");
            if (fallbackBlockedFromProfile)
              causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`);
            if (fallbackBlockedFromProcessEnv)
              causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`);
            throw new InstanceMetadataV1FallbackError(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join(", ")}].`);
          }
        }
        const imdsProfile = (await retry(async () => {
          let profile2;
          try {
            profile2 = await getProfile(options);
          } catch (err2) {
            if (err2.statusCode === 401) {
              disableFetchToken = false;
            }
            throw err2;
          }
          return profile2;
        }, maxRetries2)).trim();
        return retry(async () => {
          let creds;
          try {
            creds = await getCredentialsFromProfile(imdsProfile, options, init2);
          } catch (err2) {
            if (err2.statusCode === 401) {
              disableFetchToken = false;
            }
            throw err2;
          }
          return creds;
        }, maxRetries2);
      };
      return async () => {
        const endpoint = await getInstanceMetadataEndpoint();
        if (disableFetchToken) {
          logger2?.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)");
          return getCredentials2(maxRetries, { ...endpoint, timeout });
        } else {
          let token;
          try {
            token = (await getMetadataToken({ ...endpoint, timeout })).toString();
          } catch (error2) {
            if (error2?.statusCode === 400) {
              throw Object.assign(error2, {
                message: "EC2 Metadata token request returned error"
              });
            } else if (error2.message === "TimeoutError" || [403, 404, 405].includes(error2.statusCode)) {
              disableFetchToken = true;
            }
            logger2?.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)");
            return getCredentials2(maxRetries, { ...endpoint, timeout });
          }
          return getCredentials2(maxRetries, {
            ...endpoint,
            headers: {
              [X_AWS_EC2_METADATA_TOKEN]: token
            },
            timeout
          });
        }
      };
    };
    getMetadataToken = async (options) => httpRequest({
      ...options,
      path: IMDS_TOKEN_PATH,
      method: "PUT",
      headers: {
        "x-aws-ec2-metadata-token-ttl-seconds": "21600"
      }
    });
    getProfile = async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString();
    getCredentialsFromProfile = async (profile, options, init2) => {
      const credentialsResponse = JSON.parse((await httpRequest({
        ...options,
        path: IMDS_PATH + profile
      })).toString());
      if (!isImdsCredentials(credentialsResponse)) {
        throw new CredentialsProviderError("Invalid response received from instance metadata service.", {
          logger: init2.logger
        });
      }
      return fromImdsCredentials(credentialsResponse);
    };
  }
});

// ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/types.js
var init_types9 = __esm({
  "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/types.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/index.js
var dist_es_exports2 = {};
__export(dist_es_exports2, {
  DEFAULT_MAX_RETRIES: () => DEFAULT_MAX_RETRIES,
  DEFAULT_TIMEOUT: () => DEFAULT_TIMEOUT,
  ENV_CMDS_AUTH_TOKEN: () => ENV_CMDS_AUTH_TOKEN,
  ENV_CMDS_FULL_URI: () => ENV_CMDS_FULL_URI,
  ENV_CMDS_RELATIVE_URI: () => ENV_CMDS_RELATIVE_URI,
  Endpoint: () => Endpoint,
  fromContainerMetadata: () => fromContainerMetadata,
  fromInstanceMetadata: () => fromInstanceMetadata,
  getInstanceMetadataEndpoint: () => getInstanceMetadataEndpoint,
  httpRequest: () => httpRequest,
  providerConfigFromInit: () => providerConfigFromInit
});
var init_dist_es39 = __esm({
  "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/index.js"() {
    "use strict";
    init_fromContainerMetadata();
    init_fromInstanceMetadata();
    init_RemoteProviderInit();
    init_types9();
    init_httpRequest2();
    init_getInstanceMetadataEndpoint();
    init_Endpoint();
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/checkUrl.js
var ECS_CONTAINER_HOST, EKS_CONTAINER_HOST_IPv4, EKS_CONTAINER_HOST_IPv6, checkUrl;
var init_checkUrl = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/checkUrl.js"() {
    "use strict";
    init_dist_es21();
    ECS_CONTAINER_HOST = "169.254.170.2";
    EKS_CONTAINER_HOST_IPv4 = "169.254.170.23";
    EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]";
    checkUrl = (url, logger2) => {
      if (url.protocol === "https:") {
        return;
      }
      if (url.hostname === ECS_CONTAINER_HOST || url.hostname === EKS_CONTAINER_HOST_IPv4 || url.hostname === EKS_CONTAINER_HOST_IPv6) {
        return;
      }
      if (url.hostname.includes("[")) {
        if (url.hostname === "[::1]" || url.hostname === "[0000:0000:0000:0000:0000:0000:0000:0001]") {
          return;
        }
      } else {
        if (url.hostname === "localhost") {
          return;
        }
        const ipComponents = url.hostname.split(".");
        const inRange = (component) => {
          const num = parseInt(component, 10);
          return 0 <= num && num <= 255;
        };
        if (ipComponents[0] === "127" && inRange(ipComponents[1]) && inRange(ipComponents[2]) && inRange(ipComponents[3]) && ipComponents.length === 4) {
          return;
        }
      }
      throw new CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following:
  - loopback CIDR 127.0.0.0/8 or [::1/128]
  - ECS container host 169.254.170.2
  - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger: logger2 });
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/requestHelpers.js
function createGetRequest(url) {
  return new HttpRequest({
    protocol: url.protocol,
    hostname: url.hostname,
    port: Number(url.port),
    path: url.pathname,
    query: Array.from(url.searchParams.entries()).reduce((acc, [k5, v6]) => {
      acc[k5] = v6;
      return acc;
    }, {}),
    fragment: url.hash
  });
}
async function getCredentials(response, logger2) {
  const stream = sdkStreamMixin2(response.body);
  const str = await stream.transformToString();
  if (response.statusCode === 200) {
    const parsed = JSON.parse(str);
    if (typeof parsed.AccessKeyId !== "string" || typeof parsed.SecretAccessKey !== "string" || typeof parsed.Token !== "string" || typeof parsed.Expiration !== "string") {
      throw new CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: { AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger: logger2 });
    }
    return {
      accessKeyId: parsed.AccessKeyId,
      secretAccessKey: parsed.SecretAccessKey,
      sessionToken: parsed.Token,
      expiration: parseRfc3339DateTime(parsed.Expiration)
    };
  }
  if (response.statusCode >= 400 && response.statusCode < 500) {
    let parsedBody = {};
    try {
      parsedBody = JSON.parse(str);
    } catch (e6) {
    }
    throw Object.assign(new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger: logger2 }), {
      Code: parsedBody.Code,
      Message: parsedBody.Message
    });
  }
  throw new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger: logger2 });
}
var init_requestHelpers = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/requestHelpers.js"() {
    "use strict";
    init_dist_es21();
    init_dist_es2();
    init_dist_es24();
    init_dist_es17();
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/retry-wrapper.js
var retryWrapper;
var init_retry_wrapper = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/retry-wrapper.js"() {
    "use strict";
    retryWrapper = (toRetry, maxRetries, delayMs) => {
      return async () => {
        for (let i6 = 0; i6 < maxRetries; ++i6) {
          try {
            return await toRetry();
          } catch (e6) {
            await new Promise((resolve) => setTimeout(resolve, delayMs));
          }
        }
        return await toRetry();
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/fromHttp.js
var import_promises2, AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, DEFAULT_LINK_LOCAL_HOST, AWS_CONTAINER_CREDENTIALS_FULL_URI, AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE, AWS_CONTAINER_AUTHORIZATION_TOKEN, fromHttp;
var init_fromHttp = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/fromHttp.js"() {
    "use strict";
    init_client2();
    init_dist_es14();
    init_dist_es21();
    import_promises2 = __toESM(require("fs/promises"));
    init_checkUrl();
    init_requestHelpers();
    init_retry_wrapper();
    AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI";
    DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2";
    AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI";
    AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE";
    AWS_CONTAINER_AUTHORIZATION_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN";
    fromHttp = (options = {}) => {
      options.logger?.debug("@aws-sdk/credential-provider-http - fromHttp");
      let host;
      const relative = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI];
      const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI];
      const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN];
      const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE];
      const warn = options.logger?.constructor?.name === "NoOpLogger" || !options.logger ? console.warn : options.logger.warn;
      if (relative && full) {
        warn("@aws-sdk/credential-provider-http: you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri.");
        warn("awsContainerCredentialsFullUri will take precedence.");
      }
      if (token && tokenFile) {
        warn("@aws-sdk/credential-provider-http: you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile.");
        warn("awsContainerAuthorizationToken will take precedence.");
      }
      if (full) {
        host = full;
      } else if (relative) {
        host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`;
      } else {
        throw new CredentialsProviderError(`No HTTP credential provider host provided.
Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger });
      }
      const url = new URL(host);
      checkUrl(url, options.logger);
      const requestHandler = new NodeHttpHandler({
        requestTimeout: options.timeout ?? 1e3,
        connectionTimeout: options.timeout ?? 1e3
      });
      return retryWrapper(async () => {
        const request2 = createGetRequest(url);
        if (token) {
          request2.headers.Authorization = token;
        } else if (tokenFile) {
          request2.headers.Authorization = (await import_promises2.default.readFile(tokenFile)).toString();
        }
        try {
          const result = await requestHandler.handle(request2);
          return getCredentials(result.response).then((creds) => setCredentialFeature(creds, "CREDENTIALS_HTTP", "z"));
        } catch (e6) {
          throw new CredentialsProviderError(String(e6), { logger: options.logger });
        }
      }, options.maxRetries ?? 3, options.timeout ?? 1e3);
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/index.js
var dist_es_exports3 = {};
__export(dist_es_exports3, {
  fromHttp: () => fromHttp
});
var init_dist_es40 = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/index.js"() {
    "use strict";
    init_fromHttp();
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.817.0/node_modules/@aws-sdk/credential-provider-node/dist-es/remoteProvider.js
var ENV_IMDS_DISABLED, remoteProvider;
var init_remoteProvider = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.817.0/node_modules/@aws-sdk/credential-provider-node/dist-es/remoteProvider.js"() {
    "use strict";
    init_dist_es21();
    ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED";
    remoteProvider = async (init2) => {
      const { ENV_CMDS_FULL_URI: ENV_CMDS_FULL_URI2, ENV_CMDS_RELATIVE_URI: ENV_CMDS_RELATIVE_URI2, fromContainerMetadata: fromContainerMetadata2, fromInstanceMetadata: fromInstanceMetadata2 } = await Promise.resolve().then(() => (init_dist_es39(), dist_es_exports2));
      if (process.env[ENV_CMDS_RELATIVE_URI2] || process.env[ENV_CMDS_FULL_URI2]) {
        init2.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata");
        const { fromHttp: fromHttp2 } = await Promise.resolve().then(() => (init_dist_es40(), dist_es_exports3));
        return chain(fromHttp2(init2), fromContainerMetadata2(init2));
      }
      if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") {
        return async () => {
          throw new CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init2.logger });
        };
      }
      init2.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata");
      return fromInstanceMetadata2(init2);
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/isSsoProfile.js
var isSsoProfile;
var init_isSsoProfile = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/isSsoProfile.js"() {
    "use strict";
    isSsoProfile = (arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string");
  }
});

// ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/fromEnvSigningName.js
var init_fromEnvSigningName = __esm({
  "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/fromEnvSigningName.js"() {
    "use strict";
    init_dist_es21();
  }
});

// ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/constants.js
var EXPIRE_WINDOW_MS, REFRESH_MESSAGE;
var init_constants8 = __esm({
  "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/constants.js"() {
    "use strict";
    EXPIRE_WINDOW_MS = 5 * 60 * 1e3;
    REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`;
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthSchemeProvider.js
function createAwsAuthSigv4HttpAuthOption2(authParameters) {
  return {
    schemeId: "aws.auth#sigv4",
    signingProperties: {
      name: "sso-oauth",
      region: authParameters.region
    },
    propertiesExtractor: (config, context) => ({
      signingProperties: {
        config,
        context
      }
    })
  };
}
function createSmithyApiNoAuthHttpAuthOption(authParameters) {
  return {
    schemeId: "smithy.api#noAuth"
  };
}
var defaultSSOOIDCHttpAuthSchemeParametersProvider, defaultSSOOIDCHttpAuthSchemeProvider, resolveHttpAuthSchemeConfig2;
var init_httpAuthSchemeProvider2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthSchemeProvider.js"() {
    "use strict";
    init_dist_es25();
    init_dist_es6();
    defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => {
      return {
        operation: getSmithyContext(context).operation,
        region: await normalizeProvider(config.region)() || (() => {
          throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
        })()
      };
    };
    defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => {
      const options = [];
      switch (authParameters.operation) {
        case "CreateToken": {
          options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
          break;
        }
        default: {
          options.push(createAwsAuthSigv4HttpAuthOption2(authParameters));
        }
      }
      return options;
    };
    resolveHttpAuthSchemeConfig2 = (config) => {
      const config_0 = resolveAwsSdkSigV4Config(config);
      return Object.assign(config_0, {
        authSchemePreference: normalizeProvider(config.authSchemePreference ?? [])
      });
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/EndpointParameters.js
var resolveClientEndpointParameters2, commonParams2;
var init_EndpointParameters2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/EndpointParameters.js"() {
    "use strict";
    resolveClientEndpointParameters2 = (options) => {
      return Object.assign(options, {
        useDualstackEndpoint: options.useDualstackEndpoint ?? false,
        useFipsEndpoint: options.useFipsEndpoint ?? false,
        defaultSigningName: "sso-oauth"
      });
    };
    commonParams2 = {
      UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
      Endpoint: { type: "builtInParams", name: "endpoint" },
      Region: { type: "builtInParams", name: "region" },
      UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/package.json
var package_default2;
var init_package2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/package.json"() {
    package_default2 = {
      name: "@aws-sdk/nested-clients",
      version: "3.817.0",
      description: "Nested clients for AWS SDK packages.",
      main: "./dist-cjs/index.js",
      module: "./dist-es/index.js",
      types: "./dist-types/index.d.ts",
      scripts: {
        build: "yarn lint && concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
        "build:cjs": "node ../../scripts/compilation/inline nested-clients",
        "build:es": "tsc -p tsconfig.es.json",
        "build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
        "build:types": "tsc -p tsconfig.types.json",
        "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
        clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
        lint: "node ../../scripts/validation/submodules-linter.js --pkg nested-clients",
        test: "yarn g:vitest run",
        "test:watch": "yarn g:vitest watch"
      },
      engines: {
        node: ">=18.0.0"
      },
      author: {
        name: "AWS SDK for JavaScript Team",
        url: "https://aws.amazon.com/javascript/"
      },
      license: "Apache-2.0",
      dependencies: {
        "@aws-crypto/sha256-browser": "5.2.0",
        "@aws-crypto/sha256-js": "5.2.0",
        "@aws-sdk/core": "3.816.0",
        "@aws-sdk/middleware-host-header": "3.804.0",
        "@aws-sdk/middleware-logger": "3.804.0",
        "@aws-sdk/middleware-recursion-detection": "3.804.0",
        "@aws-sdk/middleware-user-agent": "3.816.0",
        "@aws-sdk/region-config-resolver": "3.808.0",
        "@aws-sdk/types": "3.804.0",
        "@aws-sdk/util-endpoints": "3.808.0",
        "@aws-sdk/util-user-agent-browser": "3.804.0",
        "@aws-sdk/util-user-agent-node": "3.816.0",
        "@smithy/config-resolver": "^4.1.2",
        "@smithy/core": "^3.3.3",
        "@smithy/fetch-http-handler": "^5.0.2",
        "@smithy/hash-node": "^4.0.2",
        "@smithy/invalid-dependency": "^4.0.2",
        "@smithy/middleware-content-length": "^4.0.2",
        "@smithy/middleware-endpoint": "^4.1.6",
        "@smithy/middleware-retry": "^4.1.7",
        "@smithy/middleware-serde": "^4.0.5",
        "@smithy/middleware-stack": "^4.0.2",
        "@smithy/node-config-provider": "^4.1.1",
        "@smithy/node-http-handler": "^4.0.4",
        "@smithy/protocol-http": "^5.1.0",
        "@smithy/smithy-client": "^4.2.6",
        "@smithy/types": "^4.2.0",
        "@smithy/url-parser": "^4.0.2",
        "@smithy/util-base64": "^4.0.0",
        "@smithy/util-body-length-browser": "^4.0.0",
        "@smithy/util-body-length-node": "^4.0.0",
        "@smithy/util-defaults-mode-browser": "^4.0.14",
        "@smithy/util-defaults-mode-node": "^4.0.14",
        "@smithy/util-endpoints": "^3.0.4",
        "@smithy/util-middleware": "^4.0.2",
        "@smithy/util-retry": "^4.0.3",
        "@smithy/util-utf8": "^4.0.0",
        tslib: "^2.6.2"
      },
      devDependencies: {
        concurrently: "7.0.0",
        "downlevel-dts": "0.10.1",
        rimraf: "3.0.2",
        typescript: "~5.8.3"
      },
      typesVersions: {
        "<4.0": {
          "dist-types/*": [
            "dist-types/ts3.4/*"
          ]
        }
      },
      files: [
        "./sso-oidc.d.ts",
        "./sso-oidc.js",
        "./sts.d.ts",
        "./sts.js",
        "dist-*/**"
      ],
      browser: {
        "./dist-es/submodules/sso-oidc/runtimeConfig": "./dist-es/submodules/sso-oidc/runtimeConfig.browser",
        "./dist-es/submodules/sts/runtimeConfig": "./dist-es/submodules/sts/runtimeConfig.browser"
      },
      "react-native": {},
      homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/packages/nested-clients",
      repository: {
        type: "git",
        url: "https://github.com/aws/aws-sdk-js-v3.git",
        directory: "packages/nested-clients"
      },
      exports: {
        "./sso-oidc": {
          types: "./dist-types/submodules/sso-oidc/index.d.ts",
          module: "./dist-es/submodules/sso-oidc/index.js",
          node: "./dist-cjs/submodules/sso-oidc/index.js",
          import: "./dist-es/submodules/sso-oidc/index.js",
          require: "./dist-cjs/submodules/sso-oidc/index.js"
        },
        "./sts": {
          types: "./dist-types/submodules/sts/index.d.ts",
          module: "./dist-es/submodules/sts/index.js",
          node: "./dist-cjs/submodules/sts/index.js",
          import: "./dist-es/submodules/sts/index.js",
          require: "./dist-cjs/submodules/sts/index.js"
        }
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/crt-availability.js
var crtAvailability;
var init_crt_availability = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/crt-availability.js"() {
    "use strict";
    crtAvailability = {
      isCrtAvailable: false
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/is-crt-available.js
var isCrtAvailable;
var init_is_crt_available = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/is-crt-available.js"() {
    "use strict";
    init_crt_availability();
    isCrtAvailable = () => {
      if (crtAvailability.isCrtAvailable) {
        return ["md/crt-avail"];
      }
      return null;
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/defaultUserAgent.js
var import_os2, import_process, createDefaultUserAgentProvider;
var init_defaultUserAgent = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/defaultUserAgent.js"() {
    "use strict";
    import_os2 = require("os");
    import_process = require("process");
    init_is_crt_available();
    init_crt_availability();
    createDefaultUserAgentProvider = ({ serviceId, clientVersion }) => {
      return async (config) => {
        const sections = [
          ["aws-sdk-js", clientVersion],
          ["ua", "2.1"],
          [`os/${(0, import_os2.platform)()}`, (0, import_os2.release)()],
          ["lang/js"],
          ["md/nodejs", `${import_process.versions.node}`]
        ];
        const crtAvailable = isCrtAvailable();
        if (crtAvailable) {
          sections.push(crtAvailable);
        }
        if (serviceId) {
          sections.push([`api/${serviceId}`, clientVersion]);
        }
        if (import_process.env.AWS_EXECUTION_ENV) {
          sections.push([`exec-env/${import_process.env.AWS_EXECUTION_ENV}`]);
        }
        const appId = await config?.userAgentAppId?.();
        const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections];
        return resolvedUserAgent;
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/nodeAppIdConfigOptions.js
var UA_APP_ID_ENV_NAME, UA_APP_ID_INI_NAME, UA_APP_ID_INI_NAME_DEPRECATED, NODE_APP_ID_CONFIG_OPTIONS;
var init_nodeAppIdConfigOptions = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/nodeAppIdConfigOptions.js"() {
    "use strict";
    init_dist_es26();
    UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID";
    UA_APP_ID_INI_NAME = "sdk_ua_app_id";
    UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id";
    NODE_APP_ID_CONFIG_OPTIONS = {
      environmentVariableSelector: (env4) => env4[UA_APP_ID_ENV_NAME],
      configFileSelector: (profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED],
      default: DEFAULT_UA_APP_ID
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/index.js
var init_dist_es41 = __esm({
  "../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/index.js"() {
    "use strict";
    init_defaultUserAgent();
    init_nodeAppIdConfigOptions();
  }
});

// ../node_modules/.pnpm/@smithy+hash-node@4.0.4/node_modules/@smithy/hash-node/dist-es/index.js
function castSourceData(toCast, encoding) {
  if (import_buffer4.Buffer.isBuffer(toCast)) {
    return toCast;
  }
  if (typeof toCast === "string") {
    return fromString(toCast, encoding);
  }
  if (ArrayBuffer.isView(toCast)) {
    return fromArrayBuffer(toCast.buffer, toCast.byteOffset, toCast.byteLength);
  }
  return fromArrayBuffer(toCast);
}
var import_buffer4, import_crypto6, Hash;
var init_dist_es42 = __esm({
  "../node_modules/.pnpm/@smithy+hash-node@4.0.4/node_modules/@smithy/hash-node/dist-es/index.js"() {
    "use strict";
    init_dist_es9();
    init_dist_es10();
    import_buffer4 = require("buffer");
    import_crypto6 = require("crypto");
    Hash = class {
      constructor(algorithmIdentifier, secret) {
        this.algorithmIdentifier = algorithmIdentifier;
        this.secret = secret;
        this.reset();
      }
      update(toHash, encoding) {
        this.hash.update(toUint8Array(castSourceData(toHash, encoding)));
      }
      digest() {
        return Promise.resolve(this.hash.digest());
      }
      reset() {
        this.hash = this.secret ? (0, import_crypto6.createHmac)(this.algorithmIdentifier, castSourceData(this.secret)) : (0, import_crypto6.createHash)(this.algorithmIdentifier);
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-body-length-node@4.0.0/node_modules/@smithy/util-body-length-node/dist-es/calculateBodyLength.js
var import_fs5, calculateBodyLength;
var init_calculateBodyLength = __esm({
  "../node_modules/.pnpm/@smithy+util-body-length-node@4.0.0/node_modules/@smithy/util-body-length-node/dist-es/calculateBodyLength.js"() {
    "use strict";
    import_fs5 = require("fs");
    calculateBodyLength = (body) => {
      if (!body) {
        return 0;
      }
      if (typeof body === "string") {
        return Buffer.byteLength(body);
      } else if (typeof body.byteLength === "number") {
        return body.byteLength;
      } else if (typeof body.size === "number") {
        return body.size;
      } else if (typeof body.start === "number" && typeof body.end === "number") {
        return body.end + 1 - body.start;
      } else if (typeof body.path === "string" || Buffer.isBuffer(body.path)) {
        return (0, import_fs5.lstatSync)(body.path).size;
      } else if (typeof body.fd === "number") {
        return (0, import_fs5.fstatSync)(body.fd).size;
      }
      throw new Error(`Body Length computation failed for ${body}`);
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-body-length-node@4.0.0/node_modules/@smithy/util-body-length-node/dist-es/index.js
var init_dist_es43 = __esm({
  "../node_modules/.pnpm/@smithy+util-body-length-node@4.0.0/node_modules/@smithy/util-body-length-node/dist-es/index.js"() {
    "use strict";
    init_calculateBodyLength();
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/ruleset.js
var u, v, w, x2, a, b, c, d, e2, f3, g, h2, i2, j, k, l, m2, n, o, p, q, r2, s2, t2, _data, ruleSet;
var init_ruleset = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/ruleset.js"() {
    "use strict";
    u = "required";
    v = "fn";
    w = "argv";
    x2 = "ref";
    a = true;
    b = "isSet";
    c = "booleanEquals";
    d = "error";
    e2 = "endpoint";
    f3 = "tree";
    g = "PartitionResult";
    h2 = "getAttr";
    i2 = { [u]: false, "type": "String" };
    j = { [u]: true, "default": false, "type": "Boolean" };
    k = { [x2]: "Endpoint" };
    l = { [v]: c, [w]: [{ [x2]: "UseFIPS" }, true] };
    m2 = { [v]: c, [w]: [{ [x2]: "UseDualStack" }, true] };
    n = {};
    o = { [v]: h2, [w]: [{ [x2]: g }, "supportsFIPS"] };
    p = { [x2]: g };
    q = { [v]: c, [w]: [true, { [v]: h2, [w]: [p, "supportsDualStack"] }] };
    r2 = [l];
    s2 = [m2];
    t2 = [{ [x2]: "Region" }];
    _data = { version: "1.0", parameters: { Region: i2, UseDualStack: j, UseFIPS: j, Endpoint: i2 }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: r2, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: s2, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e2 }], type: f3 }, { conditions: [{ [v]: b, [w]: t2 }], rules: [{ conditions: [{ [v]: "aws.partition", [w]: t2, assign: g }], rules: [{ conditions: [l, m2], rules: [{ conditions: [{ [v]: c, [w]: [a, o] }, q], rules: [{ endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e2 }], type: f3 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f3 }, { conditions: r2, rules: [{ conditions: [{ [v]: c, [w]: [o, a] }], rules: [{ conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h2, [w]: [p, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://oidc.{Region}.amazonaws.com", properties: n, headers: n }, type: e2 }, { endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e2 }], type: f3 }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f3 }, { conditions: s2, rules: [{ conditions: [q], rules: [{ endpoint: { url: "https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e2 }], type: f3 }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f3 }, { endpoint: { url: "https://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e2 }], type: f3 }], type: f3 }, { error: "Invalid Configuration: Missing Region", type: d }] };
    ruleSet = _data;
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/endpointResolver.js
var cache, defaultEndpointResolver;
var init_endpointResolver = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/endpointResolver.js"() {
    "use strict";
    init_dist_es20();
    init_dist_es19();
    init_ruleset();
    cache = new EndpointCache({
      size: 50,
      params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
    });
    defaultEndpointResolver = (endpointParams, context = {}) => {
      return cache.get(endpointParams, () => resolveEndpoint(ruleSet, {
        endpointParams,
        logger: context.logger
      }));
    };
    customEndpointFunctions.aws = awsEndpointFunctions;
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.shared.js
var getRuntimeConfig;
var init_runtimeConfig_shared = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.shared.js"() {
    "use strict";
    init_dist_es25();
    init_dist_es18();
    init_dist_es24();
    init_dist_es33();
    init_dist_es11();
    init_dist_es10();
    init_httpAuthSchemeProvider2();
    init_endpointResolver();
    getRuntimeConfig = (config) => {
      return {
        apiVersion: "2019-06-10",
        base64Decoder: config?.base64Decoder ?? fromBase64,
        base64Encoder: config?.base64Encoder ?? toBase64,
        disableHostPrefix: config?.disableHostPrefix ?? false,
        endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,
        extensions: config?.extensions ?? [],
        httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOOIDCHttpAuthSchemeProvider,
        httpAuthSchemes: config?.httpAuthSchemes ?? [
          {
            schemeId: "aws.auth#sigv4",
            identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
            signer: new AwsSdkSigV4Signer()
          },
          {
            schemeId: "smithy.api#noAuth",
            identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
            signer: new NoAuthSigner()
          }
        ],
        logger: config?.logger ?? new NoOpLogger(),
        serviceId: config?.serviceId ?? "SSO OIDC",
        urlParser: config?.urlParser ?? parseUrl,
        utf8Decoder: config?.utf8Decoder ?? fromUtf8,
        utf8Encoder: config?.utf8Encoder ?? toUtf8
      };
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-es/constants.js
var AWS_EXECUTION_ENV, AWS_REGION_ENV, AWS_DEFAULT_REGION_ENV, ENV_IMDS_DISABLED2, DEFAULTS_MODE_OPTIONS, IMDS_REGION_PATH;
var init_constants9 = __esm({
  "../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-es/constants.js"() {
    "use strict";
    AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV";
    AWS_REGION_ENV = "AWS_REGION";
    AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION";
    ENV_IMDS_DISABLED2 = "AWS_EC2_METADATA_DISABLED";
    DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"];
    IMDS_REGION_PATH = "/latest/meta-data/placement/region";
  }
});

// ../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-es/defaultsModeConfig.js
var AWS_DEFAULTS_MODE_ENV, AWS_DEFAULTS_MODE_CONFIG, NODE_DEFAULTS_MODE_CONFIG_OPTIONS;
var init_defaultsModeConfig = __esm({
  "../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-es/defaultsModeConfig.js"() {
    "use strict";
    AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE";
    AWS_DEFAULTS_MODE_CONFIG = "defaults_mode";
    NODE_DEFAULTS_MODE_CONFIG_OPTIONS = {
      environmentVariableSelector: (env4) => {
        return env4[AWS_DEFAULTS_MODE_ENV];
      },
      configFileSelector: (profile) => {
        return profile[AWS_DEFAULTS_MODE_CONFIG];
      },
      default: "legacy"
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-es/resolveDefaultsModeConfig.js
var resolveDefaultsModeConfig, resolveNodeDefaultsModeAuto, inferPhysicalRegion;
var init_resolveDefaultsModeConfig = __esm({
  "../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-es/resolveDefaultsModeConfig.js"() {
    "use strict";
    init_dist_es28();
    init_dist_es31();
    init_dist_es21();
    init_constants9();
    init_defaultsModeConfig();
    resolveDefaultsModeConfig = ({ region = loadConfig(NODE_REGION_CONFIG_OPTIONS), defaultsMode = loadConfig(NODE_DEFAULTS_MODE_CONFIG_OPTIONS) } = {}) => memoize(async () => {
      const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode;
      switch (mode?.toLowerCase()) {
        case "auto":
          return resolveNodeDefaultsModeAuto(region);
        case "in-region":
        case "cross-region":
        case "mobile":
        case "standard":
        case "legacy":
          return Promise.resolve(mode?.toLocaleLowerCase());
        case void 0:
          return Promise.resolve("legacy");
        default:
          throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`);
      }
    });
    resolveNodeDefaultsModeAuto = async (clientRegion) => {
      if (clientRegion) {
        const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion;
        const inferredRegion = await inferPhysicalRegion();
        if (!inferredRegion) {
          return "standard";
        }
        if (resolvedRegion === inferredRegion) {
          return "in-region";
        } else {
          return "cross-region";
        }
      }
      return "standard";
    };
    inferPhysicalRegion = async () => {
      if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) {
        return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV];
      }
      if (!process.env[ENV_IMDS_DISABLED2]) {
        try {
          const { getInstanceMetadataEndpoint: getInstanceMetadataEndpoint2, httpRequest: httpRequest2 } = await Promise.resolve().then(() => (init_dist_es39(), dist_es_exports2));
          const endpoint = await getInstanceMetadataEndpoint2();
          return (await httpRequest2({ ...endpoint, path: IMDS_REGION_PATH })).toString();
        } catch (e6) {
        }
      }
    };
  }
});

// ../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-es/index.js
var init_dist_es44 = __esm({
  "../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-es/index.js"() {
    "use strict";
    init_resolveDefaultsModeConfig();
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.js
var getRuntimeConfig2;
var init_runtimeConfig = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.js"() {
    "use strict";
    init_package2();
    init_dist_es25();
    init_dist_es41();
    init_dist_es28();
    init_dist_es42();
    init_dist_es37();
    init_dist_es31();
    init_dist_es14();
    init_dist_es43();
    init_dist_es36();
    init_runtimeConfig_shared();
    init_dist_es24();
    init_dist_es44();
    init_dist_es24();
    getRuntimeConfig2 = (config) => {
      emitWarningIfUnsupportedVersion2(process.version);
      const defaultsMode = resolveDefaultsModeConfig(config);
      const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);
      const clientSharedValues = getRuntimeConfig(config);
      emitWarningIfUnsupportedVersion(process.version);
      const loaderConfig = {
        profile: config?.profile,
        logger: clientSharedValues.logger
      };
      return {
        ...clientSharedValues,
        ...config,
        runtime: "node",
        defaultsMode,
        authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
        bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,
        defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default2.version }),
        maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
        region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
        requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),
        retryMode: config?.retryMode ?? loadConfig({
          ...NODE_RETRY_MODE_CONFIG_OPTIONS,
          default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE
        }, config),
        sha256: config?.sha256 ?? Hash.bind(null, "sha256"),
        streamCollector: config?.streamCollector ?? streamCollector,
        useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
        useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
        userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/extensions/index.js
var getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration;
var init_extensions4 = __esm({
  "../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/extensions/index.js"() {
    "use strict";
    getAwsRegionExtensionConfiguration = (runtimeConfig) => {
      return {
        setRegion(region) {
          runtimeConfig.region = region;
        },
        region() {
          return runtimeConfig.region;
        }
      };
    };
    resolveAwsRegionExtensionConfiguration = (awsRegionExtensionConfiguration) => {
      return {
        region: awsRegionExtensionConfiguration.region()
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/config.js
var init_config4 = __esm({
  "../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/config.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/isFipsRegion.js
var init_isFipsRegion2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/isFipsRegion.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/getRealRegion.js
var init_getRealRegion2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/getRealRegion.js"() {
    "use strict";
    init_isFipsRegion2();
  }
});

// ../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/resolveRegionConfig.js
var init_resolveRegionConfig2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/resolveRegionConfig.js"() {
    "use strict";
    init_getRealRegion2();
    init_isFipsRegion2();
  }
});

// ../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/index.js
var init_regionConfig2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/index.js"() {
    "use strict";
    init_config4();
    init_resolveRegionConfig2();
  }
});

// ../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/index.js
var init_dist_es45 = __esm({
  "../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/index.js"() {
    "use strict";
    init_extensions4();
    init_regionConfig2();
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.js
var getHttpAuthExtensionConfiguration, resolveHttpAuthRuntimeConfig;
var init_httpAuthExtensionConfiguration = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.js"() {
    "use strict";
    getHttpAuthExtensionConfiguration = (runtimeConfig) => {
      const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
      let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
      let _credentials = runtimeConfig.credentials;
      return {
        setHttpAuthScheme(httpAuthScheme) {
          const index6 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
          if (index6 === -1) {
            _httpAuthSchemes.push(httpAuthScheme);
          } else {
            _httpAuthSchemes.splice(index6, 1, httpAuthScheme);
          }
        },
        httpAuthSchemes() {
          return _httpAuthSchemes;
        },
        setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
          _httpAuthSchemeProvider = httpAuthSchemeProvider;
        },
        httpAuthSchemeProvider() {
          return _httpAuthSchemeProvider;
        },
        setCredentials(credentials2) {
          _credentials = credentials2;
        },
        credentials() {
          return _credentials;
        }
      };
    };
    resolveHttpAuthRuntimeConfig = (config) => {
      return {
        httpAuthSchemes: config.httpAuthSchemes(),
        httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
        credentials: config.credentials()
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeExtensions.js
var resolveRuntimeExtensions;
var init_runtimeExtensions = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeExtensions.js"() {
    "use strict";
    init_dist_es45();
    init_dist_es2();
    init_dist_es24();
    init_httpAuthExtensionConfiguration();
    resolveRuntimeExtensions = (runtimeConfig, extensions) => {
      const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));
      extensions.forEach((extension) => extension.configure(extensionConfiguration));
      return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDCClient.js
var SSOOIDCClient;
var init_SSOOIDCClient = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDCClient.js"() {
    "use strict";
    init_dist_es3();
    init_dist_es4();
    init_dist_es5();
    init_dist_es26();
    init_dist_es28();
    init_dist_es18();
    init_dist_es29();
    init_dist_es34();
    init_dist_es37();
    init_dist_es24();
    init_httpAuthSchemeProvider2();
    init_EndpointParameters2();
    init_runtimeConfig();
    init_runtimeExtensions();
    SSOOIDCClient = class extends Client {
      constructor(...[configuration]) {
        const _config_0 = getRuntimeConfig2(configuration || {});
        super(_config_0);
        __publicField(this, "config");
        this.initConfig = _config_0;
        const _config_1 = resolveClientEndpointParameters2(_config_0);
        const _config_2 = resolveUserAgentConfig(_config_1);
        const _config_3 = resolveRetryConfig(_config_2);
        const _config_4 = resolveRegionConfig(_config_3);
        const _config_5 = resolveHostHeaderConfig(_config_4);
        const _config_6 = resolveEndpointConfig(_config_5);
        const _config_7 = resolveHttpAuthSchemeConfig2(_config_6);
        const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);
        this.config = _config_8;
        this.middlewareStack.use(getUserAgentPlugin(this.config));
        this.middlewareStack.use(getRetryPlugin(this.config));
        this.middlewareStack.use(getContentLengthPlugin(this.config));
        this.middlewareStack.use(getHostHeaderPlugin(this.config));
        this.middlewareStack.use(getLoggerPlugin(this.config));
        this.middlewareStack.use(getRecursionDetectionPlugin(this.config));
        this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
          httpAuthSchemeParametersProvider: defaultSSOOIDCHttpAuthSchemeParametersProvider,
          identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({
            "aws.auth#sigv4": config.credentials
          })
        }));
        this.middlewareStack.use(getHttpSigningPlugin(this.config));
      }
      destroy() {
        super.destroy();
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/SSOOIDCServiceException.js
var SSOOIDCServiceException;
var init_SSOOIDCServiceException = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/SSOOIDCServiceException.js"() {
    "use strict";
    init_dist_es24();
    SSOOIDCServiceException = class _SSOOIDCServiceException extends ServiceException {
      constructor(options) {
        super(options);
        Object.setPrototypeOf(this, _SSOOIDCServiceException.prototype);
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/models_0.js
var AccessDeniedException, AuthorizationPendingException, CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog, ExpiredTokenException, InternalServerException, InvalidClientException, InvalidGrantException, InvalidRequestException, InvalidScopeException, SlowDownException, UnauthorizedClientException, UnsupportedGrantTypeException;
var init_models_0 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/models_0.js"() {
    "use strict";
    init_dist_es24();
    init_SSOOIDCServiceException();
    AccessDeniedException = class _AccessDeniedException extends SSOOIDCServiceException {
      constructor(opts) {
        super({
          name: "AccessDeniedException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "AccessDeniedException");
        __publicField(this, "$fault", "client");
        __publicField(this, "error");
        __publicField(this, "error_description");
        Object.setPrototypeOf(this, _AccessDeniedException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    AuthorizationPendingException = class _AuthorizationPendingException extends SSOOIDCServiceException {
      constructor(opts) {
        super({
          name: "AuthorizationPendingException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "AuthorizationPendingException");
        __publicField(this, "$fault", "client");
        __publicField(this, "error");
        __publicField(this, "error_description");
        Object.setPrototypeOf(this, _AuthorizationPendingException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    CreateTokenRequestFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.clientSecret && { clientSecret: SENSITIVE_STRING },
      ...obj.refreshToken && { refreshToken: SENSITIVE_STRING },
      ...obj.codeVerifier && { codeVerifier: SENSITIVE_STRING }
    });
    CreateTokenResponseFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.accessToken && { accessToken: SENSITIVE_STRING },
      ...obj.refreshToken && { refreshToken: SENSITIVE_STRING },
      ...obj.idToken && { idToken: SENSITIVE_STRING }
    });
    ExpiredTokenException = class _ExpiredTokenException extends SSOOIDCServiceException {
      constructor(opts) {
        super({
          name: "ExpiredTokenException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "ExpiredTokenException");
        __publicField(this, "$fault", "client");
        __publicField(this, "error");
        __publicField(this, "error_description");
        Object.setPrototypeOf(this, _ExpiredTokenException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    InternalServerException = class _InternalServerException extends SSOOIDCServiceException {
      constructor(opts) {
        super({
          name: "InternalServerException",
          $fault: "server",
          ...opts
        });
        __publicField(this, "name", "InternalServerException");
        __publicField(this, "$fault", "server");
        __publicField(this, "error");
        __publicField(this, "error_description");
        Object.setPrototypeOf(this, _InternalServerException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    InvalidClientException = class _InvalidClientException extends SSOOIDCServiceException {
      constructor(opts) {
        super({
          name: "InvalidClientException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "InvalidClientException");
        __publicField(this, "$fault", "client");
        __publicField(this, "error");
        __publicField(this, "error_description");
        Object.setPrototypeOf(this, _InvalidClientException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    InvalidGrantException = class _InvalidGrantException extends SSOOIDCServiceException {
      constructor(opts) {
        super({
          name: "InvalidGrantException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "InvalidGrantException");
        __publicField(this, "$fault", "client");
        __publicField(this, "error");
        __publicField(this, "error_description");
        Object.setPrototypeOf(this, _InvalidGrantException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    InvalidRequestException = class _InvalidRequestException extends SSOOIDCServiceException {
      constructor(opts) {
        super({
          name: "InvalidRequestException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "InvalidRequestException");
        __publicField(this, "$fault", "client");
        __publicField(this, "error");
        __publicField(this, "error_description");
        Object.setPrototypeOf(this, _InvalidRequestException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    InvalidScopeException = class _InvalidScopeException extends SSOOIDCServiceException {
      constructor(opts) {
        super({
          name: "InvalidScopeException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "InvalidScopeException");
        __publicField(this, "$fault", "client");
        __publicField(this, "error");
        __publicField(this, "error_description");
        Object.setPrototypeOf(this, _InvalidScopeException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    SlowDownException = class _SlowDownException extends SSOOIDCServiceException {
      constructor(opts) {
        super({
          name: "SlowDownException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "SlowDownException");
        __publicField(this, "$fault", "client");
        __publicField(this, "error");
        __publicField(this, "error_description");
        Object.setPrototypeOf(this, _SlowDownException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    UnauthorizedClientException = class _UnauthorizedClientException extends SSOOIDCServiceException {
      constructor(opts) {
        super({
          name: "UnauthorizedClientException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "UnauthorizedClientException");
        __publicField(this, "$fault", "client");
        __publicField(this, "error");
        __publicField(this, "error_description");
        Object.setPrototypeOf(this, _UnauthorizedClientException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    UnsupportedGrantTypeException = class _UnsupportedGrantTypeException extends SSOOIDCServiceException {
      constructor(opts) {
        super({
          name: "UnsupportedGrantTypeException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "UnsupportedGrantTypeException");
        __publicField(this, "$fault", "client");
        __publicField(this, "error");
        __publicField(this, "error_description");
        Object.setPrototypeOf(this, _UnsupportedGrantTypeException.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/protocols/Aws_restJson1.js
var se_CreateTokenCommand, de_CreateTokenCommand, de_CommandError, throwDefaultError2, de_AccessDeniedExceptionRes, de_AuthorizationPendingExceptionRes, de_ExpiredTokenExceptionRes, de_InternalServerExceptionRes, de_InvalidClientExceptionRes, de_InvalidGrantExceptionRes, de_InvalidRequestExceptionRes, de_InvalidScopeExceptionRes, de_SlowDownExceptionRes, de_UnauthorizedClientExceptionRes, de_UnsupportedGrantTypeExceptionRes, deserializeMetadata2;
var init_Aws_restJson1 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/protocols/Aws_restJson1.js"() {
    "use strict";
    init_dist_es25();
    init_dist_es18();
    init_dist_es24();
    init_models_0();
    init_SSOOIDCServiceException();
    se_CreateTokenCommand = async (input, context) => {
      const b5 = requestBuilder(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b5.bp("/token");
      let body;
      body = JSON.stringify(take(input, {
        clientId: [],
        clientSecret: [],
        code: [],
        codeVerifier: [],
        deviceCode: [],
        grantType: [],
        redirectUri: [],
        refreshToken: [],
        scope: (_3) => _json(_3)
      }));
      b5.m("POST").h(headers).b(body);
      return b5.build();
    };
    de_CreateTokenCommand = async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = map({
        $metadata: deserializeMetadata2(output)
      });
      const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
      const doc = take(data, {
        accessToken: expectString,
        expiresIn: expectInt32,
        idToken: expectString,
        refreshToken: expectString,
        tokenType: expectString
      });
      Object.assign(contents, doc);
      return contents;
    };
    de_CommandError = async (output, context) => {
      const parsedOutput = {
        ...output,
        body: await parseJsonErrorBody(output.body, context)
      };
      const errorCode = loadRestJsonErrorCode(output, parsedOutput.body);
      switch (errorCode) {
        case "AccessDeniedException":
        case "com.amazonaws.ssooidc#AccessDeniedException":
          throw await de_AccessDeniedExceptionRes(parsedOutput, context);
        case "AuthorizationPendingException":
        case "com.amazonaws.ssooidc#AuthorizationPendingException":
          throw await de_AuthorizationPendingExceptionRes(parsedOutput, context);
        case "ExpiredTokenException":
        case "com.amazonaws.ssooidc#ExpiredTokenException":
          throw await de_ExpiredTokenExceptionRes(parsedOutput, context);
        case "InternalServerException":
        case "com.amazonaws.ssooidc#InternalServerException":
          throw await de_InternalServerExceptionRes(parsedOutput, context);
        case "InvalidClientException":
        case "com.amazonaws.ssooidc#InvalidClientException":
          throw await de_InvalidClientExceptionRes(parsedOutput, context);
        case "InvalidGrantException":
        case "com.amazonaws.ssooidc#InvalidGrantException":
          throw await de_InvalidGrantExceptionRes(parsedOutput, context);
        case "InvalidRequestException":
        case "com.amazonaws.ssooidc#InvalidRequestException":
          throw await de_InvalidRequestExceptionRes(parsedOutput, context);
        case "InvalidScopeException":
        case "com.amazonaws.ssooidc#InvalidScopeException":
          throw await de_InvalidScopeExceptionRes(parsedOutput, context);
        case "SlowDownException":
        case "com.amazonaws.ssooidc#SlowDownException":
          throw await de_SlowDownExceptionRes(parsedOutput, context);
        case "UnauthorizedClientException":
        case "com.amazonaws.ssooidc#UnauthorizedClientException":
          throw await de_UnauthorizedClientExceptionRes(parsedOutput, context);
        case "UnsupportedGrantTypeException":
        case "com.amazonaws.ssooidc#UnsupportedGrantTypeException":
          throw await de_UnsupportedGrantTypeExceptionRes(parsedOutput, context);
        default:
          const parsedBody = parsedOutput.body;
          return throwDefaultError2({
            output,
            parsedBody,
            errorCode
          });
      }
    };
    throwDefaultError2 = withBaseException(SSOOIDCServiceException);
    de_AccessDeniedExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        error: expectString,
        error_description: expectString
      });
      Object.assign(contents, doc);
      const exception = new AccessDeniedException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_AuthorizationPendingExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        error: expectString,
        error_description: expectString
      });
      Object.assign(contents, doc);
      const exception = new AuthorizationPendingException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_ExpiredTokenExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        error: expectString,
        error_description: expectString
      });
      Object.assign(contents, doc);
      const exception = new ExpiredTokenException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_InternalServerExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        error: expectString,
        error_description: expectString
      });
      Object.assign(contents, doc);
      const exception = new InternalServerException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_InvalidClientExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        error: expectString,
        error_description: expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidClientException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_InvalidGrantExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        error: expectString,
        error_description: expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidGrantException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_InvalidRequestExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        error: expectString,
        error_description: expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidRequestException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_InvalidScopeExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        error: expectString,
        error_description: expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidScopeException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_SlowDownExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        error: expectString,
        error_description: expectString
      });
      Object.assign(contents, doc);
      const exception = new SlowDownException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_UnauthorizedClientExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        error: expectString,
        error_description: expectString
      });
      Object.assign(contents, doc);
      const exception = new UnauthorizedClientException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_UnsupportedGrantTypeExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        error: expectString,
        error_description: expectString
      });
      Object.assign(contents, doc);
      const exception = new UnsupportedGrantTypeException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    deserializeMetadata2 = (output) => ({
      httpStatusCode: output.statusCode,
      requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
      extendedRequestId: output.headers["x-amz-id-2"],
      cfId: output.headers["x-amz-cf-id"]
    });
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/CreateTokenCommand.js
var CreateTokenCommand;
var init_CreateTokenCommand = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/CreateTokenCommand.js"() {
    "use strict";
    init_dist_es34();
    init_dist_es7();
    init_dist_es24();
    init_EndpointParameters2();
    init_models_0();
    init_Aws_restJson1();
    CreateTokenCommand = class extends Command.classBuilder().ep(commonParams2).m(function(Command2, cs, config, o5) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
      ];
    }).s("AWSSSOOIDCService", "CreateToken", {}).n("SSOOIDCClient", "CreateTokenCommand").f(CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog).ser(se_CreateTokenCommand).de(de_CreateTokenCommand).build() {
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDC.js
var commands, SSOOIDC;
var init_SSOOIDC = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDC.js"() {
    "use strict";
    init_dist_es24();
    init_CreateTokenCommand();
    init_SSOOIDCClient();
    commands = {
      CreateTokenCommand
    };
    SSOOIDC = class extends SSOOIDCClient {
    };
    createAggregatedClient(commands, SSOOIDC);
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/index.js
var init_commands = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/index.js"() {
    "use strict";
    init_CreateTokenCommand();
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/index.js
var init_models = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/index.js"() {
    "use strict";
    init_models_0();
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/index.js
var sso_oidc_exports = {};
__export(sso_oidc_exports, {
  $Command: () => Command,
  AccessDeniedException: () => AccessDeniedException,
  AuthorizationPendingException: () => AuthorizationPendingException,
  CreateTokenCommand: () => CreateTokenCommand,
  CreateTokenRequestFilterSensitiveLog: () => CreateTokenRequestFilterSensitiveLog,
  CreateTokenResponseFilterSensitiveLog: () => CreateTokenResponseFilterSensitiveLog,
  ExpiredTokenException: () => ExpiredTokenException,
  InternalServerException: () => InternalServerException,
  InvalidClientException: () => InvalidClientException,
  InvalidGrantException: () => InvalidGrantException,
  InvalidRequestException: () => InvalidRequestException,
  InvalidScopeException: () => InvalidScopeException,
  SSOOIDC: () => SSOOIDC,
  SSOOIDCClient: () => SSOOIDCClient,
  SSOOIDCServiceException: () => SSOOIDCServiceException,
  SlowDownException: () => SlowDownException,
  UnauthorizedClientException: () => UnauthorizedClientException,
  UnsupportedGrantTypeException: () => UnsupportedGrantTypeException,
  __Client: () => Client
});
var init_sso_oidc = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/index.js"() {
    "use strict";
    init_SSOOIDCClient();
    init_SSOOIDC();
    init_commands();
    init_models();
    init_SSOOIDCServiceException();
  }
});

// ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/getSsoOidcClient.js
var getSsoOidcClient;
var init_getSsoOidcClient = __esm({
  "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/getSsoOidcClient.js"() {
    "use strict";
    getSsoOidcClient = async (ssoRegion, init2 = {}) => {
      const { SSOOIDCClient: SSOOIDCClient2 } = await Promise.resolve().then(() => (init_sso_oidc(), sso_oidc_exports));
      const ssoOidcClient = new SSOOIDCClient2(Object.assign({}, init2.clientConfig ?? {}, {
        region: ssoRegion ?? init2.clientConfig?.region,
        logger: init2.clientConfig?.logger ?? init2.parentClientConfig?.logger
      }));
      return ssoOidcClient;
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/getNewSsoOidcToken.js
var getNewSsoOidcToken;
var init_getNewSsoOidcToken = __esm({
  "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/getNewSsoOidcToken.js"() {
    "use strict";
    init_getSsoOidcClient();
    getNewSsoOidcToken = async (ssoToken, ssoRegion, init2 = {}) => {
      const { CreateTokenCommand: CreateTokenCommand2 } = await Promise.resolve().then(() => (init_sso_oidc(), sso_oidc_exports));
      const ssoOidcClient = await getSsoOidcClient(ssoRegion, init2);
      return ssoOidcClient.send(new CreateTokenCommand2({
        clientId: ssoToken.clientId,
        clientSecret: ssoToken.clientSecret,
        refreshToken: ssoToken.refreshToken,
        grantType: "refresh_token"
      }));
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/validateTokenExpiry.js
var validateTokenExpiry;
var init_validateTokenExpiry = __esm({
  "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/validateTokenExpiry.js"() {
    "use strict";
    init_dist_es21();
    init_constants8();
    validateTokenExpiry = (token) => {
      if (token.expiration && token.expiration.getTime() < Date.now()) {
        throw new TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false);
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/validateTokenKey.js
var validateTokenKey;
var init_validateTokenKey = __esm({
  "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/validateTokenKey.js"() {
    "use strict";
    init_dist_es21();
    init_constants8();
    validateTokenKey = (key, value, forRefresh = false) => {
      if (typeof value === "undefined") {
        throw new TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, false);
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/writeSSOTokenToFile.js
var import_fs6, writeFile, writeSSOTokenToFile;
var init_writeSSOTokenToFile = __esm({
  "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/writeSSOTokenToFile.js"() {
    "use strict";
    init_dist_es30();
    import_fs6 = require("fs");
    ({ writeFile } = import_fs6.promises);
    writeSSOTokenToFile = (id, ssoToken) => {
      const tokenFilepath = getSSOTokenFilepath(id);
      const tokenString = JSON.stringify(ssoToken, null, 2);
      return writeFile(tokenFilepath, tokenString);
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/fromSso.js
var lastRefreshAttemptTime, fromSso;
var init_fromSso = __esm({
  "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/fromSso.js"() {
    "use strict";
    init_dist_es21();
    init_dist_es30();
    init_constants8();
    init_getNewSsoOidcToken();
    init_validateTokenExpiry();
    init_validateTokenKey();
    init_writeSSOTokenToFile();
    lastRefreshAttemptTime = /* @__PURE__ */ new Date(0);
    fromSso = (_init2 = {}) => async ({ callerClientConfig } = {}) => {
      const init2 = {
        ..._init2,
        parentClientConfig: {
          ...callerClientConfig,
          ..._init2.parentClientConfig
        }
      };
      init2.logger?.debug("@aws-sdk/token-providers - fromSso");
      const profiles = await parseKnownFiles(init2);
      const profileName = getProfileName({
        profile: init2.profile ?? callerClientConfig?.profile
      });
      const profile = profiles[profileName];
      if (!profile) {
        throw new TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false);
      } else if (!profile["sso_session"]) {
        throw new TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`);
      }
      const ssoSessionName = profile["sso_session"];
      const ssoSessions = await loadSsoSessionData(init2);
      const ssoSession = ssoSessions[ssoSessionName];
      if (!ssoSession) {
        throw new TokenProviderError(`Sso session '${ssoSessionName}' could not be found in shared credentials file.`, false);
      }
      for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) {
        if (!ssoSession[ssoSessionRequiredKey]) {
          throw new TokenProviderError(`Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, false);
        }
      }
      const ssoStartUrl = ssoSession["sso_start_url"];
      const ssoRegion = ssoSession["sso_region"];
      let ssoToken;
      try {
        ssoToken = await getSSOTokenFromFile(ssoSessionName);
      } catch (e6) {
        throw new TokenProviderError(`The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, false);
      }
      validateTokenKey("accessToken", ssoToken.accessToken);
      validateTokenKey("expiresAt", ssoToken.expiresAt);
      const { accessToken, expiresAt } = ssoToken;
      const existingToken = { token: accessToken, expiration: new Date(expiresAt) };
      if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) {
        return existingToken;
      }
      if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1e3) {
        validateTokenExpiry(existingToken);
        return existingToken;
      }
      validateTokenKey("clientId", ssoToken.clientId, true);
      validateTokenKey("clientSecret", ssoToken.clientSecret, true);
      validateTokenKey("refreshToken", ssoToken.refreshToken, true);
      try {
        lastRefreshAttemptTime.setTime(Date.now());
        const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init2);
        validateTokenKey("accessToken", newSsoOidcToken.accessToken);
        validateTokenKey("expiresIn", newSsoOidcToken.expiresIn);
        const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1e3);
        try {
          await writeSSOTokenToFile(ssoSessionName, {
            ...ssoToken,
            accessToken: newSsoOidcToken.accessToken,
            expiresAt: newTokenExpiration.toISOString(),
            refreshToken: newSsoOidcToken.refreshToken
          });
        } catch (error2) {
        }
        return {
          token: newSsoOidcToken.accessToken,
          expiration: newTokenExpiration
        };
      } catch (error2) {
        validateTokenExpiry(existingToken);
        return existingToken;
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/fromStatic.js
var init_fromStatic3 = __esm({
  "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/fromStatic.js"() {
    "use strict";
    init_dist_es21();
  }
});

// ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/nodeProvider.js
var init_nodeProvider = __esm({
  "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/nodeProvider.js"() {
    "use strict";
    init_dist_es21();
  }
});

// ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/index.js
var init_dist_es46 = __esm({
  "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/index.js"() {
    "use strict";
    init_fromEnvSigningName();
    init_fromSso();
    init_fromStatic3();
    init_nodeProvider();
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/auth/httpAuthSchemeProvider.js
function createAwsAuthSigv4HttpAuthOption3(authParameters) {
  return {
    schemeId: "aws.auth#sigv4",
    signingProperties: {
      name: "awsssoportal",
      region: authParameters.region
    },
    propertiesExtractor: (config, context) => ({
      signingProperties: {
        config,
        context
      }
    })
  };
}
function createSmithyApiNoAuthHttpAuthOption2(authParameters) {
  return {
    schemeId: "smithy.api#noAuth"
  };
}
var defaultSSOHttpAuthSchemeParametersProvider, defaultSSOHttpAuthSchemeProvider, resolveHttpAuthSchemeConfig3;
var init_httpAuthSchemeProvider3 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/auth/httpAuthSchemeProvider.js"() {
    "use strict";
    init_dist_es25();
    init_dist_es6();
    defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => {
      return {
        operation: getSmithyContext(context).operation,
        region: await normalizeProvider(config.region)() || (() => {
          throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
        })()
      };
    };
    defaultSSOHttpAuthSchemeProvider = (authParameters) => {
      const options = [];
      switch (authParameters.operation) {
        case "GetRoleCredentials": {
          options.push(createSmithyApiNoAuthHttpAuthOption2(authParameters));
          break;
        }
        case "ListAccountRoles": {
          options.push(createSmithyApiNoAuthHttpAuthOption2(authParameters));
          break;
        }
        case "ListAccounts": {
          options.push(createSmithyApiNoAuthHttpAuthOption2(authParameters));
          break;
        }
        case "Logout": {
          options.push(createSmithyApiNoAuthHttpAuthOption2(authParameters));
          break;
        }
        default: {
          options.push(createAwsAuthSigv4HttpAuthOption3(authParameters));
        }
      }
      return options;
    };
    resolveHttpAuthSchemeConfig3 = (config) => {
      const config_0 = resolveAwsSdkSigV4Config(config);
      return Object.assign(config_0, {
        authSchemePreference: normalizeProvider(config.authSchemePreference ?? [])
      });
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/endpoint/EndpointParameters.js
var resolveClientEndpointParameters3, commonParams3;
var init_EndpointParameters3 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/endpoint/EndpointParameters.js"() {
    "use strict";
    resolveClientEndpointParameters3 = (options) => {
      return Object.assign(options, {
        useDualstackEndpoint: options.useDualstackEndpoint ?? false,
        useFipsEndpoint: options.useFipsEndpoint ?? false,
        defaultSigningName: "awsssoportal"
      });
    };
    commonParams3 = {
      UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
      Endpoint: { type: "builtInParams", name: "endpoint" },
      Region: { type: "builtInParams", name: "region" },
      UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/package.json
var package_default3;
var init_package3 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/package.json"() {
    package_default3 = {
      name: "@aws-sdk/client-sso",
      description: "AWS SDK for JavaScript Sso Client for Node.js, Browser and React Native",
      version: "3.817.0",
      scripts: {
        build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
        "build:cjs": "node ../../scripts/compilation/inline client-sso",
        "build:es": "tsc -p tsconfig.es.json",
        "build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
        "build:types": "tsc -p tsconfig.types.json",
        "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
        clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
        "extract:docs": "api-extractor run --local",
        "generate:client": "node ../../scripts/generate-clients/single-service --solo sso"
      },
      main: "./dist-cjs/index.js",
      types: "./dist-types/index.d.ts",
      module: "./dist-es/index.js",
      sideEffects: false,
      dependencies: {
        "@aws-crypto/sha256-browser": "5.2.0",
        "@aws-crypto/sha256-js": "5.2.0",
        "@aws-sdk/core": "3.816.0",
        "@aws-sdk/middleware-host-header": "3.804.0",
        "@aws-sdk/middleware-logger": "3.804.0",
        "@aws-sdk/middleware-recursion-detection": "3.804.0",
        "@aws-sdk/middleware-user-agent": "3.816.0",
        "@aws-sdk/region-config-resolver": "3.808.0",
        "@aws-sdk/types": "3.804.0",
        "@aws-sdk/util-endpoints": "3.808.0",
        "@aws-sdk/util-user-agent-browser": "3.804.0",
        "@aws-sdk/util-user-agent-node": "3.816.0",
        "@smithy/config-resolver": "^4.1.2",
        "@smithy/core": "^3.3.3",
        "@smithy/fetch-http-handler": "^5.0.2",
        "@smithy/hash-node": "^4.0.2",
        "@smithy/invalid-dependency": "^4.0.2",
        "@smithy/middleware-content-length": "^4.0.2",
        "@smithy/middleware-endpoint": "^4.1.6",
        "@smithy/middleware-retry": "^4.1.7",
        "@smithy/middleware-serde": "^4.0.5",
        "@smithy/middleware-stack": "^4.0.2",
        "@smithy/node-config-provider": "^4.1.1",
        "@smithy/node-http-handler": "^4.0.4",
        "@smithy/protocol-http": "^5.1.0",
        "@smithy/smithy-client": "^4.2.6",
        "@smithy/types": "^4.2.0",
        "@smithy/url-parser": "^4.0.2",
        "@smithy/util-base64": "^4.0.0",
        "@smithy/util-body-length-browser": "^4.0.0",
        "@smithy/util-body-length-node": "^4.0.0",
        "@smithy/util-defaults-mode-browser": "^4.0.14",
        "@smithy/util-defaults-mode-node": "^4.0.14",
        "@smithy/util-endpoints": "^3.0.4",
        "@smithy/util-middleware": "^4.0.2",
        "@smithy/util-retry": "^4.0.3",
        "@smithy/util-utf8": "^4.0.0",
        tslib: "^2.6.2"
      },
      devDependencies: {
        "@tsconfig/node18": "18.2.4",
        "@types/node": "^18.19.69",
        concurrently: "7.0.0",
        "downlevel-dts": "0.10.1",
        rimraf: "3.0.2",
        typescript: "~5.8.3"
      },
      engines: {
        node: ">=18.0.0"
      },
      typesVersions: {
        "<4.0": {
          "dist-types/*": [
            "dist-types/ts3.4/*"
          ]
        }
      },
      files: [
        "dist-*/**"
      ],
      author: {
        name: "AWS SDK for JavaScript Team",
        url: "https://aws.amazon.com/javascript/"
      },
      license: "Apache-2.0",
      browser: {
        "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser"
      },
      "react-native": {
        "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native"
      },
      homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-sso",
      repository: {
        type: "git",
        url: "https://github.com/aws/aws-sdk-js-v3.git",
        directory: "clients/client-sso"
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/endpoint/ruleset.js
var u2, v2, w2, x3, a2, b2, c2, d2, e3, f4, g2, h3, i3, j2, k2, l2, m3, n2, o2, p2, q2, r3, s3, t3, _data2, ruleSet2;
var init_ruleset2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/endpoint/ruleset.js"() {
    "use strict";
    u2 = "required";
    v2 = "fn";
    w2 = "argv";
    x3 = "ref";
    a2 = true;
    b2 = "isSet";
    c2 = "booleanEquals";
    d2 = "error";
    e3 = "endpoint";
    f4 = "tree";
    g2 = "PartitionResult";
    h3 = "getAttr";
    i3 = { [u2]: false, "type": "String" };
    j2 = { [u2]: true, "default": false, "type": "Boolean" };
    k2 = { [x3]: "Endpoint" };
    l2 = { [v2]: c2, [w2]: [{ [x3]: "UseFIPS" }, true] };
    m3 = { [v2]: c2, [w2]: [{ [x3]: "UseDualStack" }, true] };
    n2 = {};
    o2 = { [v2]: h3, [w2]: [{ [x3]: g2 }, "supportsFIPS"] };
    p2 = { [x3]: g2 };
    q2 = { [v2]: c2, [w2]: [true, { [v2]: h3, [w2]: [p2, "supportsDualStack"] }] };
    r3 = [l2];
    s3 = [m3];
    t3 = [{ [x3]: "Region" }];
    _data2 = { version: "1.0", parameters: { Region: i3, UseDualStack: j2, UseFIPS: j2, Endpoint: i3 }, rules: [{ conditions: [{ [v2]: b2, [w2]: [k2] }], rules: [{ conditions: r3, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d2 }, { conditions: s3, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d2 }, { endpoint: { url: k2, properties: n2, headers: n2 }, type: e3 }], type: f4 }, { conditions: [{ [v2]: b2, [w2]: t3 }], rules: [{ conditions: [{ [v2]: "aws.partition", [w2]: t3, assign: g2 }], rules: [{ conditions: [l2, m3], rules: [{ conditions: [{ [v2]: c2, [w2]: [a2, o2] }, q2], rules: [{ endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n2, headers: n2 }, type: e3 }], type: f4 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d2 }], type: f4 }, { conditions: r3, rules: [{ conditions: [{ [v2]: c2, [w2]: [o2, a2] }], rules: [{ conditions: [{ [v2]: "stringEquals", [w2]: [{ [v2]: h3, [w2]: [p2, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://portal.sso.{Region}.amazonaws.com", properties: n2, headers: n2 }, type: e3 }, { endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n2, headers: n2 }, type: e3 }], type: f4 }, { error: "FIPS is enabled but this partition does not support FIPS", type: d2 }], type: f4 }, { conditions: s3, rules: [{ conditions: [q2], rules: [{ endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n2, headers: n2 }, type: e3 }], type: f4 }, { error: "DualStack is enabled but this partition does not support DualStack", type: d2 }], type: f4 }, { endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dnsSuffix}", properties: n2, headers: n2 }, type: e3 }], type: f4 }], type: f4 }, { error: "Invalid Configuration: Missing Region", type: d2 }] };
    ruleSet2 = _data2;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/endpoint/endpointResolver.js
var cache2, defaultEndpointResolver2;
var init_endpointResolver2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/endpoint/endpointResolver.js"() {
    "use strict";
    init_dist_es20();
    init_dist_es19();
    init_ruleset2();
    cache2 = new EndpointCache({
      size: 50,
      params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
    });
    defaultEndpointResolver2 = (endpointParams, context = {}) => {
      return cache2.get(endpointParams, () => resolveEndpoint(ruleSet2, {
        endpointParams,
        logger: context.logger
      }));
    };
    customEndpointFunctions.aws = awsEndpointFunctions;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.shared.js
var getRuntimeConfig3;
var init_runtimeConfig_shared2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.shared.js"() {
    "use strict";
    init_dist_es25();
    init_dist_es18();
    init_dist_es24();
    init_dist_es33();
    init_dist_es11();
    init_dist_es10();
    init_httpAuthSchemeProvider3();
    init_endpointResolver2();
    getRuntimeConfig3 = (config) => {
      return {
        apiVersion: "2019-06-10",
        base64Decoder: config?.base64Decoder ?? fromBase64,
        base64Encoder: config?.base64Encoder ?? toBase64,
        disableHostPrefix: config?.disableHostPrefix ?? false,
        endpointProvider: config?.endpointProvider ?? defaultEndpointResolver2,
        extensions: config?.extensions ?? [],
        httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOHttpAuthSchemeProvider,
        httpAuthSchemes: config?.httpAuthSchemes ?? [
          {
            schemeId: "aws.auth#sigv4",
            identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
            signer: new AwsSdkSigV4Signer()
          },
          {
            schemeId: "smithy.api#noAuth",
            identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
            signer: new NoAuthSigner()
          }
        ],
        logger: config?.logger ?? new NoOpLogger(),
        serviceId: config?.serviceId ?? "SSO",
        urlParser: config?.urlParser ?? parseUrl,
        utf8Decoder: config?.utf8Decoder ?? fromUtf8,
        utf8Encoder: config?.utf8Encoder ?? toUtf8
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.js
var getRuntimeConfig4;
var init_runtimeConfig2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.js"() {
    "use strict";
    init_package3();
    init_dist_es25();
    init_dist_es41();
    init_dist_es28();
    init_dist_es42();
    init_dist_es37();
    init_dist_es31();
    init_dist_es14();
    init_dist_es43();
    init_dist_es36();
    init_runtimeConfig_shared2();
    init_dist_es24();
    init_dist_es44();
    init_dist_es24();
    getRuntimeConfig4 = (config) => {
      emitWarningIfUnsupportedVersion2(process.version);
      const defaultsMode = resolveDefaultsModeConfig(config);
      const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);
      const clientSharedValues = getRuntimeConfig3(config);
      emitWarningIfUnsupportedVersion(process.version);
      const loaderConfig = {
        profile: config?.profile,
        logger: clientSharedValues.logger
      };
      return {
        ...clientSharedValues,
        ...config,
        runtime: "node",
        defaultsMode,
        authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
        bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,
        defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default3.version }),
        maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
        region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
        requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),
        retryMode: config?.retryMode ?? loadConfig({
          ...NODE_RETRY_MODE_CONFIG_OPTIONS,
          default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE
        }, config),
        sha256: config?.sha256 ?? Hash.bind(null, "sha256"),
        streamCollector: config?.streamCollector ?? streamCollector,
        useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
        useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
        userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/auth/httpAuthExtensionConfiguration.js
var getHttpAuthExtensionConfiguration2, resolveHttpAuthRuntimeConfig2;
var init_httpAuthExtensionConfiguration2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/auth/httpAuthExtensionConfiguration.js"() {
    "use strict";
    getHttpAuthExtensionConfiguration2 = (runtimeConfig) => {
      const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
      let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
      let _credentials = runtimeConfig.credentials;
      return {
        setHttpAuthScheme(httpAuthScheme) {
          const index6 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
          if (index6 === -1) {
            _httpAuthSchemes.push(httpAuthScheme);
          } else {
            _httpAuthSchemes.splice(index6, 1, httpAuthScheme);
          }
        },
        httpAuthSchemes() {
          return _httpAuthSchemes;
        },
        setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
          _httpAuthSchemeProvider = httpAuthSchemeProvider;
        },
        httpAuthSchemeProvider() {
          return _httpAuthSchemeProvider;
        },
        setCredentials(credentials2) {
          _credentials = credentials2;
        },
        credentials() {
          return _credentials;
        }
      };
    };
    resolveHttpAuthRuntimeConfig2 = (config) => {
      return {
        httpAuthSchemes: config.httpAuthSchemes(),
        httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
        credentials: config.credentials()
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/runtimeExtensions.js
var resolveRuntimeExtensions2;
var init_runtimeExtensions2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/runtimeExtensions.js"() {
    "use strict";
    init_dist_es45();
    init_dist_es2();
    init_dist_es24();
    init_httpAuthExtensionConfiguration2();
    resolveRuntimeExtensions2 = (runtimeConfig, extensions) => {
      const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration2(runtimeConfig));
      extensions.forEach((extension) => extension.configure(extensionConfiguration));
      return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig2(extensionConfiguration));
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/SSOClient.js
var SSOClient;
var init_SSOClient = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/SSOClient.js"() {
    "use strict";
    init_dist_es3();
    init_dist_es4();
    init_dist_es5();
    init_dist_es26();
    init_dist_es28();
    init_dist_es18();
    init_dist_es29();
    init_dist_es34();
    init_dist_es37();
    init_dist_es24();
    init_httpAuthSchemeProvider3();
    init_EndpointParameters3();
    init_runtimeConfig2();
    init_runtimeExtensions2();
    SSOClient = class extends Client {
      constructor(...[configuration]) {
        const _config_0 = getRuntimeConfig4(configuration || {});
        super(_config_0);
        __publicField(this, "config");
        this.initConfig = _config_0;
        const _config_1 = resolveClientEndpointParameters3(_config_0);
        const _config_2 = resolveUserAgentConfig(_config_1);
        const _config_3 = resolveRetryConfig(_config_2);
        const _config_4 = resolveRegionConfig(_config_3);
        const _config_5 = resolveHostHeaderConfig(_config_4);
        const _config_6 = resolveEndpointConfig(_config_5);
        const _config_7 = resolveHttpAuthSchemeConfig3(_config_6);
        const _config_8 = resolveRuntimeExtensions2(_config_7, configuration?.extensions || []);
        this.config = _config_8;
        this.middlewareStack.use(getUserAgentPlugin(this.config));
        this.middlewareStack.use(getRetryPlugin(this.config));
        this.middlewareStack.use(getContentLengthPlugin(this.config));
        this.middlewareStack.use(getHostHeaderPlugin(this.config));
        this.middlewareStack.use(getLoggerPlugin(this.config));
        this.middlewareStack.use(getRecursionDetectionPlugin(this.config));
        this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
          httpAuthSchemeParametersProvider: defaultSSOHttpAuthSchemeParametersProvider,
          identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({
            "aws.auth#sigv4": config.credentials
          })
        }));
        this.middlewareStack.use(getHttpSigningPlugin(this.config));
      }
      destroy() {
        super.destroy();
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/models/SSOServiceException.js
var SSOServiceException;
var init_SSOServiceException = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/models/SSOServiceException.js"() {
    "use strict";
    init_dist_es24();
    SSOServiceException = class _SSOServiceException extends ServiceException {
      constructor(options) {
        super(options);
        Object.setPrototypeOf(this, _SSOServiceException.prototype);
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/models/models_0.js
var InvalidRequestException2, ResourceNotFoundException, TooManyRequestsException, UnauthorizedException, GetRoleCredentialsRequestFilterSensitiveLog, RoleCredentialsFilterSensitiveLog, GetRoleCredentialsResponseFilterSensitiveLog, ListAccountRolesRequestFilterSensitiveLog, ListAccountsRequestFilterSensitiveLog, LogoutRequestFilterSensitiveLog;
var init_models_02 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/models/models_0.js"() {
    "use strict";
    init_dist_es24();
    init_SSOServiceException();
    InvalidRequestException2 = class _InvalidRequestException extends SSOServiceException {
      constructor(opts) {
        super({
          name: "InvalidRequestException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "InvalidRequestException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _InvalidRequestException.prototype);
      }
    };
    ResourceNotFoundException = class _ResourceNotFoundException extends SSOServiceException {
      constructor(opts) {
        super({
          name: "ResourceNotFoundException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "ResourceNotFoundException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _ResourceNotFoundException.prototype);
      }
    };
    TooManyRequestsException = class _TooManyRequestsException extends SSOServiceException {
      constructor(opts) {
        super({
          name: "TooManyRequestsException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "TooManyRequestsException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _TooManyRequestsException.prototype);
      }
    };
    UnauthorizedException = class _UnauthorizedException extends SSOServiceException {
      constructor(opts) {
        super({
          name: "UnauthorizedException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "UnauthorizedException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _UnauthorizedException.prototype);
      }
    };
    GetRoleCredentialsRequestFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.accessToken && { accessToken: SENSITIVE_STRING }
    });
    RoleCredentialsFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.secretAccessKey && { secretAccessKey: SENSITIVE_STRING },
      ...obj.sessionToken && { sessionToken: SENSITIVE_STRING }
    });
    GetRoleCredentialsResponseFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.roleCredentials && { roleCredentials: RoleCredentialsFilterSensitiveLog(obj.roleCredentials) }
    });
    ListAccountRolesRequestFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.accessToken && { accessToken: SENSITIVE_STRING }
    });
    ListAccountsRequestFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.accessToken && { accessToken: SENSITIVE_STRING }
    });
    LogoutRequestFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.accessToken && { accessToken: SENSITIVE_STRING }
    });
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/protocols/Aws_restJson1.js
var se_GetRoleCredentialsCommand, se_ListAccountRolesCommand, se_ListAccountsCommand, se_LogoutCommand, de_GetRoleCredentialsCommand, de_ListAccountRolesCommand, de_ListAccountsCommand, de_LogoutCommand, de_CommandError2, throwDefaultError3, de_InvalidRequestExceptionRes2, de_ResourceNotFoundExceptionRes, de_TooManyRequestsExceptionRes, de_UnauthorizedExceptionRes, deserializeMetadata3, _aI, _aT, _ai, _mR, _mr, _nT, _nt, _rN, _rn, _xasbt;
var init_Aws_restJson12 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/protocols/Aws_restJson1.js"() {
    "use strict";
    init_dist_es25();
    init_dist_es18();
    init_dist_es24();
    init_models_02();
    init_SSOServiceException();
    se_GetRoleCredentialsCommand = async (input, context) => {
      const b5 = requestBuilder(input, context);
      const headers = map({}, isSerializableHeaderValue, {
        [_xasbt]: input[_aT]
      });
      b5.bp("/federation/credentials");
      const query = map({
        [_rn]: [, expectNonNull(input[_rN], `roleName`)],
        [_ai]: [, expectNonNull(input[_aI], `accountId`)]
      });
      let body;
      b5.m("GET").h(headers).q(query).b(body);
      return b5.build();
    };
    se_ListAccountRolesCommand = async (input, context) => {
      const b5 = requestBuilder(input, context);
      const headers = map({}, isSerializableHeaderValue, {
        [_xasbt]: input[_aT]
      });
      b5.bp("/assignment/roles");
      const query = map({
        [_nt]: [, input[_nT]],
        [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()],
        [_ai]: [, expectNonNull(input[_aI], `accountId`)]
      });
      let body;
      b5.m("GET").h(headers).q(query).b(body);
      return b5.build();
    };
    se_ListAccountsCommand = async (input, context) => {
      const b5 = requestBuilder(input, context);
      const headers = map({}, isSerializableHeaderValue, {
        [_xasbt]: input[_aT]
      });
      b5.bp("/assignment/accounts");
      const query = map({
        [_nt]: [, input[_nT]],
        [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()]
      });
      let body;
      b5.m("GET").h(headers).q(query).b(body);
      return b5.build();
    };
    se_LogoutCommand = async (input, context) => {
      const b5 = requestBuilder(input, context);
      const headers = map({}, isSerializableHeaderValue, {
        [_xasbt]: input[_aT]
      });
      b5.bp("/logout");
      let body;
      b5.m("POST").h(headers).b(body);
      return b5.build();
    };
    de_GetRoleCredentialsCommand = async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError2(output, context);
      }
      const contents = map({
        $metadata: deserializeMetadata3(output)
      });
      const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
      const doc = take(data, {
        roleCredentials: _json
      });
      Object.assign(contents, doc);
      return contents;
    };
    de_ListAccountRolesCommand = async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError2(output, context);
      }
      const contents = map({
        $metadata: deserializeMetadata3(output)
      });
      const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
      const doc = take(data, {
        nextToken: expectString,
        roleList: _json
      });
      Object.assign(contents, doc);
      return contents;
    };
    de_ListAccountsCommand = async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError2(output, context);
      }
      const contents = map({
        $metadata: deserializeMetadata3(output)
      });
      const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
      const doc = take(data, {
        accountList: _json,
        nextToken: expectString
      });
      Object.assign(contents, doc);
      return contents;
    };
    de_LogoutCommand = async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError2(output, context);
      }
      const contents = map({
        $metadata: deserializeMetadata3(output)
      });
      await collectBody(output.body, context);
      return contents;
    };
    de_CommandError2 = async (output, context) => {
      const parsedOutput = {
        ...output,
        body: await parseJsonErrorBody(output.body, context)
      };
      const errorCode = loadRestJsonErrorCode(output, parsedOutput.body);
      switch (errorCode) {
        case "InvalidRequestException":
        case "com.amazonaws.sso#InvalidRequestException":
          throw await de_InvalidRequestExceptionRes2(parsedOutput, context);
        case "ResourceNotFoundException":
        case "com.amazonaws.sso#ResourceNotFoundException":
          throw await de_ResourceNotFoundExceptionRes(parsedOutput, context);
        case "TooManyRequestsException":
        case "com.amazonaws.sso#TooManyRequestsException":
          throw await de_TooManyRequestsExceptionRes(parsedOutput, context);
        case "UnauthorizedException":
        case "com.amazonaws.sso#UnauthorizedException":
          throw await de_UnauthorizedExceptionRes(parsedOutput, context);
        default:
          const parsedBody = parsedOutput.body;
          return throwDefaultError3({
            output,
            parsedBody,
            errorCode
          });
      }
    };
    throwDefaultError3 = withBaseException(SSOServiceException);
    de_InvalidRequestExceptionRes2 = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        message: expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidRequestException2({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_ResourceNotFoundExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        message: expectString
      });
      Object.assign(contents, doc);
      const exception = new ResourceNotFoundException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_TooManyRequestsExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        message: expectString
      });
      Object.assign(contents, doc);
      const exception = new TooManyRequestsException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_UnauthorizedExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        message: expectString
      });
      Object.assign(contents, doc);
      const exception = new UnauthorizedException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    deserializeMetadata3 = (output) => ({
      httpStatusCode: output.statusCode,
      requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
      extendedRequestId: output.headers["x-amz-id-2"],
      cfId: output.headers["x-amz-cf-id"]
    });
    _aI = "accountId";
    _aT = "accessToken";
    _ai = "account_id";
    _mR = "maxResults";
    _mr = "max_result";
    _nT = "nextToken";
    _nt = "next_token";
    _rN = "roleName";
    _rn = "role_name";
    _xasbt = "x-amz-sso_bearer_token";
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/GetRoleCredentialsCommand.js
var GetRoleCredentialsCommand;
var init_GetRoleCredentialsCommand = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/GetRoleCredentialsCommand.js"() {
    "use strict";
    init_dist_es34();
    init_dist_es7();
    init_dist_es24();
    init_EndpointParameters3();
    init_models_02();
    init_Aws_restJson12();
    GetRoleCredentialsCommand = class extends Command.classBuilder().ep(commonParams3).m(function(Command2, cs, config, o5) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
      ];
    }).s("SWBPortalService", "GetRoleCredentials", {}).n("SSOClient", "GetRoleCredentialsCommand").f(GetRoleCredentialsRequestFilterSensitiveLog, GetRoleCredentialsResponseFilterSensitiveLog).ser(se_GetRoleCredentialsCommand).de(de_GetRoleCredentialsCommand).build() {
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/ListAccountRolesCommand.js
var ListAccountRolesCommand;
var init_ListAccountRolesCommand = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/ListAccountRolesCommand.js"() {
    "use strict";
    init_dist_es34();
    init_dist_es7();
    init_dist_es24();
    init_EndpointParameters3();
    init_models_02();
    init_Aws_restJson12();
    ListAccountRolesCommand = class extends Command.classBuilder().ep(commonParams3).m(function(Command2, cs, config, o5) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
      ];
    }).s("SWBPortalService", "ListAccountRoles", {}).n("SSOClient", "ListAccountRolesCommand").f(ListAccountRolesRequestFilterSensitiveLog, void 0).ser(se_ListAccountRolesCommand).de(de_ListAccountRolesCommand).build() {
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/ListAccountsCommand.js
var ListAccountsCommand;
var init_ListAccountsCommand = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/ListAccountsCommand.js"() {
    "use strict";
    init_dist_es34();
    init_dist_es7();
    init_dist_es24();
    init_EndpointParameters3();
    init_models_02();
    init_Aws_restJson12();
    ListAccountsCommand = class extends Command.classBuilder().ep(commonParams3).m(function(Command2, cs, config, o5) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
      ];
    }).s("SWBPortalService", "ListAccounts", {}).n("SSOClient", "ListAccountsCommand").f(ListAccountsRequestFilterSensitiveLog, void 0).ser(se_ListAccountsCommand).de(de_ListAccountsCommand).build() {
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/LogoutCommand.js
var LogoutCommand;
var init_LogoutCommand = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/LogoutCommand.js"() {
    "use strict";
    init_dist_es34();
    init_dist_es7();
    init_dist_es24();
    init_EndpointParameters3();
    init_models_02();
    init_Aws_restJson12();
    LogoutCommand = class extends Command.classBuilder().ep(commonParams3).m(function(Command2, cs, config, o5) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
      ];
    }).s("SWBPortalService", "Logout", {}).n("SSOClient", "LogoutCommand").f(LogoutRequestFilterSensitiveLog, void 0).ser(se_LogoutCommand).de(de_LogoutCommand).build() {
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/SSO.js
var commands2, SSO;
var init_SSO = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/SSO.js"() {
    "use strict";
    init_dist_es24();
    init_GetRoleCredentialsCommand();
    init_ListAccountRolesCommand();
    init_ListAccountsCommand();
    init_LogoutCommand();
    init_SSOClient();
    commands2 = {
      GetRoleCredentialsCommand,
      ListAccountRolesCommand,
      ListAccountsCommand,
      LogoutCommand
    };
    SSO = class extends SSOClient {
    };
    createAggregatedClient(commands2, SSO);
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/index.js
var init_commands2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/index.js"() {
    "use strict";
    init_GetRoleCredentialsCommand();
    init_ListAccountRolesCommand();
    init_ListAccountsCommand();
    init_LogoutCommand();
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/Interfaces.js
var init_Interfaces = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/Interfaces.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountRolesPaginator.js
var paginateListAccountRoles;
var init_ListAccountRolesPaginator = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountRolesPaginator.js"() {
    "use strict";
    init_dist_es18();
    init_ListAccountRolesCommand();
    init_SSOClient();
    paginateListAccountRoles = createPaginator(SSOClient, ListAccountRolesCommand, "nextToken", "nextToken", "maxResults");
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountsPaginator.js
var paginateListAccounts;
var init_ListAccountsPaginator = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountsPaginator.js"() {
    "use strict";
    init_dist_es18();
    init_ListAccountsCommand();
    init_SSOClient();
    paginateListAccounts = createPaginator(SSOClient, ListAccountsCommand, "nextToken", "nextToken", "maxResults");
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/index.js
var init_pagination2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/index.js"() {
    "use strict";
    init_Interfaces();
    init_ListAccountRolesPaginator();
    init_ListAccountsPaginator();
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/models/index.js
var init_models2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/models/index.js"() {
    "use strict";
    init_models_02();
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/index.js
var init_dist_es47 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/index.js"() {
    "use strict";
    init_SSOClient();
    init_SSO();
    init_commands2();
    init_pagination2();
    init_models2();
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/loadSso.js
var loadSso_exports = {};
__export(loadSso_exports, {
  GetRoleCredentialsCommand: () => GetRoleCredentialsCommand,
  SSOClient: () => SSOClient
});
var init_loadSso = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/loadSso.js"() {
    "use strict";
    init_dist_es47();
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/resolveSSOCredentials.js
var SHOULD_FAIL_CREDENTIAL_CHAIN, resolveSSOCredentials;
var init_resolveSSOCredentials = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/resolveSSOCredentials.js"() {
    "use strict";
    init_client2();
    init_dist_es46();
    init_dist_es21();
    init_dist_es30();
    SHOULD_FAIL_CREDENTIAL_CHAIN = false;
    resolveSSOCredentials = async ({ ssoStartUrl, ssoSession, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, clientConfig, parentClientConfig, profile, logger: logger2 }) => {
      let token;
      const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`;
      if (ssoSession) {
        try {
          const _token = await fromSso({ profile })();
          token = {
            accessToken: _token.token,
            expiresAt: new Date(_token.expiration).toISOString()
          };
        } catch (e6) {
          throw new CredentialsProviderError(e6.message, {
            tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
            logger: logger2
          });
        }
      } else {
        try {
          token = await getSSOTokenFromFile(ssoStartUrl);
        } catch (e6) {
          throw new CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, {
            tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
            logger: logger2
          });
        }
      }
      if (new Date(token.expiresAt).getTime() - Date.now() <= 0) {
        throw new CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, {
          tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
          logger: logger2
        });
      }
      const { accessToken } = token;
      const { SSOClient: SSOClient2, GetRoleCredentialsCommand: GetRoleCredentialsCommand2 } = await Promise.resolve().then(() => (init_loadSso(), loadSso_exports));
      const sso = ssoClient || new SSOClient2(Object.assign({}, clientConfig ?? {}, {
        logger: clientConfig?.logger ?? parentClientConfig?.logger,
        region: clientConfig?.region ?? ssoRegion
      }));
      let ssoResp;
      try {
        ssoResp = await sso.send(new GetRoleCredentialsCommand2({
          accountId: ssoAccountId,
          roleName: ssoRoleName,
          accessToken
        }));
      } catch (e6) {
        throw new CredentialsProviderError(e6, {
          tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
          logger: logger2
        });
      }
      const { roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {} } = ssoResp;
      if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) {
        throw new CredentialsProviderError("SSO returns an invalid temporary credential.", {
          tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
          logger: logger2
        });
      }
      const credentials2 = {
        accessKeyId,
        secretAccessKey,
        sessionToken,
        expiration: new Date(expiration),
        ...credentialScope && { credentialScope },
        ...accountId && { accountId }
      };
      if (ssoSession) {
        setCredentialFeature(credentials2, "CREDENTIALS_SSO", "s");
      } else {
        setCredentialFeature(credentials2, "CREDENTIALS_SSO_LEGACY", "u");
      }
      return credentials2;
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/validateSsoProfile.js
var validateSsoProfile;
var init_validateSsoProfile = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/validateSsoProfile.js"() {
    "use strict";
    init_dist_es21();
    validateSsoProfile = (profile, logger2) => {
      const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile;
      if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) {
        throw new CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(profile).join(", ")}
Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, { tryNextLink: false, logger: logger2 });
      }
      return profile;
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/fromSSO.js
var fromSSO;
var init_fromSSO = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/fromSSO.js"() {
    "use strict";
    init_dist_es21();
    init_dist_es30();
    init_isSsoProfile();
    init_resolveSSOCredentials();
    init_validateSsoProfile();
    fromSSO = (init2 = {}) => async ({ callerClientConfig } = {}) => {
      init2.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO");
      const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init2;
      const { ssoClient } = init2;
      const profileName = getProfileName({
        profile: init2.profile ?? callerClientConfig?.profile
      });
      if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {
        const profiles = await parseKnownFiles(init2);
        const profile = profiles[profileName];
        if (!profile) {
          throw new CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init2.logger });
        }
        if (!isSsoProfile(profile)) {
          throw new CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, {
            logger: init2.logger
          });
        }
        if (profile?.sso_session) {
          const ssoSessions = await loadSsoSessionData(init2);
          const session = ssoSessions[profile.sso_session];
          const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`;
          if (ssoRegion && ssoRegion !== session.sso_region) {
            throw new CredentialsProviderError(`Conflicting SSO region` + conflictMsg, {
              tryNextLink: false,
              logger: init2.logger
            });
          }
          if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) {
            throw new CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, {
              tryNextLink: false,
              logger: init2.logger
            });
          }
          profile.sso_region = session.sso_region;
          profile.sso_start_url = session.sso_start_url;
        }
        const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile(profile, init2.logger);
        return resolveSSOCredentials({
          ssoStartUrl: sso_start_url,
          ssoSession: sso_session,
          ssoAccountId: sso_account_id,
          ssoRegion: sso_region,
          ssoRoleName: sso_role_name,
          ssoClient,
          clientConfig: init2.clientConfig,
          parentClientConfig: init2.parentClientConfig,
          profile: profileName
        });
      } else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) {
        throw new CredentialsProviderError('Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"', { tryNextLink: false, logger: init2.logger });
      } else {
        return resolveSSOCredentials({
          ssoStartUrl,
          ssoSession,
          ssoAccountId,
          ssoRegion,
          ssoRoleName,
          ssoClient,
          clientConfig: init2.clientConfig,
          parentClientConfig: init2.parentClientConfig,
          profile: profileName
        });
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/types.js
var init_types10 = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/types.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/index.js
var dist_es_exports4 = {};
__export(dist_es_exports4, {
  fromSSO: () => fromSSO,
  isSsoProfile: () => isSsoProfile,
  validateSsoProfile: () => validateSsoProfile
});
var init_dist_es48 = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/index.js"() {
    "use strict";
    init_fromSSO();
    init_isSsoProfile();
    init_types10();
    init_validateSsoProfile();
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveCredentialSource.js
var resolveCredentialSource, setNamedProvider;
var init_resolveCredentialSource = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveCredentialSource.js"() {
    "use strict";
    init_client2();
    init_dist_es21();
    resolveCredentialSource = (credentialSource, profileName, logger2) => {
      const sourceProvidersMap = {
        EcsContainer: async (options) => {
          const { fromHttp: fromHttp2 } = await Promise.resolve().then(() => (init_dist_es40(), dist_es_exports3));
          const { fromContainerMetadata: fromContainerMetadata2 } = await Promise.resolve().then(() => (init_dist_es39(), dist_es_exports2));
          logger2?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer");
          return async () => chain(fromHttp2(options ?? {}), fromContainerMetadata2(options))().then(setNamedProvider);
        },
        Ec2InstanceMetadata: async (options) => {
          logger2?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");
          const { fromInstanceMetadata: fromInstanceMetadata2 } = await Promise.resolve().then(() => (init_dist_es39(), dist_es_exports2));
          return async () => fromInstanceMetadata2(options)().then(setNamedProvider);
        },
        Environment: async (options) => {
          logger2?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");
          const { fromEnv: fromEnv3 } = await Promise.resolve().then(() => (init_dist_es38(), dist_es_exports));
          return async () => fromEnv3(options)().then(setNamedProvider);
        }
      };
      if (credentialSource in sourceProvidersMap) {
        return sourceProvidersMap[credentialSource];
      } else {
        throw new CredentialsProviderError(`Unsupported credential source in profile ${profileName}. Got ${credentialSource}, expected EcsContainer or Ec2InstanceMetadata or Environment.`, { logger: logger2 });
      }
    };
    setNamedProvider = (creds) => setCredentialFeature(creds, "CREDENTIALS_PROFILE_NAMED_PROVIDER", "p");
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthSchemeProvider.js
function createAwsAuthSigv4HttpAuthOption4(authParameters) {
  return {
    schemeId: "aws.auth#sigv4",
    signingProperties: {
      name: "sts",
      region: authParameters.region
    },
    propertiesExtractor: (config, context) => ({
      signingProperties: {
        config,
        context
      }
    })
  };
}
function createSmithyApiNoAuthHttpAuthOption3(authParameters) {
  return {
    schemeId: "smithy.api#noAuth"
  };
}
var defaultSTSHttpAuthSchemeParametersProvider, defaultSTSHttpAuthSchemeProvider, resolveStsAuthConfig, resolveHttpAuthSchemeConfig4;
var init_httpAuthSchemeProvider4 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthSchemeProvider.js"() {
    "use strict";
    init_dist_es25();
    init_dist_es6();
    init_STSClient();
    defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => {
      return {
        operation: getSmithyContext(context).operation,
        region: await normalizeProvider(config.region)() || (() => {
          throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
        })()
      };
    };
    defaultSTSHttpAuthSchemeProvider = (authParameters) => {
      const options = [];
      switch (authParameters.operation) {
        case "AssumeRoleWithWebIdentity": {
          options.push(createSmithyApiNoAuthHttpAuthOption3(authParameters));
          break;
        }
        default: {
          options.push(createAwsAuthSigv4HttpAuthOption4(authParameters));
        }
      }
      return options;
    };
    resolveStsAuthConfig = (input) => Object.assign(input, {
      stsClientCtor: STSClient
    });
    resolveHttpAuthSchemeConfig4 = (config) => {
      const config_0 = resolveStsAuthConfig(config);
      const config_1 = resolveAwsSdkSigV4Config(config_0);
      return Object.assign(config_1, {
        authSchemePreference: normalizeProvider(config.authSchemePreference ?? [])
      });
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/EndpointParameters.js
var resolveClientEndpointParameters4, commonParams4;
var init_EndpointParameters4 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/EndpointParameters.js"() {
    "use strict";
    resolveClientEndpointParameters4 = (options) => {
      return Object.assign(options, {
        useDualstackEndpoint: options.useDualstackEndpoint ?? false,
        useFipsEndpoint: options.useFipsEndpoint ?? false,
        useGlobalEndpoint: options.useGlobalEndpoint ?? false,
        defaultSigningName: "sts"
      });
    };
    commonParams4 = {
      UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" },
      UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
      Endpoint: { type: "builtInParams", name: "endpoint" },
      Region: { type: "builtInParams", name: "region" },
      UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/ruleset.js
var F2, G, H, I, J, a3, b3, c3, d3, e4, f5, g3, h4, i4, j3, k3, l3, m4, n3, o3, p3, q3, r4, s4, t4, u3, v3, w3, x4, y, z, A2, B, C, D, E, _data3, ruleSet3;
var init_ruleset3 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/ruleset.js"() {
    "use strict";
    F2 = "required";
    G = "type";
    H = "fn";
    I = "argv";
    J = "ref";
    a3 = false;
    b3 = true;
    c3 = "booleanEquals";
    d3 = "stringEquals";
    e4 = "sigv4";
    f5 = "sts";
    g3 = "us-east-1";
    h4 = "endpoint";
    i4 = "https://sts.{Region}.{PartitionResult#dnsSuffix}";
    j3 = "tree";
    k3 = "error";
    l3 = "getAttr";
    m4 = { [F2]: false, [G]: "String" };
    n3 = { [F2]: true, "default": false, [G]: "Boolean" };
    o3 = { [J]: "Endpoint" };
    p3 = { [H]: "isSet", [I]: [{ [J]: "Region" }] };
    q3 = { [J]: "Region" };
    r4 = { [H]: "aws.partition", [I]: [q3], "assign": "PartitionResult" };
    s4 = { [J]: "UseFIPS" };
    t4 = { [J]: "UseDualStack" };
    u3 = { "url": "https://sts.amazonaws.com", "properties": { "authSchemes": [{ "name": e4, "signingName": f5, "signingRegion": g3 }] }, "headers": {} };
    v3 = {};
    w3 = { "conditions": [{ [H]: d3, [I]: [q3, "aws-global"] }], [h4]: u3, [G]: h4 };
    x4 = { [H]: c3, [I]: [s4, true] };
    y = { [H]: c3, [I]: [t4, true] };
    z = { [H]: l3, [I]: [{ [J]: "PartitionResult" }, "supportsFIPS"] };
    A2 = { [J]: "PartitionResult" };
    B = { [H]: c3, [I]: [true, { [H]: l3, [I]: [A2, "supportsDualStack"] }] };
    C = [{ [H]: "isSet", [I]: [o3] }];
    D = [x4];
    E = [y];
    _data3 = { version: "1.0", parameters: { Region: m4, UseDualStack: n3, UseFIPS: n3, Endpoint: m4, UseGlobalEndpoint: n3 }, rules: [{ conditions: [{ [H]: c3, [I]: [{ [J]: "UseGlobalEndpoint" }, b3] }, { [H]: "not", [I]: C }, p3, r4, { [H]: c3, [I]: [s4, a3] }, { [H]: c3, [I]: [t4, a3] }], rules: [{ conditions: [{ [H]: d3, [I]: [q3, "ap-northeast-1"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "ap-south-1"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "ap-southeast-1"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "ap-southeast-2"] }], endpoint: u3, [G]: h4 }, w3, { conditions: [{ [H]: d3, [I]: [q3, "ca-central-1"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "eu-central-1"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "eu-north-1"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "eu-west-1"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "eu-west-2"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "eu-west-3"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "sa-east-1"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, g3] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "us-east-2"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "us-west-1"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "us-west-2"] }], endpoint: u3, [G]: h4 }, { endpoint: { url: i4, properties: { authSchemes: [{ name: e4, signingName: f5, signingRegion: "{Region}" }] }, headers: v3 }, [G]: h4 }], [G]: j3 }, { conditions: C, rules: [{ conditions: D, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G]: k3 }, { conditions: E, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G]: k3 }, { endpoint: { url: o3, properties: v3, headers: v3 }, [G]: h4 }], [G]: j3 }, { conditions: [p3], rules: [{ conditions: [r4], rules: [{ conditions: [x4, y], rules: [{ conditions: [{ [H]: c3, [I]: [b3, z] }, B], rules: [{ endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v3, headers: v3 }, [G]: h4 }], [G]: j3 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G]: k3 }], [G]: j3 }, { conditions: D, rules: [{ conditions: [{ [H]: c3, [I]: [z, b3] }], rules: [{ conditions: [{ [H]: d3, [I]: [{ [H]: l3, [I]: [A2, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v3, headers: v3 }, [G]: h4 }, { endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", properties: v3, headers: v3 }, [G]: h4 }], [G]: j3 }, { error: "FIPS is enabled but this partition does not support FIPS", [G]: k3 }], [G]: j3 }, { conditions: E, rules: [{ conditions: [B], rules: [{ endpoint: { url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v3, headers: v3 }, [G]: h4 }], [G]: j3 }, { error: "DualStack is enabled but this partition does not support DualStack", [G]: k3 }], [G]: j3 }, w3, { endpoint: { url: i4, properties: v3, headers: v3 }, [G]: h4 }], [G]: j3 }], [G]: j3 }, { error: "Invalid Configuration: Missing Region", [G]: k3 }] };
    ruleSet3 = _data3;
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/endpointResolver.js
var cache3, defaultEndpointResolver3;
var init_endpointResolver3 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/endpointResolver.js"() {
    "use strict";
    init_dist_es20();
    init_dist_es19();
    init_ruleset3();
    cache3 = new EndpointCache({
      size: 50,
      params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"]
    });
    defaultEndpointResolver3 = (endpointParams, context = {}) => {
      return cache3.get(endpointParams, () => resolveEndpoint(ruleSet3, {
        endpointParams,
        logger: context.logger
      }));
    };
    customEndpointFunctions.aws = awsEndpointFunctions;
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.shared.js
var getRuntimeConfig5;
var init_runtimeConfig_shared3 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.shared.js"() {
    "use strict";
    init_dist_es25();
    init_dist_es18();
    init_dist_es24();
    init_dist_es33();
    init_dist_es11();
    init_dist_es10();
    init_httpAuthSchemeProvider4();
    init_endpointResolver3();
    getRuntimeConfig5 = (config) => {
      return {
        apiVersion: "2011-06-15",
        base64Decoder: config?.base64Decoder ?? fromBase64,
        base64Encoder: config?.base64Encoder ?? toBase64,
        disableHostPrefix: config?.disableHostPrefix ?? false,
        endpointProvider: config?.endpointProvider ?? defaultEndpointResolver3,
        extensions: config?.extensions ?? [],
        httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSTSHttpAuthSchemeProvider,
        httpAuthSchemes: config?.httpAuthSchemes ?? [
          {
            schemeId: "aws.auth#sigv4",
            identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
            signer: new AwsSdkSigV4Signer()
          },
          {
            schemeId: "smithy.api#noAuth",
            identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
            signer: new NoAuthSigner()
          }
        ],
        logger: config?.logger ?? new NoOpLogger(),
        serviceId: config?.serviceId ?? "STS",
        urlParser: config?.urlParser ?? parseUrl,
        utf8Decoder: config?.utf8Decoder ?? fromUtf8,
        utf8Encoder: config?.utf8Encoder ?? toUtf8
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.js
var getRuntimeConfig6;
var init_runtimeConfig3 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.js"() {
    "use strict";
    init_package2();
    init_dist_es25();
    init_dist_es41();
    init_dist_es28();
    init_dist_es18();
    init_dist_es42();
    init_dist_es37();
    init_dist_es31();
    init_dist_es14();
    init_dist_es43();
    init_dist_es36();
    init_runtimeConfig_shared3();
    init_dist_es24();
    init_dist_es44();
    init_dist_es24();
    getRuntimeConfig6 = (config) => {
      emitWarningIfUnsupportedVersion2(process.version);
      const defaultsMode = resolveDefaultsModeConfig(config);
      const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);
      const clientSharedValues = getRuntimeConfig5(config);
      emitWarningIfUnsupportedVersion(process.version);
      const loaderConfig = {
        profile: config?.profile,
        logger: clientSharedValues.logger
      };
      return {
        ...clientSharedValues,
        ...config,
        runtime: "node",
        defaultsMode,
        authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
        bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,
        defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default2.version }),
        httpAuthSchemes: config?.httpAuthSchemes ?? [
          {
            schemeId: "aws.auth#sigv4",
            identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || (async (idProps) => await config.credentialDefaultProvider(idProps?.__config || {})()),
            signer: new AwsSdkSigV4Signer()
          },
          {
            schemeId: "smithy.api#noAuth",
            identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
            signer: new NoAuthSigner()
          }
        ],
        maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
        region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
        requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),
        retryMode: config?.retryMode ?? loadConfig({
          ...NODE_RETRY_MODE_CONFIG_OPTIONS,
          default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE
        }, config),
        sha256: config?.sha256 ?? Hash.bind(null, "sha256"),
        streamCollector: config?.streamCollector ?? streamCollector,
        useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
        useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
        userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthExtensionConfiguration.js
var getHttpAuthExtensionConfiguration3, resolveHttpAuthRuntimeConfig3;
var init_httpAuthExtensionConfiguration3 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthExtensionConfiguration.js"() {
    "use strict";
    getHttpAuthExtensionConfiguration3 = (runtimeConfig) => {
      const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
      let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
      let _credentials = runtimeConfig.credentials;
      return {
        setHttpAuthScheme(httpAuthScheme) {
          const index6 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
          if (index6 === -1) {
            _httpAuthSchemes.push(httpAuthScheme);
          } else {
            _httpAuthSchemes.splice(index6, 1, httpAuthScheme);
          }
        },
        httpAuthSchemes() {
          return _httpAuthSchemes;
        },
        setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
          _httpAuthSchemeProvider = httpAuthSchemeProvider;
        },
        httpAuthSchemeProvider() {
          return _httpAuthSchemeProvider;
        },
        setCredentials(credentials2) {
          _credentials = credentials2;
        },
        credentials() {
          return _credentials;
        }
      };
    };
    resolveHttpAuthRuntimeConfig3 = (config) => {
      return {
        httpAuthSchemes: config.httpAuthSchemes(),
        httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
        credentials: config.credentials()
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeExtensions.js
var resolveRuntimeExtensions3;
var init_runtimeExtensions3 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeExtensions.js"() {
    "use strict";
    init_dist_es45();
    init_dist_es2();
    init_dist_es24();
    init_httpAuthExtensionConfiguration3();
    resolveRuntimeExtensions3 = (runtimeConfig, extensions) => {
      const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration3(runtimeConfig));
      extensions.forEach((extension) => extension.configure(extensionConfiguration));
      return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig3(extensionConfiguration));
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STSClient.js
var STSClient;
var init_STSClient = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STSClient.js"() {
    "use strict";
    init_dist_es3();
    init_dist_es4();
    init_dist_es5();
    init_dist_es26();
    init_dist_es28();
    init_dist_es18();
    init_dist_es29();
    init_dist_es34();
    init_dist_es37();
    init_dist_es24();
    init_httpAuthSchemeProvider4();
    init_EndpointParameters4();
    init_runtimeConfig3();
    init_runtimeExtensions3();
    STSClient = class extends Client {
      constructor(...[configuration]) {
        const _config_0 = getRuntimeConfig6(configuration || {});
        super(_config_0);
        __publicField(this, "config");
        this.initConfig = _config_0;
        const _config_1 = resolveClientEndpointParameters4(_config_0);
        const _config_2 = resolveUserAgentConfig(_config_1);
        const _config_3 = resolveRetryConfig(_config_2);
        const _config_4 = resolveRegionConfig(_config_3);
        const _config_5 = resolveHostHeaderConfig(_config_4);
        const _config_6 = resolveEndpointConfig(_config_5);
        const _config_7 = resolveHttpAuthSchemeConfig4(_config_6);
        const _config_8 = resolveRuntimeExtensions3(_config_7, configuration?.extensions || []);
        this.config = _config_8;
        this.middlewareStack.use(getUserAgentPlugin(this.config));
        this.middlewareStack.use(getRetryPlugin(this.config));
        this.middlewareStack.use(getContentLengthPlugin(this.config));
        this.middlewareStack.use(getHostHeaderPlugin(this.config));
        this.middlewareStack.use(getLoggerPlugin(this.config));
        this.middlewareStack.use(getRecursionDetectionPlugin(this.config));
        this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
          httpAuthSchemeParametersProvider: defaultSTSHttpAuthSchemeParametersProvider,
          identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({
            "aws.auth#sigv4": config.credentials
          })
        }));
        this.middlewareStack.use(getHttpSigningPlugin(this.config));
      }
      destroy() {
        super.destroy();
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/STSServiceException.js
var STSServiceException;
var init_STSServiceException = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/STSServiceException.js"() {
    "use strict";
    init_dist_es24();
    STSServiceException = class _STSServiceException extends ServiceException {
      constructor(options) {
        super(options);
        Object.setPrototypeOf(this, _STSServiceException.prototype);
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/models_0.js
var CredentialsFilterSensitiveLog, AssumeRoleResponseFilterSensitiveLog, ExpiredTokenException2, MalformedPolicyDocumentException, PackedPolicyTooLargeException, RegionDisabledException, IDPRejectedClaimException, InvalidIdentityTokenException, AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog, IDPCommunicationErrorException;
var init_models_03 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/models_0.js"() {
    "use strict";
    init_dist_es24();
    init_STSServiceException();
    CredentialsFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.SecretAccessKey && { SecretAccessKey: SENSITIVE_STRING }
    });
    AssumeRoleResponseFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
    });
    ExpiredTokenException2 = class _ExpiredTokenException extends STSServiceException {
      constructor(opts) {
        super({
          name: "ExpiredTokenException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "ExpiredTokenException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _ExpiredTokenException.prototype);
      }
    };
    MalformedPolicyDocumentException = class _MalformedPolicyDocumentException extends STSServiceException {
      constructor(opts) {
        super({
          name: "MalformedPolicyDocumentException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "MalformedPolicyDocumentException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _MalformedPolicyDocumentException.prototype);
      }
    };
    PackedPolicyTooLargeException = class _PackedPolicyTooLargeException extends STSServiceException {
      constructor(opts) {
        super({
          name: "PackedPolicyTooLargeException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "PackedPolicyTooLargeException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _PackedPolicyTooLargeException.prototype);
      }
    };
    RegionDisabledException = class _RegionDisabledException extends STSServiceException {
      constructor(opts) {
        super({
          name: "RegionDisabledException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "RegionDisabledException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _RegionDisabledException.prototype);
      }
    };
    IDPRejectedClaimException = class _IDPRejectedClaimException extends STSServiceException {
      constructor(opts) {
        super({
          name: "IDPRejectedClaimException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "IDPRejectedClaimException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _IDPRejectedClaimException.prototype);
      }
    };
    InvalidIdentityTokenException = class _InvalidIdentityTokenException extends STSServiceException {
      constructor(opts) {
        super({
          name: "InvalidIdentityTokenException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "InvalidIdentityTokenException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _InvalidIdentityTokenException.prototype);
      }
    };
    AssumeRoleWithWebIdentityRequestFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.WebIdentityToken && { WebIdentityToken: SENSITIVE_STRING }
    });
    AssumeRoleWithWebIdentityResponseFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
    });
    IDPCommunicationErrorException = class _IDPCommunicationErrorException extends STSServiceException {
      constructor(opts) {
        super({
          name: "IDPCommunicationErrorException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "IDPCommunicationErrorException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _IDPCommunicationErrorException.prototype);
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/protocols/Aws_query.js
var se_AssumeRoleCommand, se_AssumeRoleWithWebIdentityCommand, de_AssumeRoleCommand, de_AssumeRoleWithWebIdentityCommand, de_CommandError3, de_ExpiredTokenExceptionRes2, de_IDPCommunicationErrorExceptionRes, de_IDPRejectedClaimExceptionRes, de_InvalidIdentityTokenExceptionRes, de_MalformedPolicyDocumentExceptionRes, de_PackedPolicyTooLargeExceptionRes, de_RegionDisabledExceptionRes, se_AssumeRoleRequest, se_AssumeRoleWithWebIdentityRequest, se_policyDescriptorListType, se_PolicyDescriptorType, se_ProvidedContext, se_ProvidedContextsListType, se_Tag, se_tagKeyListType, se_tagListType, de_AssumedRoleUser, de_AssumeRoleResponse, de_AssumeRoleWithWebIdentityResponse, de_Credentials, de_ExpiredTokenException, de_IDPCommunicationErrorException, de_IDPRejectedClaimException, de_InvalidIdentityTokenException, de_MalformedPolicyDocumentException, de_PackedPolicyTooLargeException, de_RegionDisabledException, deserializeMetadata4, throwDefaultError4, buildHttpRpcRequest, SHARED_HEADERS, _2, _A, _AKI, _AR, _ARI, _ARU, _ARWWI, _Ar, _Au, _C, _CA, _DS, _E, _EI, _K, _P, _PA, _PAr, _PC, _PI, _PPS, _Pr, _RA, _RSN, _SAK, _SFWIT, _SI, _SN, _ST, _T, _TC, _TTK, _V, _Va, _WIT, _a14, _m, buildFormUrlencodedString, loadQueryErrorCode;
var init_Aws_query = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/protocols/Aws_query.js"() {
    "use strict";
    init_dist_es25();
    init_dist_es2();
    init_dist_es24();
    init_models_03();
    init_STSServiceException();
    se_AssumeRoleCommand = async (input, context) => {
      const headers = SHARED_HEADERS;
      let body;
      body = buildFormUrlencodedString({
        ...se_AssumeRoleRequest(input, context),
        [_A]: _AR,
        [_V]: _2
      });
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_AssumeRoleWithWebIdentityCommand = async (input, context) => {
      const headers = SHARED_HEADERS;
      let body;
      body = buildFormUrlencodedString({
        ...se_AssumeRoleWithWebIdentityRequest(input, context),
        [_A]: _ARWWI,
        [_V]: _2
      });
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    de_AssumeRoleCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError3(output, context);
      }
      const data = await parseXmlBody(output.body, context);
      let contents = {};
      contents = de_AssumeRoleResponse(data.AssumeRoleResult, context);
      const response = {
        $metadata: deserializeMetadata4(output),
        ...contents
      };
      return response;
    };
    de_AssumeRoleWithWebIdentityCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError3(output, context);
      }
      const data = await parseXmlBody(output.body, context);
      let contents = {};
      contents = de_AssumeRoleWithWebIdentityResponse(data.AssumeRoleWithWebIdentityResult, context);
      const response = {
        $metadata: deserializeMetadata4(output),
        ...contents
      };
      return response;
    };
    de_CommandError3 = async (output, context) => {
      const parsedOutput = {
        ...output,
        body: await parseXmlErrorBody(output.body, context)
      };
      const errorCode = loadQueryErrorCode(output, parsedOutput.body);
      switch (errorCode) {
        case "ExpiredTokenException":
        case "com.amazonaws.sts#ExpiredTokenException":
          throw await de_ExpiredTokenExceptionRes2(parsedOutput, context);
        case "MalformedPolicyDocument":
        case "com.amazonaws.sts#MalformedPolicyDocumentException":
          throw await de_MalformedPolicyDocumentExceptionRes(parsedOutput, context);
        case "PackedPolicyTooLarge":
        case "com.amazonaws.sts#PackedPolicyTooLargeException":
          throw await de_PackedPolicyTooLargeExceptionRes(parsedOutput, context);
        case "RegionDisabledException":
        case "com.amazonaws.sts#RegionDisabledException":
          throw await de_RegionDisabledExceptionRes(parsedOutput, context);
        case "IDPCommunicationError":
        case "com.amazonaws.sts#IDPCommunicationErrorException":
          throw await de_IDPCommunicationErrorExceptionRes(parsedOutput, context);
        case "IDPRejectedClaim":
        case "com.amazonaws.sts#IDPRejectedClaimException":
          throw await de_IDPRejectedClaimExceptionRes(parsedOutput, context);
        case "InvalidIdentityToken":
        case "com.amazonaws.sts#InvalidIdentityTokenException":
          throw await de_InvalidIdentityTokenExceptionRes(parsedOutput, context);
        default:
          const parsedBody = parsedOutput.body;
          return throwDefaultError4({
            output,
            parsedBody: parsedBody.Error,
            errorCode
          });
      }
    };
    de_ExpiredTokenExceptionRes2 = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_ExpiredTokenException(body.Error, context);
      const exception = new ExpiredTokenException2({
        $metadata: deserializeMetadata4(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_IDPCommunicationErrorExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_IDPCommunicationErrorException(body.Error, context);
      const exception = new IDPCommunicationErrorException({
        $metadata: deserializeMetadata4(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_IDPRejectedClaimExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_IDPRejectedClaimException(body.Error, context);
      const exception = new IDPRejectedClaimException({
        $metadata: deserializeMetadata4(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_InvalidIdentityTokenExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_InvalidIdentityTokenException(body.Error, context);
      const exception = new InvalidIdentityTokenException({
        $metadata: deserializeMetadata4(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_MalformedPolicyDocumentExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_MalformedPolicyDocumentException(body.Error, context);
      const exception = new MalformedPolicyDocumentException({
        $metadata: deserializeMetadata4(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_PackedPolicyTooLargeExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_PackedPolicyTooLargeException(body.Error, context);
      const exception = new PackedPolicyTooLargeException({
        $metadata: deserializeMetadata4(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_RegionDisabledExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_RegionDisabledException(body.Error, context);
      const exception = new RegionDisabledException({
        $metadata: deserializeMetadata4(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    se_AssumeRoleRequest = (input, context) => {
      const entries = {};
      if (input[_RA] != null) {
        entries[_RA] = input[_RA];
      }
      if (input[_RSN] != null) {
        entries[_RSN] = input[_RSN];
      }
      if (input[_PA] != null) {
        const memberEntries = se_policyDescriptorListType(input[_PA], context);
        if (input[_PA]?.length === 0) {
          entries.PolicyArns = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `PolicyArns.${key}`;
          entries[loc] = value;
        });
      }
      if (input[_P] != null) {
        entries[_P] = input[_P];
      }
      if (input[_DS] != null) {
        entries[_DS] = input[_DS];
      }
      if (input[_T] != null) {
        const memberEntries = se_tagListType(input[_T], context);
        if (input[_T]?.length === 0) {
          entries.Tags = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `Tags.${key}`;
          entries[loc] = value;
        });
      }
      if (input[_TTK] != null) {
        const memberEntries = se_tagKeyListType(input[_TTK], context);
        if (input[_TTK]?.length === 0) {
          entries.TransitiveTagKeys = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `TransitiveTagKeys.${key}`;
          entries[loc] = value;
        });
      }
      if (input[_EI] != null) {
        entries[_EI] = input[_EI];
      }
      if (input[_SN] != null) {
        entries[_SN] = input[_SN];
      }
      if (input[_TC] != null) {
        entries[_TC] = input[_TC];
      }
      if (input[_SI] != null) {
        entries[_SI] = input[_SI];
      }
      if (input[_PC] != null) {
        const memberEntries = se_ProvidedContextsListType(input[_PC], context);
        if (input[_PC]?.length === 0) {
          entries.ProvidedContexts = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `ProvidedContexts.${key}`;
          entries[loc] = value;
        });
      }
      return entries;
    };
    se_AssumeRoleWithWebIdentityRequest = (input, context) => {
      const entries = {};
      if (input[_RA] != null) {
        entries[_RA] = input[_RA];
      }
      if (input[_RSN] != null) {
        entries[_RSN] = input[_RSN];
      }
      if (input[_WIT] != null) {
        entries[_WIT] = input[_WIT];
      }
      if (input[_PI] != null) {
        entries[_PI] = input[_PI];
      }
      if (input[_PA] != null) {
        const memberEntries = se_policyDescriptorListType(input[_PA], context);
        if (input[_PA]?.length === 0) {
          entries.PolicyArns = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `PolicyArns.${key}`;
          entries[loc] = value;
        });
      }
      if (input[_P] != null) {
        entries[_P] = input[_P];
      }
      if (input[_DS] != null) {
        entries[_DS] = input[_DS];
      }
      return entries;
    };
    se_policyDescriptorListType = (input, context) => {
      const entries = {};
      let counter = 1;
      for (const entry of input) {
        if (entry === null) {
          continue;
        }
        const memberEntries = se_PolicyDescriptorType(entry, context);
        Object.entries(memberEntries).forEach(([key, value]) => {
          entries[`member.${counter}.${key}`] = value;
        });
        counter++;
      }
      return entries;
    };
    se_PolicyDescriptorType = (input, context) => {
      const entries = {};
      if (input[_a14] != null) {
        entries[_a14] = input[_a14];
      }
      return entries;
    };
    se_ProvidedContext = (input, context) => {
      const entries = {};
      if (input[_PAr] != null) {
        entries[_PAr] = input[_PAr];
      }
      if (input[_CA] != null) {
        entries[_CA] = input[_CA];
      }
      return entries;
    };
    se_ProvidedContextsListType = (input, context) => {
      const entries = {};
      let counter = 1;
      for (const entry of input) {
        if (entry === null) {
          continue;
        }
        const memberEntries = se_ProvidedContext(entry, context);
        Object.entries(memberEntries).forEach(([key, value]) => {
          entries[`member.${counter}.${key}`] = value;
        });
        counter++;
      }
      return entries;
    };
    se_Tag = (input, context) => {
      const entries = {};
      if (input[_K] != null) {
        entries[_K] = input[_K];
      }
      if (input[_Va] != null) {
        entries[_Va] = input[_Va];
      }
      return entries;
    };
    se_tagKeyListType = (input, context) => {
      const entries = {};
      let counter = 1;
      for (const entry of input) {
        if (entry === null) {
          continue;
        }
        entries[`member.${counter}`] = entry;
        counter++;
      }
      return entries;
    };
    se_tagListType = (input, context) => {
      const entries = {};
      let counter = 1;
      for (const entry of input) {
        if (entry === null) {
          continue;
        }
        const memberEntries = se_Tag(entry, context);
        Object.entries(memberEntries).forEach(([key, value]) => {
          entries[`member.${counter}.${key}`] = value;
        });
        counter++;
      }
      return entries;
    };
    de_AssumedRoleUser = (output, context) => {
      const contents = {};
      if (output[_ARI] != null) {
        contents[_ARI] = expectString(output[_ARI]);
      }
      if (output[_Ar] != null) {
        contents[_Ar] = expectString(output[_Ar]);
      }
      return contents;
    };
    de_AssumeRoleResponse = (output, context) => {
      const contents = {};
      if (output[_C] != null) {
        contents[_C] = de_Credentials(output[_C], context);
      }
      if (output[_ARU] != null) {
        contents[_ARU] = de_AssumedRoleUser(output[_ARU], context);
      }
      if (output[_PPS] != null) {
        contents[_PPS] = strictParseInt32(output[_PPS]);
      }
      if (output[_SI] != null) {
        contents[_SI] = expectString(output[_SI]);
      }
      return contents;
    };
    de_AssumeRoleWithWebIdentityResponse = (output, context) => {
      const contents = {};
      if (output[_C] != null) {
        contents[_C] = de_Credentials(output[_C], context);
      }
      if (output[_SFWIT] != null) {
        contents[_SFWIT] = expectString(output[_SFWIT]);
      }
      if (output[_ARU] != null) {
        contents[_ARU] = de_AssumedRoleUser(output[_ARU], context);
      }
      if (output[_PPS] != null) {
        contents[_PPS] = strictParseInt32(output[_PPS]);
      }
      if (output[_Pr] != null) {
        contents[_Pr] = expectString(output[_Pr]);
      }
      if (output[_Au] != null) {
        contents[_Au] = expectString(output[_Au]);
      }
      if (output[_SI] != null) {
        contents[_SI] = expectString(output[_SI]);
      }
      return contents;
    };
    de_Credentials = (output, context) => {
      const contents = {};
      if (output[_AKI] != null) {
        contents[_AKI] = expectString(output[_AKI]);
      }
      if (output[_SAK] != null) {
        contents[_SAK] = expectString(output[_SAK]);
      }
      if (output[_ST] != null) {
        contents[_ST] = expectString(output[_ST]);
      }
      if (output[_E] != null) {
        contents[_E] = expectNonNull(parseRfc3339DateTimeWithOffset(output[_E]));
      }
      return contents;
    };
    de_ExpiredTokenException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = expectString(output[_m]);
      }
      return contents;
    };
    de_IDPCommunicationErrorException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = expectString(output[_m]);
      }
      return contents;
    };
    de_IDPRejectedClaimException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = expectString(output[_m]);
      }
      return contents;
    };
    de_InvalidIdentityTokenException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = expectString(output[_m]);
      }
      return contents;
    };
    de_MalformedPolicyDocumentException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = expectString(output[_m]);
      }
      return contents;
    };
    de_PackedPolicyTooLargeException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = expectString(output[_m]);
      }
      return contents;
    };
    de_RegionDisabledException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = expectString(output[_m]);
      }
      return contents;
    };
    deserializeMetadata4 = (output) => ({
      httpStatusCode: output.statusCode,
      requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
      extendedRequestId: output.headers["x-amz-id-2"],
      cfId: output.headers["x-amz-cf-id"]
    });
    throwDefaultError4 = withBaseException(STSServiceException);
    buildHttpRpcRequest = async (context, headers, path3, resolvedHostname, body) => {
      const { hostname, protocol = "https", port, path: basePath } = await context.endpoint();
      const contents = {
        protocol,
        hostname,
        port,
        method: "POST",
        path: basePath.endsWith("/") ? basePath.slice(0, -1) + path3 : basePath + path3,
        headers
      };
      if (resolvedHostname !== void 0) {
        contents.hostname = resolvedHostname;
      }
      if (body !== void 0) {
        contents.body = body;
      }
      return new HttpRequest(contents);
    };
    SHARED_HEADERS = {
      "content-type": "application/x-www-form-urlencoded"
    };
    _2 = "2011-06-15";
    _A = "Action";
    _AKI = "AccessKeyId";
    _AR = "AssumeRole";
    _ARI = "AssumedRoleId";
    _ARU = "AssumedRoleUser";
    _ARWWI = "AssumeRoleWithWebIdentity";
    _Ar = "Arn";
    _Au = "Audience";
    _C = "Credentials";
    _CA = "ContextAssertion";
    _DS = "DurationSeconds";
    _E = "Expiration";
    _EI = "ExternalId";
    _K = "Key";
    _P = "Policy";
    _PA = "PolicyArns";
    _PAr = "ProviderArn";
    _PC = "ProvidedContexts";
    _PI = "ProviderId";
    _PPS = "PackedPolicySize";
    _Pr = "Provider";
    _RA = "RoleArn";
    _RSN = "RoleSessionName";
    _SAK = "SecretAccessKey";
    _SFWIT = "SubjectFromWebIdentityToken";
    _SI = "SourceIdentity";
    _SN = "SerialNumber";
    _ST = "SessionToken";
    _T = "Tags";
    _TC = "TokenCode";
    _TTK = "TransitiveTagKeys";
    _V = "Version";
    _Va = "Value";
    _WIT = "WebIdentityToken";
    _a14 = "arn";
    _m = "message";
    buildFormUrlencodedString = (formEntries) => Object.entries(formEntries).map(([key, value]) => extendedEncodeURIComponent(key) + "=" + extendedEncodeURIComponent(value)).join("&");
    loadQueryErrorCode = (output, data) => {
      if (data.Error?.Code !== void 0) {
        return data.Error.Code;
      }
      if (output.statusCode == 404) {
        return "NotFound";
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleCommand.js
var AssumeRoleCommand;
var init_AssumeRoleCommand = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleCommand.js"() {
    "use strict";
    init_dist_es34();
    init_dist_es7();
    init_dist_es24();
    init_EndpointParameters4();
    init_models_03();
    init_Aws_query();
    AssumeRoleCommand = class extends Command.classBuilder().ep(commonParams4).m(function(Command2, cs, config, o5) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").f(void 0, AssumeRoleResponseFilterSensitiveLog).ser(se_AssumeRoleCommand).de(de_AssumeRoleCommand).build() {
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.js
var AssumeRoleWithWebIdentityCommand;
var init_AssumeRoleWithWebIdentityCommand = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.js"() {
    "use strict";
    init_dist_es34();
    init_dist_es7();
    init_dist_es24();
    init_EndpointParameters4();
    init_models_03();
    init_Aws_query();
    AssumeRoleWithWebIdentityCommand = class extends Command.classBuilder().ep(commonParams4).m(function(Command2, cs, config, o5) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").f(AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog).ser(se_AssumeRoleWithWebIdentityCommand).de(de_AssumeRoleWithWebIdentityCommand).build() {
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STS.js
var commands3, STS;
var init_STS = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STS.js"() {
    "use strict";
    init_dist_es24();
    init_AssumeRoleCommand();
    init_AssumeRoleWithWebIdentityCommand();
    init_STSClient();
    commands3 = {
      AssumeRoleCommand,
      AssumeRoleWithWebIdentityCommand
    };
    STS = class extends STSClient {
    };
    createAggregatedClient(commands3, STS);
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/index.js
var init_commands3 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/index.js"() {
    "use strict";
    init_AssumeRoleCommand();
    init_AssumeRoleWithWebIdentityCommand();
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/index.js
var init_models3 = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/index.js"() {
    "use strict";
    init_models_03();
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultStsRoleAssumers.js
var ASSUME_ROLE_DEFAULT_REGION, getAccountIdFromAssumedRoleUser, resolveRegion, getDefaultRoleAssumer, getDefaultRoleAssumerWithWebIdentity, isH2;
var init_defaultStsRoleAssumers = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultStsRoleAssumers.js"() {
    "use strict";
    init_client2();
    init_AssumeRoleCommand();
    init_AssumeRoleWithWebIdentityCommand();
    ASSUME_ROLE_DEFAULT_REGION = "us-east-1";
    getAccountIdFromAssumedRoleUser = (assumedRoleUser) => {
      if (typeof assumedRoleUser?.Arn === "string") {
        const arnComponents = assumedRoleUser.Arn.split(":");
        if (arnComponents.length > 4 && arnComponents[4] !== "") {
          return arnComponents[4];
        }
      }
      return void 0;
    };
    resolveRegion = async (_region, _parentRegion, credentialProviderLogger) => {
      const region = typeof _region === "function" ? await _region() : _region;
      const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion;
      credentialProviderLogger?.debug?.("@aws-sdk/client-sts::resolveRegion", "accepting first of:", `${region} (provider)`, `${parentRegion} (parent client)`, `${ASSUME_ROLE_DEFAULT_REGION} (STS default)`);
      return region ?? parentRegion ?? ASSUME_ROLE_DEFAULT_REGION;
    };
    getDefaultRoleAssumer = (stsOptions, STSClient2) => {
      let stsClient;
      let closureSourceCreds;
      return async (sourceCreds, params) => {
        closureSourceCreds = sourceCreds;
        if (!stsClient) {
          const { logger: logger2 = stsOptions?.parentClientConfig?.logger, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger } = stsOptions;
          const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger);
          const isCompatibleRequestHandler = !isH2(requestHandler);
          stsClient = new STSClient2({
            profile: stsOptions?.parentClientConfig?.profile,
            credentialDefaultProvider: () => async () => closureSourceCreds,
            region: resolvedRegion,
            requestHandler: isCompatibleRequestHandler ? requestHandler : void 0,
            logger: logger2
          });
        }
        const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleCommand(params));
        if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {
          throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`);
        }
        const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser);
        const credentials2 = {
          accessKeyId: Credentials.AccessKeyId,
          secretAccessKey: Credentials.SecretAccessKey,
          sessionToken: Credentials.SessionToken,
          expiration: Credentials.Expiration,
          ...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope },
          ...accountId && { accountId }
        };
        setCredentialFeature(credentials2, "CREDENTIALS_STS_ASSUME_ROLE", "i");
        return credentials2;
      };
    };
    getDefaultRoleAssumerWithWebIdentity = (stsOptions, STSClient2) => {
      let stsClient;
      return async (params) => {
        if (!stsClient) {
          const { logger: logger2 = stsOptions?.parentClientConfig?.logger, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger } = stsOptions;
          const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger);
          const isCompatibleRequestHandler = !isH2(requestHandler);
          stsClient = new STSClient2({
            profile: stsOptions?.parentClientConfig?.profile,
            region: resolvedRegion,
            requestHandler: isCompatibleRequestHandler ? requestHandler : void 0,
            logger: logger2
          });
        }
        const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params));
        if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {
          throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`);
        }
        const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser);
        const credentials2 = {
          accessKeyId: Credentials.AccessKeyId,
          secretAccessKey: Credentials.SecretAccessKey,
          sessionToken: Credentials.SessionToken,
          expiration: Credentials.Expiration,
          ...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope },
          ...accountId && { accountId }
        };
        if (accountId) {
          setCredentialFeature(credentials2, "RESOLVED_ACCOUNT_ID", "T");
        }
        setCredentialFeature(credentials2, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k");
        return credentials2;
      };
    };
    isH2 = (requestHandler) => {
      return requestHandler?.metadata?.handlerProtocol === "h2";
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultRoleAssumers.js
var getCustomizableStsClientCtor, getDefaultRoleAssumer2, getDefaultRoleAssumerWithWebIdentity2, decorateDefaultCredentialProvider;
var init_defaultRoleAssumers = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultRoleAssumers.js"() {
    "use strict";
    init_defaultStsRoleAssumers();
    init_STSClient();
    getCustomizableStsClientCtor = (baseCtor, customizations) => {
      if (!customizations)
        return baseCtor;
      else
        return class CustomizableSTSClient extends baseCtor {
          constructor(config) {
            super(config);
            for (const customization of customizations) {
              this.middlewareStack.use(customization);
            }
          }
        };
    };
    getDefaultRoleAssumer2 = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins));
    getDefaultRoleAssumerWithWebIdentity2 = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins));
    decorateDefaultCredentialProvider = (provider) => (input) => provider({
      roleAssumer: getDefaultRoleAssumer2(input),
      roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input),
      ...input
    });
  }
});

// ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/index.js
var sts_exports = {};
__export(sts_exports, {
  $Command: () => Command,
  AssumeRoleCommand: () => AssumeRoleCommand,
  AssumeRoleResponseFilterSensitiveLog: () => AssumeRoleResponseFilterSensitiveLog,
  AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand,
  AssumeRoleWithWebIdentityRequestFilterSensitiveLog: () => AssumeRoleWithWebIdentityRequestFilterSensitiveLog,
  AssumeRoleWithWebIdentityResponseFilterSensitiveLog: () => AssumeRoleWithWebIdentityResponseFilterSensitiveLog,
  CredentialsFilterSensitiveLog: () => CredentialsFilterSensitiveLog,
  ExpiredTokenException: () => ExpiredTokenException2,
  IDPCommunicationErrorException: () => IDPCommunicationErrorException,
  IDPRejectedClaimException: () => IDPRejectedClaimException,
  InvalidIdentityTokenException: () => InvalidIdentityTokenException,
  MalformedPolicyDocumentException: () => MalformedPolicyDocumentException,
  PackedPolicyTooLargeException: () => PackedPolicyTooLargeException,
  RegionDisabledException: () => RegionDisabledException,
  STS: () => STS,
  STSClient: () => STSClient,
  STSServiceException: () => STSServiceException,
  __Client: () => Client,
  decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider,
  getDefaultRoleAssumer: () => getDefaultRoleAssumer2,
  getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2
});
var init_sts = __esm({
  "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/index.js"() {
    "use strict";
    init_STSClient();
    init_STS();
    init_commands3();
    init_models3();
    init_defaultRoleAssumers();
    init_STSServiceException();
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveAssumeRoleCredentials.js
var isAssumeRoleProfile, isAssumeRoleWithSourceProfile, isCredentialSourceProfile, resolveAssumeRoleCredentials, isCredentialSourceWithoutRoleArn;
var init_resolveAssumeRoleCredentials = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveAssumeRoleCredentials.js"() {
    "use strict";
    init_client2();
    init_dist_es21();
    init_dist_es30();
    init_resolveCredentialSource();
    init_resolveProfileData();
    isAssumeRoleProfile = (arg, { profile = "default", logger: logger2 } = {}) => {
      return Boolean(arg) && typeof arg === "object" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1 && ["undefined", "string"].indexOf(typeof arg.external_id) > -1 && ["undefined", "string"].indexOf(typeof arg.mfa_serial) > -1 && (isAssumeRoleWithSourceProfile(arg, { profile, logger: logger2 }) || isCredentialSourceProfile(arg, { profile, logger: logger2 }));
    };
    isAssumeRoleWithSourceProfile = (arg, { profile, logger: logger2 }) => {
      const withSourceProfile = typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined";
      if (withSourceProfile) {
        logger2?.debug?.(`    ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`);
      }
      return withSourceProfile;
    };
    isCredentialSourceProfile = (arg, { profile, logger: logger2 }) => {
      const withProviderProfile = typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined";
      if (withProviderProfile) {
        logger2?.debug?.(`    ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`);
      }
      return withProviderProfile;
    };
    resolveAssumeRoleCredentials = async (profileName, profiles, options, visitedProfiles = {}) => {
      options.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");
      const profileData = profiles[profileName];
      const { source_profile, region } = profileData;
      if (!options.roleAssumer) {
        const { getDefaultRoleAssumer: getDefaultRoleAssumer3 } = await Promise.resolve().then(() => (init_sts(), sts_exports));
        options.roleAssumer = getDefaultRoleAssumer3({
          ...options.clientConfig,
          credentialProviderLogger: options.logger,
          parentClientConfig: {
            ...options?.parentClientConfig,
            region: region ?? options?.parentClientConfig?.region
          }
        }, options.clientPlugins);
      }
      if (source_profile && source_profile in visitedProfiles) {
        throw new CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile ${getProfileName(options)}. Profiles visited: ` + Object.keys(visitedProfiles).join(", "), { logger: options.logger });
      }
      options.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}`);
      const sourceCredsProvider = source_profile ? resolveProfileData(source_profile, profiles, options, {
        ...visitedProfiles,
        [source_profile]: true
      }, isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {})) : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))();
      if (isCredentialSourceWithoutRoleArn(profileData)) {
        return sourceCredsProvider.then((creds) => setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o"));
      } else {
        const params = {
          RoleArn: profileData.role_arn,
          RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`,
          ExternalId: profileData.external_id,
          DurationSeconds: parseInt(profileData.duration_seconds || "3600", 10)
        };
        const { mfa_serial } = profileData;
        if (mfa_serial) {
          if (!options.mfaCodeProvider) {
            throw new CredentialsProviderError(`Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, { logger: options.logger, tryNextLink: false });
          }
          params.SerialNumber = mfa_serial;
          params.TokenCode = await options.mfaCodeProvider(mfa_serial);
        }
        const sourceCreds = await sourceCredsProvider;
        return options.roleAssumer(sourceCreds, params).then((creds) => setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o"));
      }
    };
    isCredentialSourceWithoutRoleArn = (section) => {
      return !section.role_arn && !!section.credential_source;
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-es/getValidatedProcessCredentials.js
var getValidatedProcessCredentials;
var init_getValidatedProcessCredentials = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-es/getValidatedProcessCredentials.js"() {
    "use strict";
    init_client2();
    getValidatedProcessCredentials = (profileName, data, profiles) => {
      if (data.Version !== 1) {
        throw Error(`Profile ${profileName} credential_process did not return Version 1.`);
      }
      if (data.AccessKeyId === void 0 || data.SecretAccessKey === void 0) {
        throw Error(`Profile ${profileName} credential_process returned invalid credentials.`);
      }
      if (data.Expiration) {
        const currentTime = /* @__PURE__ */ new Date();
        const expireTime = new Date(data.Expiration);
        if (expireTime < currentTime) {
          throw Error(`Profile ${profileName} credential_process returned expired credentials.`);
        }
      }
      let accountId = data.AccountId;
      if (!accountId && profiles?.[profileName]?.aws_account_id) {
        accountId = profiles[profileName].aws_account_id;
      }
      const credentials2 = {
        accessKeyId: data.AccessKeyId,
        secretAccessKey: data.SecretAccessKey,
        ...data.SessionToken && { sessionToken: data.SessionToken },
        ...data.Expiration && { expiration: new Date(data.Expiration) },
        ...data.CredentialScope && { credentialScope: data.CredentialScope },
        ...accountId && { accountId }
      };
      setCredentialFeature(credentials2, "CREDENTIALS_PROCESS", "w");
      return credentials2;
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-es/resolveProcessCredentials.js
var import_child_process, import_util6, resolveProcessCredentials;
var init_resolveProcessCredentials = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-es/resolveProcessCredentials.js"() {
    "use strict";
    init_dist_es21();
    import_child_process = require("child_process");
    import_util6 = require("util");
    init_getValidatedProcessCredentials();
    resolveProcessCredentials = async (profileName, profiles, logger2) => {
      const profile = profiles[profileName];
      if (profiles[profileName]) {
        const credentialProcess = profile["credential_process"];
        if (credentialProcess !== void 0) {
          const execPromise = (0, import_util6.promisify)(import_child_process.exec);
          try {
            const { stdout } = await execPromise(credentialProcess);
            let data;
            try {
              data = JSON.parse(stdout.trim());
            } catch {
              throw Error(`Profile ${profileName} credential_process returned invalid JSON.`);
            }
            return getValidatedProcessCredentials(profileName, data, profiles);
          } catch (error2) {
            throw new CredentialsProviderError(error2.message, { logger: logger2 });
          }
        } else {
          throw new CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger: logger2 });
        }
      } else {
        throw new CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, {
          logger: logger2
        });
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-es/fromProcess.js
var fromProcess;
var init_fromProcess = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-es/fromProcess.js"() {
    "use strict";
    init_dist_es30();
    init_resolveProcessCredentials();
    fromProcess = (init2 = {}) => async ({ callerClientConfig } = {}) => {
      init2.logger?.debug("@aws-sdk/credential-provider-process - fromProcess");
      const profiles = await parseKnownFiles(init2);
      return resolveProcessCredentials(getProfileName({
        profile: init2.profile ?? callerClientConfig?.profile
      }), profiles, init2.logger);
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-es/index.js
var dist_es_exports5 = {};
__export(dist_es_exports5, {
  fromProcess: () => fromProcess
});
var init_dist_es49 = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-es/index.js"() {
    "use strict";
    init_fromProcess();
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProcessCredentials.js
var isProcessProfile, resolveProcessCredentials2;
var init_resolveProcessCredentials2 = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProcessCredentials.js"() {
    "use strict";
    init_client2();
    isProcessProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string";
    resolveProcessCredentials2 = async (options, profile) => Promise.resolve().then(() => (init_dist_es49(), dist_es_exports5)).then(({ fromProcess: fromProcess2 }) => fromProcess2({
      ...options,
      profile
    })().then((creds) => setCredentialFeature(creds, "CREDENTIALS_PROFILE_PROCESS", "v")));
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveSsoCredentials.js
var resolveSsoCredentials, isSsoProfile2;
var init_resolveSsoCredentials = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveSsoCredentials.js"() {
    "use strict";
    init_client2();
    resolveSsoCredentials = async (profile, profileData, options = {}) => {
      const { fromSSO: fromSSO2 } = await Promise.resolve().then(() => (init_dist_es48(), dist_es_exports4));
      return fromSSO2({
        profile,
        logger: options.logger,
        parentClientConfig: options.parentClientConfig,
        clientConfig: options.clientConfig
      })().then((creds) => {
        if (profileData.sso_session) {
          return setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO", "r");
        } else {
          return setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO_LEGACY", "t");
        }
      });
    };
    isSsoProfile2 = (arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string");
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveStaticCredentials.js
var isStaticCredsProfile, resolveStaticCredentials;
var init_resolveStaticCredentials = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveStaticCredentials.js"() {
    "use strict";
    init_client2();
    isStaticCredsProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.aws_access_key_id === "string" && typeof arg.aws_secret_access_key === "string" && ["undefined", "string"].indexOf(typeof arg.aws_session_token) > -1 && ["undefined", "string"].indexOf(typeof arg.aws_account_id) > -1;
    resolveStaticCredentials = async (profile, options) => {
      options?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");
      const credentials2 = {
        accessKeyId: profile.aws_access_key_id,
        secretAccessKey: profile.aws_secret_access_key,
        sessionToken: profile.aws_session_token,
        ...profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope },
        ...profile.aws_account_id && { accountId: profile.aws_account_id }
      };
      return setCredentialFeature(credentials2, "CREDENTIALS_PROFILE", "n");
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromWebToken.js
var fromWebToken;
var init_fromWebToken = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromWebToken.js"() {
    "use strict";
    fromWebToken = (init2) => async (awsIdentityProperties) => {
      init2.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken");
      const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy: policy5, durationSeconds } = init2;
      let { roleAssumerWithWebIdentity } = init2;
      if (!roleAssumerWithWebIdentity) {
        const { getDefaultRoleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity3 } = await Promise.resolve().then(() => (init_sts(), sts_exports));
        roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity3({
          ...init2.clientConfig,
          credentialProviderLogger: init2.logger,
          parentClientConfig: {
            ...awsIdentityProperties?.callerClientConfig,
            ...init2.parentClientConfig
          }
        }, init2.clientPlugins);
      }
      return roleAssumerWithWebIdentity({
        RoleArn: roleArn,
        RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`,
        WebIdentityToken: webIdentityToken,
        ProviderId: providerId,
        PolicyArns: policyArns,
        Policy: policy5,
        DurationSeconds: durationSeconds
      });
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromTokenFile.js
var import_fs7, ENV_TOKEN_FILE, ENV_ROLE_ARN, ENV_ROLE_SESSION_NAME, fromTokenFile;
var init_fromTokenFile = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromTokenFile.js"() {
    "use strict";
    init_client2();
    init_dist_es21();
    import_fs7 = require("fs");
    init_fromWebToken();
    ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE";
    ENV_ROLE_ARN = "AWS_ROLE_ARN";
    ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME";
    fromTokenFile = (init2 = {}) => async () => {
      init2.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile");
      const webIdentityTokenFile = init2?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE];
      const roleArn = init2?.roleArn ?? process.env[ENV_ROLE_ARN];
      const roleSessionName = init2?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME];
      if (!webIdentityTokenFile || !roleArn) {
        throw new CredentialsProviderError("Web identity configuration not specified", {
          logger: init2.logger
        });
      }
      const credentials2 = await fromWebToken({
        ...init2,
        webIdentityToken: (0, import_fs7.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }),
        roleArn,
        roleSessionName
      })();
      if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) {
        setCredentialFeature(credentials2, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h");
      }
      return credentials2;
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/index.js
var dist_es_exports6 = {};
__export(dist_es_exports6, {
  fromTokenFile: () => fromTokenFile,
  fromWebToken: () => fromWebToken
});
var init_dist_es50 = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/index.js"() {
    "use strict";
    init_fromTokenFile();
    init_fromWebToken();
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveWebIdentityCredentials.js
var isWebIdentityProfile, resolveWebIdentityCredentials;
var init_resolveWebIdentityCredentials = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveWebIdentityCredentials.js"() {
    "use strict";
    init_client2();
    isWebIdentityProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.web_identity_token_file === "string" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1;
    resolveWebIdentityCredentials = async (profile, options) => Promise.resolve().then(() => (init_dist_es50(), dist_es_exports6)).then(({ fromTokenFile: fromTokenFile2 }) => fromTokenFile2({
      webIdentityTokenFile: profile.web_identity_token_file,
      roleArn: profile.role_arn,
      roleSessionName: profile.role_session_name,
      roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity,
      logger: options.logger,
      parentClientConfig: options.parentClientConfig
    })().then((creds) => setCredentialFeature(creds, "CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN", "q")));
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProfileData.js
var resolveProfileData;
var init_resolveProfileData = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProfileData.js"() {
    "use strict";
    init_dist_es21();
    init_resolveAssumeRoleCredentials();
    init_resolveProcessCredentials2();
    init_resolveSsoCredentials();
    init_resolveStaticCredentials();
    init_resolveWebIdentityCredentials();
    resolveProfileData = async (profileName, profiles, options, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => {
      const data = profiles[profileName];
      if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) {
        return resolveStaticCredentials(data, options);
      }
      if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) {
        return resolveAssumeRoleCredentials(profileName, profiles, options, visitedProfiles);
      }
      if (isStaticCredsProfile(data)) {
        return resolveStaticCredentials(data, options);
      }
      if (isWebIdentityProfile(data)) {
        return resolveWebIdentityCredentials(data, options);
      }
      if (isProcessProfile(data)) {
        return resolveProcessCredentials2(options, profileName);
      }
      if (isSsoProfile2(data)) {
        return await resolveSsoCredentials(profileName, data, options);
      }
      throw new CredentialsProviderError(`Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, { logger: options.logger });
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/fromIni.js
var fromIni;
var init_fromIni = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/fromIni.js"() {
    "use strict";
    init_dist_es30();
    init_resolveProfileData();
    fromIni = (_init2 = {}) => async ({ callerClientConfig } = {}) => {
      const init2 = {
        ..._init2,
        parentClientConfig: {
          ...callerClientConfig,
          ..._init2.parentClientConfig
        }
      };
      init2.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");
      const profiles = await parseKnownFiles(init2);
      return resolveProfileData(getProfileName({
        profile: _init2.profile ?? callerClientConfig?.profile
      }), profiles, init2);
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/index.js
var dist_es_exports7 = {};
__export(dist_es_exports7, {
  fromIni: () => fromIni
});
var init_dist_es51 = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/index.js"() {
    "use strict";
    init_fromIni();
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.817.0/node_modules/@aws-sdk/credential-provider-node/dist-es/defaultProvider.js
var multipleCredentialSourceWarningEmitted, defaultProvider, credentialsWillNeedRefresh, credentialsTreatedAsExpired;
var init_defaultProvider = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.817.0/node_modules/@aws-sdk/credential-provider-node/dist-es/defaultProvider.js"() {
    "use strict";
    init_dist_es38();
    init_dist_es21();
    init_dist_es30();
    init_remoteProvider();
    multipleCredentialSourceWarningEmitted = false;
    defaultProvider = (init2 = {}) => memoize(chain(async () => {
      const profile = init2.profile ?? process.env[ENV_PROFILE];
      if (profile) {
        const envStaticCredentialsAreSet = process.env[ENV_KEY] && process.env[ENV_SECRET];
        if (envStaticCredentialsAreSet) {
          if (!multipleCredentialSourceWarningEmitted) {
            const warnFn = init2.logger?.warn && init2.logger?.constructor?.name !== "NoOpLogger" ? init2.logger.warn : console.warn;
            warnFn(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING:
    Multiple credential sources detected: 
    Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set.
    This SDK will proceed with the AWS_PROFILE value.
    
    However, a future version may change this behavior to prefer the ENV static credentials.
    Please ensure that your environment only sets either the AWS_PROFILE or the
    AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair.
`);
            multipleCredentialSourceWarningEmitted = true;
          }
        }
        throw new CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", {
          logger: init2.logger,
          tryNextLink: true
        });
      }
      init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv");
      return fromEnv2(init2)();
    }, async () => {
      init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO");
      const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init2;
      if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {
        throw new CredentialsProviderError("Skipping SSO provider in default chain (inputs do not include SSO fields).", { logger: init2.logger });
      }
      const { fromSSO: fromSSO2 } = await Promise.resolve().then(() => (init_dist_es48(), dist_es_exports4));
      return fromSSO2(init2)();
    }, async () => {
      init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni");
      const { fromIni: fromIni2 } = await Promise.resolve().then(() => (init_dist_es51(), dist_es_exports7));
      return fromIni2(init2)();
    }, async () => {
      init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess");
      const { fromProcess: fromProcess2 } = await Promise.resolve().then(() => (init_dist_es49(), dist_es_exports5));
      return fromProcess2(init2)();
    }, async () => {
      init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile");
      const { fromTokenFile: fromTokenFile2 } = await Promise.resolve().then(() => (init_dist_es50(), dist_es_exports6));
      return fromTokenFile2(init2)();
    }, async () => {
      init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider");
      return (await remoteProvider(init2))();
    }, async () => {
      throw new CredentialsProviderError("Could not load credentials from any providers", {
        tryNextLink: false,
        logger: init2.logger
      });
    }), credentialsTreatedAsExpired, credentialsWillNeedRefresh);
    credentialsWillNeedRefresh = (credentials2) => credentials2?.expiration !== void 0;
    credentialsTreatedAsExpired = (credentials2) => credentials2?.expiration !== void 0 && credentials2.expiration.getTime() - Date.now() < 3e5;
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.817.0/node_modules/@aws-sdk/credential-provider-node/dist-es/index.js
var init_dist_es52 = __esm({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.817.0/node_modules/@aws-sdk/credential-provider-node/dist-es/index.js"() {
    "use strict";
    init_defaultProvider();
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/endpoint/ruleset.js
var s5, t5, u4, v5, a4, b4, c4, d4, e5, f6, g4, h5, i5, j4, k4, l4, m5, n4, o4, p4, q4, r5, _data4, ruleSet4;
var init_ruleset4 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/endpoint/ruleset.js"() {
    "use strict";
    s5 = "required";
    t5 = "fn";
    u4 = "argv";
    v5 = "ref";
    a4 = true;
    b4 = "isSet";
    c4 = "booleanEquals";
    d4 = "error";
    e5 = "endpoint";
    f6 = "tree";
    g4 = "PartitionResult";
    h5 = { [s5]: false, "type": "String" };
    i5 = { [s5]: true, "default": false, "type": "Boolean" };
    j4 = { [v5]: "Endpoint" };
    k4 = { [t5]: c4, [u4]: [{ [v5]: "UseFIPS" }, true] };
    l4 = { [t5]: c4, [u4]: [{ [v5]: "UseDualStack" }, true] };
    m5 = {};
    n4 = { [t5]: "getAttr", [u4]: [{ [v5]: g4 }, "supportsFIPS"] };
    o4 = { [t5]: c4, [u4]: [true, { [t5]: "getAttr", [u4]: [{ [v5]: g4 }, "supportsDualStack"] }] };
    p4 = [k4];
    q4 = [l4];
    r5 = [{ [v5]: "Region" }];
    _data4 = { version: "1.0", parameters: { Region: h5, UseDualStack: i5, UseFIPS: i5, Endpoint: h5 }, rules: [{ conditions: [{ [t5]: b4, [u4]: [j4] }], rules: [{ conditions: p4, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d4 }, { conditions: q4, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d4 }, { endpoint: { url: j4, properties: m5, headers: m5 }, type: e5 }], type: f6 }, { conditions: [{ [t5]: b4, [u4]: r5 }], rules: [{ conditions: [{ [t5]: "aws.partition", [u4]: r5, assign: g4 }], rules: [{ conditions: [k4, l4], rules: [{ conditions: [{ [t5]: c4, [u4]: [a4, n4] }, o4], rules: [{ endpoint: { url: "https://rds-data-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m5, headers: m5 }, type: e5 }], type: f6 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d4 }], type: f6 }, { conditions: p4, rules: [{ conditions: [{ [t5]: c4, [u4]: [n4, a4] }], rules: [{ endpoint: { url: "https://rds-data-fips.{Region}.{PartitionResult#dnsSuffix}", properties: m5, headers: m5 }, type: e5 }], type: f6 }, { error: "FIPS is enabled but this partition does not support FIPS", type: d4 }], type: f6 }, { conditions: q4, rules: [{ conditions: [o4], rules: [{ endpoint: { url: "https://rds-data.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m5, headers: m5 }, type: e5 }], type: f6 }, { error: "DualStack is enabled but this partition does not support DualStack", type: d4 }], type: f6 }, { endpoint: { url: "https://rds-data.{Region}.{PartitionResult#dnsSuffix}", properties: m5, headers: m5 }, type: e5 }], type: f6 }], type: f6 }, { error: "Invalid Configuration: Missing Region", type: d4 }] };
    ruleSet4 = _data4;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/endpoint/endpointResolver.js
var cache4, defaultEndpointResolver4;
var init_endpointResolver4 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/endpoint/endpointResolver.js"() {
    "use strict";
    init_dist_es20();
    init_dist_es19();
    init_ruleset4();
    cache4 = new EndpointCache({
      size: 50,
      params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
    });
    defaultEndpointResolver4 = (endpointParams, context = {}) => {
      return cache4.get(endpointParams, () => resolveEndpoint(ruleSet4, {
        endpointParams,
        logger: context.logger
      }));
    };
    customEndpointFunctions.aws = awsEndpointFunctions;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/runtimeConfig.shared.js
var getRuntimeConfig7;
var init_runtimeConfig_shared4 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/runtimeConfig.shared.js"() {
    "use strict";
    init_dist_es25();
    init_dist_es24();
    init_dist_es33();
    init_dist_es11();
    init_dist_es10();
    init_httpAuthSchemeProvider();
    init_endpointResolver4();
    getRuntimeConfig7 = (config) => {
      return {
        apiVersion: "2018-08-01",
        base64Decoder: config?.base64Decoder ?? fromBase64,
        base64Encoder: config?.base64Encoder ?? toBase64,
        disableHostPrefix: config?.disableHostPrefix ?? false,
        endpointProvider: config?.endpointProvider ?? defaultEndpointResolver4,
        extensions: config?.extensions ?? [],
        httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultRDSDataHttpAuthSchemeProvider,
        httpAuthSchemes: config?.httpAuthSchemes ?? [
          {
            schemeId: "aws.auth#sigv4",
            identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
            signer: new AwsSdkSigV4Signer()
          }
        ],
        logger: config?.logger ?? new NoOpLogger(),
        serviceId: config?.serviceId ?? "RDS Data",
        urlParser: config?.urlParser ?? parseUrl,
        utf8Decoder: config?.utf8Decoder ?? fromUtf8,
        utf8Encoder: config?.utf8Encoder ?? toUtf8
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/runtimeConfig.js
var getRuntimeConfig8;
var init_runtimeConfig4 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/runtimeConfig.js"() {
    "use strict";
    init_package();
    init_dist_es25();
    init_dist_es52();
    init_dist_es41();
    init_dist_es28();
    init_dist_es42();
    init_dist_es37();
    init_dist_es31();
    init_dist_es14();
    init_dist_es43();
    init_dist_es36();
    init_runtimeConfig_shared4();
    init_dist_es24();
    init_dist_es44();
    init_dist_es24();
    getRuntimeConfig8 = (config) => {
      emitWarningIfUnsupportedVersion2(process.version);
      const defaultsMode = resolveDefaultsModeConfig(config);
      const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);
      const clientSharedValues = getRuntimeConfig7(config);
      emitWarningIfUnsupportedVersion(process.version);
      const loaderConfig = {
        profile: config?.profile,
        logger: clientSharedValues.logger
      };
      return {
        ...clientSharedValues,
        ...config,
        runtime: "node",
        defaultsMode,
        authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
        bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,
        credentialDefaultProvider: config?.credentialDefaultProvider ?? defaultProvider,
        defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }),
        maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
        region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
        requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),
        retryMode: config?.retryMode ?? loadConfig({
          ...NODE_RETRY_MODE_CONFIG_OPTIONS,
          default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE
        }, config),
        sha256: config?.sha256 ?? Hash.bind(null, "sha256"),
        streamCollector: config?.streamCollector ?? streamCollector,
        useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
        useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
        userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/auth/httpAuthExtensionConfiguration.js
var getHttpAuthExtensionConfiguration4, resolveHttpAuthRuntimeConfig4;
var init_httpAuthExtensionConfiguration4 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/auth/httpAuthExtensionConfiguration.js"() {
    "use strict";
    getHttpAuthExtensionConfiguration4 = (runtimeConfig) => {
      const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
      let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
      let _credentials = runtimeConfig.credentials;
      return {
        setHttpAuthScheme(httpAuthScheme) {
          const index6 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
          if (index6 === -1) {
            _httpAuthSchemes.push(httpAuthScheme);
          } else {
            _httpAuthSchemes.splice(index6, 1, httpAuthScheme);
          }
        },
        httpAuthSchemes() {
          return _httpAuthSchemes;
        },
        setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
          _httpAuthSchemeProvider = httpAuthSchemeProvider;
        },
        httpAuthSchemeProvider() {
          return _httpAuthSchemeProvider;
        },
        setCredentials(credentials2) {
          _credentials = credentials2;
        },
        credentials() {
          return _credentials;
        }
      };
    };
    resolveHttpAuthRuntimeConfig4 = (config) => {
      return {
        httpAuthSchemes: config.httpAuthSchemes(),
        httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
        credentials: config.credentials()
      };
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/runtimeExtensions.js
var resolveRuntimeExtensions4;
var init_runtimeExtensions4 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/runtimeExtensions.js"() {
    "use strict";
    init_dist_es45();
    init_dist_es2();
    init_dist_es24();
    init_httpAuthExtensionConfiguration4();
    resolveRuntimeExtensions4 = (runtimeConfig, extensions) => {
      const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration4(runtimeConfig));
      extensions.forEach((extension) => extension.configure(extensionConfiguration));
      return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig4(extensionConfiguration));
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/RDSDataClient.js
var RDSDataClient;
var init_RDSDataClient = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/RDSDataClient.js"() {
    "use strict";
    init_dist_es3();
    init_dist_es4();
    init_dist_es5();
    init_dist_es26();
    init_dist_es28();
    init_dist_es18();
    init_dist_es29();
    init_dist_es34();
    init_dist_es37();
    init_dist_es24();
    init_httpAuthSchemeProvider();
    init_EndpointParameters();
    init_runtimeConfig4();
    init_runtimeExtensions4();
    RDSDataClient = class extends Client {
      constructor(...[configuration]) {
        const _config_0 = getRuntimeConfig8(configuration || {});
        super(_config_0);
        __publicField(this, "config");
        this.initConfig = _config_0;
        const _config_1 = resolveClientEndpointParameters(_config_0);
        const _config_2 = resolveUserAgentConfig(_config_1);
        const _config_3 = resolveRetryConfig(_config_2);
        const _config_4 = resolveRegionConfig(_config_3);
        const _config_5 = resolveHostHeaderConfig(_config_4);
        const _config_6 = resolveEndpointConfig(_config_5);
        const _config_7 = resolveHttpAuthSchemeConfig(_config_6);
        const _config_8 = resolveRuntimeExtensions4(_config_7, configuration?.extensions || []);
        this.config = _config_8;
        this.middlewareStack.use(getUserAgentPlugin(this.config));
        this.middlewareStack.use(getRetryPlugin(this.config));
        this.middlewareStack.use(getContentLengthPlugin(this.config));
        this.middlewareStack.use(getHostHeaderPlugin(this.config));
        this.middlewareStack.use(getLoggerPlugin(this.config));
        this.middlewareStack.use(getRecursionDetectionPlugin(this.config));
        this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
          httpAuthSchemeParametersProvider: defaultRDSDataHttpAuthSchemeParametersProvider,
          identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({
            "aws.auth#sigv4": config.credentials
          })
        }));
        this.middlewareStack.use(getHttpSigningPlugin(this.config));
      }
      destroy() {
        super.destroy();
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/models/RDSDataServiceException.js
var RDSDataServiceException;
var init_RDSDataServiceException = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/models/RDSDataServiceException.js"() {
    "use strict";
    init_dist_es24();
    RDSDataServiceException = class _RDSDataServiceException extends ServiceException {
      constructor(options) {
        super(options);
        Object.setPrototypeOf(this, _RDSDataServiceException.prototype);
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/models/models_0.js
var AccessDeniedException2, BadRequestException, TypeHint, DatabaseErrorException, DatabaseNotFoundException, DatabaseResumingException, DatabaseUnavailableException, ForbiddenException, HttpEndpointNotEnabledException, InternalServerErrorException, InvalidResourceStateException, InvalidSecretException, SecretsErrorException, ServiceUnavailableError, StatementTimeoutException, TransactionNotFoundException, NotFoundException, DecimalReturnType, RecordsFormatType, LongReturnType, UnsupportedResultException, ArrayValue, Field, Value;
var init_models_04 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/models/models_0.js"() {
    "use strict";
    init_RDSDataServiceException();
    AccessDeniedException2 = class _AccessDeniedException extends RDSDataServiceException {
      constructor(opts) {
        super({
          name: "AccessDeniedException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "AccessDeniedException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _AccessDeniedException.prototype);
      }
    };
    BadRequestException = class _BadRequestException extends RDSDataServiceException {
      constructor(opts) {
        super({
          name: "BadRequestException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "BadRequestException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _BadRequestException.prototype);
      }
    };
    TypeHint = {
      DATE: "DATE",
      DECIMAL: "DECIMAL",
      JSON: "JSON",
      TIME: "TIME",
      TIMESTAMP: "TIMESTAMP",
      UUID: "UUID"
    };
    DatabaseErrorException = class _DatabaseErrorException extends RDSDataServiceException {
      constructor(opts) {
        super({
          name: "DatabaseErrorException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "DatabaseErrorException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _DatabaseErrorException.prototype);
      }
    };
    DatabaseNotFoundException = class _DatabaseNotFoundException extends RDSDataServiceException {
      constructor(opts) {
        super({
          name: "DatabaseNotFoundException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "DatabaseNotFoundException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _DatabaseNotFoundException.prototype);
      }
    };
    DatabaseResumingException = class _DatabaseResumingException extends RDSDataServiceException {
      constructor(opts) {
        super({
          name: "DatabaseResumingException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "DatabaseResumingException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _DatabaseResumingException.prototype);
      }
    };
    DatabaseUnavailableException = class _DatabaseUnavailableException extends RDSDataServiceException {
      constructor(opts) {
        super({
          name: "DatabaseUnavailableException",
          $fault: "server",
          ...opts
        });
        __publicField(this, "name", "DatabaseUnavailableException");
        __publicField(this, "$fault", "server");
        Object.setPrototypeOf(this, _DatabaseUnavailableException.prototype);
      }
    };
    ForbiddenException = class _ForbiddenException extends RDSDataServiceException {
      constructor(opts) {
        super({
          name: "ForbiddenException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "ForbiddenException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _ForbiddenException.prototype);
      }
    };
    HttpEndpointNotEnabledException = class _HttpEndpointNotEnabledException extends RDSDataServiceException {
      constructor(opts) {
        super({
          name: "HttpEndpointNotEnabledException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "HttpEndpointNotEnabledException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _HttpEndpointNotEnabledException.prototype);
      }
    };
    InternalServerErrorException = class _InternalServerErrorException extends RDSDataServiceException {
      constructor(opts) {
        super({
          name: "InternalServerErrorException",
          $fault: "server",
          ...opts
        });
        __publicField(this, "name", "InternalServerErrorException");
        __publicField(this, "$fault", "server");
        Object.setPrototypeOf(this, _InternalServerErrorException.prototype);
      }
    };
    InvalidResourceStateException = class _InvalidResourceStateException extends RDSDataServiceException {
      constructor(opts) {
        super({
          name: "InvalidResourceStateException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "InvalidResourceStateException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _InvalidResourceStateException.prototype);
      }
    };
    InvalidSecretException = class _InvalidSecretException extends RDSDataServiceException {
      constructor(opts) {
        super({
          name: "InvalidSecretException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "InvalidSecretException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _InvalidSecretException.prototype);
      }
    };
    SecretsErrorException = class _SecretsErrorException extends RDSDataServiceException {
      constructor(opts) {
        super({
          name: "SecretsErrorException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "SecretsErrorException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _SecretsErrorException.prototype);
      }
    };
    ServiceUnavailableError = class _ServiceUnavailableError extends RDSDataServiceException {
      constructor(opts) {
        super({
          name: "ServiceUnavailableError",
          $fault: "server",
          ...opts
        });
        __publicField(this, "name", "ServiceUnavailableError");
        __publicField(this, "$fault", "server");
        Object.setPrototypeOf(this, _ServiceUnavailableError.prototype);
      }
    };
    StatementTimeoutException = class _StatementTimeoutException extends RDSDataServiceException {
      constructor(opts) {
        super({
          name: "StatementTimeoutException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "StatementTimeoutException");
        __publicField(this, "$fault", "client");
        __publicField(this, "dbConnectionId");
        Object.setPrototypeOf(this, _StatementTimeoutException.prototype);
        this.dbConnectionId = opts.dbConnectionId;
      }
    };
    TransactionNotFoundException = class _TransactionNotFoundException extends RDSDataServiceException {
      constructor(opts) {
        super({
          name: "TransactionNotFoundException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "TransactionNotFoundException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _TransactionNotFoundException.prototype);
      }
    };
    NotFoundException = class _NotFoundException extends RDSDataServiceException {
      constructor(opts) {
        super({
          name: "NotFoundException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "NotFoundException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _NotFoundException.prototype);
      }
    };
    DecimalReturnType = {
      DOUBLE_OR_LONG: "DOUBLE_OR_LONG",
      STRING: "STRING"
    };
    RecordsFormatType = {
      JSON: "JSON",
      NONE: "NONE"
    };
    LongReturnType = {
      LONG: "LONG",
      STRING: "STRING"
    };
    UnsupportedResultException = class _UnsupportedResultException extends RDSDataServiceException {
      constructor(opts) {
        super({
          name: "UnsupportedResultException",
          $fault: "client",
          ...opts
        });
        __publicField(this, "name", "UnsupportedResultException");
        __publicField(this, "$fault", "client");
        Object.setPrototypeOf(this, _UnsupportedResultException.prototype);
      }
    };
    (function(ArrayValue2) {
      ArrayValue2.visit = (value, visitor) => {
        if (value.booleanValues !== void 0)
          return visitor.booleanValues(value.booleanValues);
        if (value.longValues !== void 0)
          return visitor.longValues(value.longValues);
        if (value.doubleValues !== void 0)
          return visitor.doubleValues(value.doubleValues);
        if (value.stringValues !== void 0)
          return visitor.stringValues(value.stringValues);
        if (value.arrayValues !== void 0)
          return visitor.arrayValues(value.arrayValues);
        return visitor._(value.$unknown[0], value.$unknown[1]);
      };
    })(ArrayValue || (ArrayValue = {}));
    (function(Field2) {
      Field2.visit = (value, visitor) => {
        if (value.isNull !== void 0)
          return visitor.isNull(value.isNull);
        if (value.booleanValue !== void 0)
          return visitor.booleanValue(value.booleanValue);
        if (value.longValue !== void 0)
          return visitor.longValue(value.longValue);
        if (value.doubleValue !== void 0)
          return visitor.doubleValue(value.doubleValue);
        if (value.stringValue !== void 0)
          return visitor.stringValue(value.stringValue);
        if (value.blobValue !== void 0)
          return visitor.blobValue(value.blobValue);
        if (value.arrayValue !== void 0)
          return visitor.arrayValue(value.arrayValue);
        return visitor._(value.$unknown[0], value.$unknown[1]);
      };
    })(Field || (Field = {}));
    (function(Value2) {
      Value2.visit = (value, visitor) => {
        if (value.isNull !== void 0)
          return visitor.isNull(value.isNull);
        if (value.bitValue !== void 0)
          return visitor.bitValue(value.bitValue);
        if (value.bigIntValue !== void 0)
          return visitor.bigIntValue(value.bigIntValue);
        if (value.intValue !== void 0)
          return visitor.intValue(value.intValue);
        if (value.doubleValue !== void 0)
          return visitor.doubleValue(value.doubleValue);
        if (value.realValue !== void 0)
          return visitor.realValue(value.realValue);
        if (value.stringValue !== void 0)
          return visitor.stringValue(value.stringValue);
        if (value.blobValue !== void 0)
          return visitor.blobValue(value.blobValue);
        if (value.arrayValues !== void 0)
          return visitor.arrayValues(value.arrayValues);
        if (value.structValue !== void 0)
          return visitor.structValue(value.structValue);
        return visitor._(value.$unknown[0], value.$unknown[1]);
      };
    })(Value || (Value = {}));
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/protocols/Aws_restJson1.js
var se_BatchExecuteStatementCommand, se_BeginTransactionCommand, se_CommitTransactionCommand, se_ExecuteSqlCommand, se_ExecuteStatementCommand, se_RollbackTransactionCommand, de_BatchExecuteStatementCommand, de_BeginTransactionCommand, de_CommitTransactionCommand, de_ExecuteSqlCommand, de_ExecuteStatementCommand, de_RollbackTransactionCommand, de_CommandError4, throwDefaultError5, de_AccessDeniedExceptionRes2, de_BadRequestExceptionRes, de_DatabaseErrorExceptionRes, de_DatabaseNotFoundExceptionRes, de_DatabaseResumingExceptionRes, de_DatabaseUnavailableExceptionRes, de_ForbiddenExceptionRes, de_HttpEndpointNotEnabledExceptionRes, de_InternalServerErrorExceptionRes, de_InvalidResourceStateExceptionRes, de_InvalidSecretExceptionRes, de_NotFoundExceptionRes, de_SecretsErrorExceptionRes, de_ServiceUnavailableErrorRes, de_StatementTimeoutExceptionRes, de_TransactionNotFoundExceptionRes, de_UnsupportedResultExceptionRes, se_ArrayOfArray, se_ArrayValue, se_DoubleArray, se_Field, se_SqlParameter, se_SqlParameterSets, se_SqlParametersList, de_ArrayOfArray, de_ArrayValue, de_ArrayValueList, de_DoubleArray, de_Field, de_FieldList, de__Record, de_Records, de_ResultFrame, de_Row, de_SqlRecords, de_SqlStatementResult, de_SqlStatementResults, de_StructValue, de_UpdateResult, de_UpdateResults, de_Value, deserializeMetadata5;
var init_Aws_restJson13 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/protocols/Aws_restJson1.js"() {
    "use strict";
    init_dist_es25();
    init_dist_es18();
    init_dist_es24();
    init_models_04();
    init_RDSDataServiceException();
    se_BatchExecuteStatementCommand = async (input, context) => {
      const b5 = requestBuilder(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b5.bp("/BatchExecute");
      let body;
      body = JSON.stringify(take(input, {
        database: [],
        parameterSets: (_3) => se_SqlParameterSets(_3, context),
        resourceArn: [],
        schema: [],
        secretArn: [],
        sql: [],
        transactionId: []
      }));
      b5.m("POST").h(headers).b(body);
      return b5.build();
    };
    se_BeginTransactionCommand = async (input, context) => {
      const b5 = requestBuilder(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b5.bp("/BeginTransaction");
      let body;
      body = JSON.stringify(take(input, {
        database: [],
        resourceArn: [],
        schema: [],
        secretArn: []
      }));
      b5.m("POST").h(headers).b(body);
      return b5.build();
    };
    se_CommitTransactionCommand = async (input, context) => {
      const b5 = requestBuilder(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b5.bp("/CommitTransaction");
      let body;
      body = JSON.stringify(take(input, {
        resourceArn: [],
        secretArn: [],
        transactionId: []
      }));
      b5.m("POST").h(headers).b(body);
      return b5.build();
    };
    se_ExecuteSqlCommand = async (input, context) => {
      const b5 = requestBuilder(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b5.bp("/ExecuteSql");
      let body;
      body = JSON.stringify(take(input, {
        awsSecretStoreArn: [],
        database: [],
        dbClusterOrInstanceArn: [],
        schema: [],
        sqlStatements: []
      }));
      b5.m("POST").h(headers).b(body);
      return b5.build();
    };
    se_ExecuteStatementCommand = async (input, context) => {
      const b5 = requestBuilder(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b5.bp("/Execute");
      let body;
      body = JSON.stringify(take(input, {
        continueAfterTimeout: [],
        database: [],
        formatRecordsAs: [],
        includeResultMetadata: [],
        parameters: (_3) => se_SqlParametersList(_3, context),
        resourceArn: [],
        resultSetOptions: (_3) => _json(_3),
        schema: [],
        secretArn: [],
        sql: [],
        transactionId: []
      }));
      b5.m("POST").h(headers).b(body);
      return b5.build();
    };
    se_RollbackTransactionCommand = async (input, context) => {
      const b5 = requestBuilder(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b5.bp("/RollbackTransaction");
      let body;
      body = JSON.stringify(take(input, {
        resourceArn: [],
        secretArn: [],
        transactionId: []
      }));
      b5.m("POST").h(headers).b(body);
      return b5.build();
    };
    de_BatchExecuteStatementCommand = async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError4(output, context);
      }
      const contents = map({
        $metadata: deserializeMetadata5(output)
      });
      const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
      const doc = take(data, {
        updateResults: (_3) => de_UpdateResults(_3, context)
      });
      Object.assign(contents, doc);
      return contents;
    };
    de_BeginTransactionCommand = async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError4(output, context);
      }
      const contents = map({
        $metadata: deserializeMetadata5(output)
      });
      const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
      const doc = take(data, {
        transactionId: expectString
      });
      Object.assign(contents, doc);
      return contents;
    };
    de_CommitTransactionCommand = async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError4(output, context);
      }
      const contents = map({
        $metadata: deserializeMetadata5(output)
      });
      const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
      const doc = take(data, {
        transactionStatus: expectString
      });
      Object.assign(contents, doc);
      return contents;
    };
    de_ExecuteSqlCommand = async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError4(output, context);
      }
      const contents = map({
        $metadata: deserializeMetadata5(output)
      });
      const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
      const doc = take(data, {
        sqlStatementResults: (_3) => de_SqlStatementResults(_3, context)
      });
      Object.assign(contents, doc);
      return contents;
    };
    de_ExecuteStatementCommand = async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError4(output, context);
      }
      const contents = map({
        $metadata: deserializeMetadata5(output)
      });
      const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
      const doc = take(data, {
        columnMetadata: _json,
        formattedRecords: expectString,
        generatedFields: (_3) => de_FieldList(_3, context),
        numberOfRecordsUpdated: expectLong,
        records: (_3) => de_SqlRecords(_3, context)
      });
      Object.assign(contents, doc);
      return contents;
    };
    de_RollbackTransactionCommand = async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError4(output, context);
      }
      const contents = map({
        $metadata: deserializeMetadata5(output)
      });
      const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
      const doc = take(data, {
        transactionStatus: expectString
      });
      Object.assign(contents, doc);
      return contents;
    };
    de_CommandError4 = async (output, context) => {
      const parsedOutput = {
        ...output,
        body: await parseJsonErrorBody(output.body, context)
      };
      const errorCode = loadRestJsonErrorCode(output, parsedOutput.body);
      switch (errorCode) {
        case "AccessDeniedException":
        case "com.amazonaws.rdsdata#AccessDeniedException":
          throw await de_AccessDeniedExceptionRes2(parsedOutput, context);
        case "BadRequestException":
        case "com.amazonaws.rdsdata#BadRequestException":
          throw await de_BadRequestExceptionRes(parsedOutput, context);
        case "DatabaseErrorException":
        case "com.amazonaws.rdsdata#DatabaseErrorException":
          throw await de_DatabaseErrorExceptionRes(parsedOutput, context);
        case "DatabaseNotFoundException":
        case "com.amazonaws.rdsdata#DatabaseNotFoundException":
          throw await de_DatabaseNotFoundExceptionRes(parsedOutput, context);
        case "DatabaseResumingException":
        case "com.amazonaws.rdsdata#DatabaseResumingException":
          throw await de_DatabaseResumingExceptionRes(parsedOutput, context);
        case "DatabaseUnavailableException":
        case "com.amazonaws.rdsdata#DatabaseUnavailableException":
          throw await de_DatabaseUnavailableExceptionRes(parsedOutput, context);
        case "ForbiddenException":
        case "com.amazonaws.rdsdata#ForbiddenException":
          throw await de_ForbiddenExceptionRes(parsedOutput, context);
        case "HttpEndpointNotEnabledException":
        case "com.amazonaws.rdsdata#HttpEndpointNotEnabledException":
          throw await de_HttpEndpointNotEnabledExceptionRes(parsedOutput, context);
        case "InternalServerErrorException":
        case "com.amazonaws.rdsdata#InternalServerErrorException":
          throw await de_InternalServerErrorExceptionRes(parsedOutput, context);
        case "InvalidResourceStateException":
        case "com.amazonaws.rdsdata#InvalidResourceStateException":
          throw await de_InvalidResourceStateExceptionRes(parsedOutput, context);
        case "InvalidSecretException":
        case "com.amazonaws.rdsdata#InvalidSecretException":
          throw await de_InvalidSecretExceptionRes(parsedOutput, context);
        case "SecretsErrorException":
        case "com.amazonaws.rdsdata#SecretsErrorException":
          throw await de_SecretsErrorExceptionRes(parsedOutput, context);
        case "ServiceUnavailableError":
        case "com.amazonaws.rdsdata#ServiceUnavailableError":
          throw await de_ServiceUnavailableErrorRes(parsedOutput, context);
        case "StatementTimeoutException":
        case "com.amazonaws.rdsdata#StatementTimeoutException":
          throw await de_StatementTimeoutExceptionRes(parsedOutput, context);
        case "TransactionNotFoundException":
        case "com.amazonaws.rdsdata#TransactionNotFoundException":
          throw await de_TransactionNotFoundExceptionRes(parsedOutput, context);
        case "NotFoundException":
        case "com.amazonaws.rdsdata#NotFoundException":
          throw await de_NotFoundExceptionRes(parsedOutput, context);
        case "UnsupportedResultException":
        case "com.amazonaws.rdsdata#UnsupportedResultException":
          throw await de_UnsupportedResultExceptionRes(parsedOutput, context);
        default:
          const parsedBody = parsedOutput.body;
          return throwDefaultError5({
            output,
            parsedBody,
            errorCode
          });
      }
    };
    throwDefaultError5 = withBaseException(RDSDataServiceException);
    de_AccessDeniedExceptionRes2 = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        message: expectString
      });
      Object.assign(contents, doc);
      const exception = new AccessDeniedException2({
        $metadata: deserializeMetadata5(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_BadRequestExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        message: expectString
      });
      Object.assign(contents, doc);
      const exception = new BadRequestException({
        $metadata: deserializeMetadata5(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_DatabaseErrorExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        message: expectString
      });
      Object.assign(contents, doc);
      const exception = new DatabaseErrorException({
        $metadata: deserializeMetadata5(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_DatabaseNotFoundExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        message: expectString
      });
      Object.assign(contents, doc);
      const exception = new DatabaseNotFoundException({
        $metadata: deserializeMetadata5(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_DatabaseResumingExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        message: expectString
      });
      Object.assign(contents, doc);
      const exception = new DatabaseResumingException({
        $metadata: deserializeMetadata5(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_DatabaseUnavailableExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {});
      Object.assign(contents, doc);
      const exception = new DatabaseUnavailableException({
        $metadata: deserializeMetadata5(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_ForbiddenExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        message: expectString
      });
      Object.assign(contents, doc);
      const exception = new ForbiddenException({
        $metadata: deserializeMetadata5(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_HttpEndpointNotEnabledExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        message: expectString
      });
      Object.assign(contents, doc);
      const exception = new HttpEndpointNotEnabledException({
        $metadata: deserializeMetadata5(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_InternalServerErrorExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {});
      Object.assign(contents, doc);
      const exception = new InternalServerErrorException({
        $metadata: deserializeMetadata5(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_InvalidResourceStateExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        message: expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidResourceStateException({
        $metadata: deserializeMetadata5(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_InvalidSecretExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        message: expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidSecretException({
        $metadata: deserializeMetadata5(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_NotFoundExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        message: expectString
      });
      Object.assign(contents, doc);
      const exception = new NotFoundException({
        $metadata: deserializeMetadata5(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_SecretsErrorExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        message: expectString
      });
      Object.assign(contents, doc);
      const exception = new SecretsErrorException({
        $metadata: deserializeMetadata5(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_ServiceUnavailableErrorRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {});
      Object.assign(contents, doc);
      const exception = new ServiceUnavailableError({
        $metadata: deserializeMetadata5(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_StatementTimeoutExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        dbConnectionId: expectLong,
        message: expectString
      });
      Object.assign(contents, doc);
      const exception = new StatementTimeoutException({
        $metadata: deserializeMetadata5(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_TransactionNotFoundExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        message: expectString
      });
      Object.assign(contents, doc);
      const exception = new TransactionNotFoundException({
        $metadata: deserializeMetadata5(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    de_UnsupportedResultExceptionRes = async (parsedOutput, context) => {
      const contents = map({});
      const data = parsedOutput.body;
      const doc = take(data, {
        message: expectString
      });
      Object.assign(contents, doc);
      const exception = new UnsupportedResultException({
        $metadata: deserializeMetadata5(parsedOutput),
        ...contents
      });
      return decorateServiceException(exception, parsedOutput.body);
    };
    se_ArrayOfArray = (input, context) => {
      return input.filter((e6) => e6 != null).map((entry) => {
        return se_ArrayValue(entry, context);
      });
    };
    se_ArrayValue = (input, context) => {
      return ArrayValue.visit(input, {
        arrayValues: (value) => ({ arrayValues: se_ArrayOfArray(value, context) }),
        booleanValues: (value) => ({ booleanValues: _json(value) }),
        doubleValues: (value) => ({ doubleValues: se_DoubleArray(value, context) }),
        longValues: (value) => ({ longValues: _json(value) }),
        stringValues: (value) => ({ stringValues: _json(value) }),
        _: (name, value) => ({ [name]: value })
      });
    };
    se_DoubleArray = (input, context) => {
      return input.filter((e6) => e6 != null).map((entry) => {
        return serializeFloat(entry);
      });
    };
    se_Field = (input, context) => {
      return Field.visit(input, {
        arrayValue: (value) => ({ arrayValue: se_ArrayValue(value, context) }),
        blobValue: (value) => ({ blobValue: context.base64Encoder(value) }),
        booleanValue: (value) => ({ booleanValue: value }),
        doubleValue: (value) => ({ doubleValue: serializeFloat(value) }),
        isNull: (value) => ({ isNull: value }),
        longValue: (value) => ({ longValue: value }),
        stringValue: (value) => ({ stringValue: value }),
        _: (name, value) => ({ [name]: value })
      });
    };
    se_SqlParameter = (input, context) => {
      return take(input, {
        name: [],
        typeHint: [],
        value: (_3) => se_Field(_3, context)
      });
    };
    se_SqlParameterSets = (input, context) => {
      return input.filter((e6) => e6 != null).map((entry) => {
        return se_SqlParametersList(entry, context);
      });
    };
    se_SqlParametersList = (input, context) => {
      return input.filter((e6) => e6 != null).map((entry) => {
        return se_SqlParameter(entry, context);
      });
    };
    de_ArrayOfArray = (output, context) => {
      const retVal = (output || []).filter((e6) => e6 != null).map((entry) => {
        return de_ArrayValue(awsExpectUnion(entry), context);
      });
      return retVal;
    };
    de_ArrayValue = (output, context) => {
      if (output.arrayValues != null) {
        return {
          arrayValues: de_ArrayOfArray(output.arrayValues, context)
        };
      }
      if (output.booleanValues != null) {
        return {
          booleanValues: _json(output.booleanValues)
        };
      }
      if (output.doubleValues != null) {
        return {
          doubleValues: de_DoubleArray(output.doubleValues, context)
        };
      }
      if (output.longValues != null) {
        return {
          longValues: _json(output.longValues)
        };
      }
      if (output.stringValues != null) {
        return {
          stringValues: _json(output.stringValues)
        };
      }
      return { $unknown: Object.entries(output)[0] };
    };
    de_ArrayValueList = (output, context) => {
      const retVal = (output || []).filter((e6) => e6 != null).map((entry) => {
        return de_Value(awsExpectUnion(entry), context);
      });
      return retVal;
    };
    de_DoubleArray = (output, context) => {
      const retVal = (output || []).filter((e6) => e6 != null).map((entry) => {
        return limitedParseDouble(entry);
      });
      return retVal;
    };
    de_Field = (output, context) => {
      if (output.arrayValue != null) {
        return {
          arrayValue: de_ArrayValue(awsExpectUnion(output.arrayValue), context)
        };
      }
      if (output.blobValue != null) {
        return {
          blobValue: context.base64Decoder(output.blobValue)
        };
      }
      if (expectBoolean(output.booleanValue) !== void 0) {
        return { booleanValue: expectBoolean(output.booleanValue) };
      }
      if (limitedParseDouble(output.doubleValue) !== void 0) {
        return { doubleValue: limitedParseDouble(output.doubleValue) };
      }
      if (expectBoolean(output.isNull) !== void 0) {
        return { isNull: expectBoolean(output.isNull) };
      }
      if (expectLong(output.longValue) !== void 0) {
        return { longValue: expectLong(output.longValue) };
      }
      if (expectString(output.stringValue) !== void 0) {
        return { stringValue: expectString(output.stringValue) };
      }
      return { $unknown: Object.entries(output)[0] };
    };
    de_FieldList = (output, context) => {
      const retVal = (output || []).filter((e6) => e6 != null).map((entry) => {
        return de_Field(awsExpectUnion(entry), context);
      });
      return retVal;
    };
    de__Record = (output, context) => {
      return take(output, {
        values: (_3) => de_Row(_3, context)
      });
    };
    de_Records = (output, context) => {
      const retVal = (output || []).filter((e6) => e6 != null).map((entry) => {
        return de__Record(entry, context);
      });
      return retVal;
    };
    de_ResultFrame = (output, context) => {
      return take(output, {
        records: (_3) => de_Records(_3, context),
        resultSetMetadata: _json
      });
    };
    de_Row = (output, context) => {
      const retVal = (output || []).filter((e6) => e6 != null).map((entry) => {
        return de_Value(awsExpectUnion(entry), context);
      });
      return retVal;
    };
    de_SqlRecords = (output, context) => {
      const retVal = (output || []).filter((e6) => e6 != null).map((entry) => {
        return de_FieldList(entry, context);
      });
      return retVal;
    };
    de_SqlStatementResult = (output, context) => {
      return take(output, {
        numberOfRecordsUpdated: expectLong,
        resultFrame: (_3) => de_ResultFrame(_3, context)
      });
    };
    de_SqlStatementResults = (output, context) => {
      const retVal = (output || []).filter((e6) => e6 != null).map((entry) => {
        return de_SqlStatementResult(entry, context);
      });
      return retVal;
    };
    de_StructValue = (output, context) => {
      return take(output, {
        attributes: (_3) => de_ArrayValueList(_3, context)
      });
    };
    de_UpdateResult = (output, context) => {
      return take(output, {
        generatedFields: (_3) => de_FieldList(_3, context)
      });
    };
    de_UpdateResults = (output, context) => {
      const retVal = (output || []).filter((e6) => e6 != null).map((entry) => {
        return de_UpdateResult(entry, context);
      });
      return retVal;
    };
    de_Value = (output, context) => {
      if (output.arrayValues != null) {
        return {
          arrayValues: de_ArrayValueList(output.arrayValues, context)
        };
      }
      if (expectLong(output.bigIntValue) !== void 0) {
        return { bigIntValue: expectLong(output.bigIntValue) };
      }
      if (expectBoolean(output.bitValue) !== void 0) {
        return { bitValue: expectBoolean(output.bitValue) };
      }
      if (output.blobValue != null) {
        return {
          blobValue: context.base64Decoder(output.blobValue)
        };
      }
      if (limitedParseDouble(output.doubleValue) !== void 0) {
        return { doubleValue: limitedParseDouble(output.doubleValue) };
      }
      if (expectInt32(output.intValue) !== void 0) {
        return { intValue: expectInt32(output.intValue) };
      }
      if (expectBoolean(output.isNull) !== void 0) {
        return { isNull: expectBoolean(output.isNull) };
      }
      if (limitedParseFloat32(output.realValue) !== void 0) {
        return { realValue: limitedParseFloat32(output.realValue) };
      }
      if (expectString(output.stringValue) !== void 0) {
        return { stringValue: expectString(output.stringValue) };
      }
      if (output.structValue != null) {
        return {
          structValue: de_StructValue(output.structValue, context)
        };
      }
      return { $unknown: Object.entries(output)[0] };
    };
    deserializeMetadata5 = (output) => ({
      httpStatusCode: output.statusCode,
      requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
      extendedRequestId: output.headers["x-amz-id-2"],
      cfId: output.headers["x-amz-cf-id"]
    });
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/BatchExecuteStatementCommand.js
var BatchExecuteStatementCommand;
var init_BatchExecuteStatementCommand = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/BatchExecuteStatementCommand.js"() {
    "use strict";
    init_dist_es34();
    init_dist_es7();
    init_dist_es24();
    init_EndpointParameters();
    init_Aws_restJson13();
    BatchExecuteStatementCommand = class extends Command.classBuilder().ep(commonParams).m(function(Command2, cs, config, o5) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
      ];
    }).s("RdsDataService", "BatchExecuteStatement", {}).n("RDSDataClient", "BatchExecuteStatementCommand").f(void 0, void 0).ser(se_BatchExecuteStatementCommand).de(de_BatchExecuteStatementCommand).build() {
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/BeginTransactionCommand.js
var BeginTransactionCommand;
var init_BeginTransactionCommand = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/BeginTransactionCommand.js"() {
    "use strict";
    init_dist_es34();
    init_dist_es7();
    init_dist_es24();
    init_EndpointParameters();
    init_Aws_restJson13();
    BeginTransactionCommand = class extends Command.classBuilder().ep(commonParams).m(function(Command2, cs, config, o5) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
      ];
    }).s("RdsDataService", "BeginTransaction", {}).n("RDSDataClient", "BeginTransactionCommand").f(void 0, void 0).ser(se_BeginTransactionCommand).de(de_BeginTransactionCommand).build() {
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/CommitTransactionCommand.js
var CommitTransactionCommand;
var init_CommitTransactionCommand = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/CommitTransactionCommand.js"() {
    "use strict";
    init_dist_es34();
    init_dist_es7();
    init_dist_es24();
    init_EndpointParameters();
    init_Aws_restJson13();
    CommitTransactionCommand = class extends Command.classBuilder().ep(commonParams).m(function(Command2, cs, config, o5) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
      ];
    }).s("RdsDataService", "CommitTransaction", {}).n("RDSDataClient", "CommitTransactionCommand").f(void 0, void 0).ser(se_CommitTransactionCommand).de(de_CommitTransactionCommand).build() {
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/ExecuteSqlCommand.js
var ExecuteSqlCommand;
var init_ExecuteSqlCommand = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/ExecuteSqlCommand.js"() {
    "use strict";
    init_dist_es34();
    init_dist_es7();
    init_dist_es24();
    init_EndpointParameters();
    init_Aws_restJson13();
    ExecuteSqlCommand = class extends Command.classBuilder().ep(commonParams).m(function(Command2, cs, config, o5) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
      ];
    }).s("RdsDataService", "ExecuteSql", {}).n("RDSDataClient", "ExecuteSqlCommand").f(void 0, void 0).ser(se_ExecuteSqlCommand).de(de_ExecuteSqlCommand).build() {
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/ExecuteStatementCommand.js
var ExecuteStatementCommand;
var init_ExecuteStatementCommand = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/ExecuteStatementCommand.js"() {
    "use strict";
    init_dist_es34();
    init_dist_es7();
    init_dist_es24();
    init_EndpointParameters();
    init_Aws_restJson13();
    ExecuteStatementCommand = class extends Command.classBuilder().ep(commonParams).m(function(Command2, cs, config, o5) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
      ];
    }).s("RdsDataService", "ExecuteStatement", {}).n("RDSDataClient", "ExecuteStatementCommand").f(void 0, void 0).ser(se_ExecuteStatementCommand).de(de_ExecuteStatementCommand).build() {
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/RollbackTransactionCommand.js
var RollbackTransactionCommand;
var init_RollbackTransactionCommand = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/RollbackTransactionCommand.js"() {
    "use strict";
    init_dist_es34();
    init_dist_es7();
    init_dist_es24();
    init_EndpointParameters();
    init_Aws_restJson13();
    RollbackTransactionCommand = class extends Command.classBuilder().ep(commonParams).m(function(Command2, cs, config, o5) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
      ];
    }).s("RdsDataService", "RollbackTransaction", {}).n("RDSDataClient", "RollbackTransactionCommand").f(void 0, void 0).ser(se_RollbackTransactionCommand).de(de_RollbackTransactionCommand).build() {
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/RDSData.js
var commands4, RDSData;
var init_RDSData = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/RDSData.js"() {
    "use strict";
    init_dist_es24();
    init_BatchExecuteStatementCommand();
    init_BeginTransactionCommand();
    init_CommitTransactionCommand();
    init_ExecuteSqlCommand();
    init_ExecuteStatementCommand();
    init_RollbackTransactionCommand();
    init_RDSDataClient();
    commands4 = {
      BatchExecuteStatementCommand,
      BeginTransactionCommand,
      CommitTransactionCommand,
      ExecuteSqlCommand,
      ExecuteStatementCommand,
      RollbackTransactionCommand
    };
    RDSData = class extends RDSDataClient {
    };
    createAggregatedClient(commands4, RDSData);
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/index.js
var init_commands4 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/index.js"() {
    "use strict";
    init_BatchExecuteStatementCommand();
    init_BeginTransactionCommand();
    init_CommitTransactionCommand();
    init_ExecuteSqlCommand();
    init_ExecuteStatementCommand();
    init_RollbackTransactionCommand();
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/models/index.js
var init_models4 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/models/index.js"() {
    "use strict";
    init_models_04();
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/index.js
var dist_es_exports8 = {};
__export(dist_es_exports8, {
  $Command: () => Command,
  AccessDeniedException: () => AccessDeniedException2,
  ArrayValue: () => ArrayValue,
  BadRequestException: () => BadRequestException,
  BatchExecuteStatementCommand: () => BatchExecuteStatementCommand,
  BeginTransactionCommand: () => BeginTransactionCommand,
  CommitTransactionCommand: () => CommitTransactionCommand,
  DatabaseErrorException: () => DatabaseErrorException,
  DatabaseNotFoundException: () => DatabaseNotFoundException,
  DatabaseResumingException: () => DatabaseResumingException,
  DatabaseUnavailableException: () => DatabaseUnavailableException,
  DecimalReturnType: () => DecimalReturnType,
  ExecuteSqlCommand: () => ExecuteSqlCommand,
  ExecuteStatementCommand: () => ExecuteStatementCommand,
  Field: () => Field,
  ForbiddenException: () => ForbiddenException,
  HttpEndpointNotEnabledException: () => HttpEndpointNotEnabledException,
  InternalServerErrorException: () => InternalServerErrorException,
  InvalidResourceStateException: () => InvalidResourceStateException,
  InvalidSecretException: () => InvalidSecretException,
  LongReturnType: () => LongReturnType,
  NotFoundException: () => NotFoundException,
  RDSData: () => RDSData,
  RDSDataClient: () => RDSDataClient,
  RDSDataServiceException: () => RDSDataServiceException,
  RecordsFormatType: () => RecordsFormatType,
  RollbackTransactionCommand: () => RollbackTransactionCommand,
  SecretsErrorException: () => SecretsErrorException,
  ServiceUnavailableError: () => ServiceUnavailableError,
  StatementTimeoutException: () => StatementTimeoutException,
  TransactionNotFoundException: () => TransactionNotFoundException,
  TypeHint: () => TypeHint,
  UnsupportedResultException: () => UnsupportedResultException,
  Value: () => Value,
  __Client: () => Client
});
var init_dist_es53 = __esm({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/index.js"() {
    "use strict";
    init_RDSDataClient();
    init_RDSData();
    init_commands4();
    init_models4();
    init_RDSDataServiceException();
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/chars.js
var require_chars = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/chars.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.$v = exports2.$s = exports2.$r = exports2.$p = exports2.$o = exports2.$n = exports2.$m = exports2.$j = exports2.$b = exports2.$Z = exports2.$Y = exports2.$X = exports2.$V = exports2.$T = exports2.$S = exports2.$R = exports2.$Q = exports2.$P = exports2.$O = exports2.$M = exports2.$L = exports2.$K = exports2.$I = exports2.$H = exports2.$E = exports2.$D = exports2.$C = exports2.$A = exports2.$1 = exports2.$0 = void 0;
    exports2.ord = ord;
    exports2.chr = chr;
    exports2.$0 = ord("0");
    exports2.$1 = ord("1");
    exports2.$A = ord("A");
    exports2.$C = ord("C");
    exports2.$D = ord("D");
    exports2.$E = ord("E");
    exports2.$H = ord("H");
    exports2.$I = ord("I");
    exports2.$K = ord("K");
    exports2.$L = ord("L");
    exports2.$M = ord("M");
    exports2.$O = ord("O");
    exports2.$P = ord("P");
    exports2.$Q = ord("Q");
    exports2.$R = ord("R");
    exports2.$S = ord("S");
    exports2.$T = ord("T");
    exports2.$V = ord("V");
    exports2.$X = ord("X");
    exports2.$Y = ord("Y");
    exports2.$Z = ord("Z");
    exports2.$b = ord("b");
    exports2.$j = ord("j");
    exports2.$m = ord("m");
    exports2.$n = ord("n");
    exports2.$o = ord("o");
    exports2.$p = ord("p");
    exports2.$r = ord("r");
    exports2.$s = ord("s");
    exports2.$v = ord("v");
    function ord(str) {
      const ch = str.charCodeAt(0);
      if (ch <= 0 || ch >= 255) {
        throw new TypeError(`char "${ch}" is outside ASCII`);
      }
      return ch & 255;
    }
    function chr(ch) {
      if (ch <= 0 || ch >= 255) {
        throw new TypeError(`char "${ch}" is outside ASCII`);
      }
      return String.fromCharCode(ch);
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/buffer.js
var require_buffer = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/buffer.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      var desc = Object.getOwnPropertyDescriptor(m6, k5);
      if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m6[k5];
        } };
      }
      Object.defineProperty(o5, k22, desc);
    } : function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      o5[k22] = m6[k5];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v6) {
      Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
    } : function(o5, v6) {
      o5["default"] = v6;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ReadBuffer = exports2.ReadMessageBuffer = exports2.WriteMessageBuffer = exports2.WriteBuffer = exports2.BufferError = exports2.encodeB64 = exports2.decodeB64 = exports2.utf8Decoder = exports2.utf8Encoder = void 0;
    exports2.uuidToBuffer = uuidToBuffer;
    var chars = __importStar(require_chars());
    exports2.utf8Encoder = new TextEncoder();
    exports2.utf8Decoder = new TextDecoder("utf8");
    var decodeB64;
    var encodeB64;
    if (typeof Buffer === "function") {
      exports2.decodeB64 = decodeB64 = (b64) => {
        return Buffer.from(b64, "base64");
      };
      exports2.encodeB64 = encodeB64 = (data) => {
        const buf = !Buffer.isBuffer(data) ? Buffer.from(data.buffer, data.byteOffset, data.byteLength) : data;
        return buf.toString("base64");
      };
    } else {
      exports2.decodeB64 = decodeB64 = (b64) => {
        const binaryString = atob(b64);
        const size = binaryString.length;
        const bytes = new Uint8Array(size);
        for (let i6 = 0; i6 < size; i6++) {
          bytes[i6] = binaryString.charCodeAt(i6);
        }
        return bytes;
      };
      exports2.encodeB64 = encodeB64 = (data) => {
        const binaryString = String.fromCharCode(...data);
        return btoa(binaryString);
      };
    }
    var BUFFER_INC_SIZE = 4096;
    var EMPTY_BUFFER = new Uint8Array(0);
    var BufferError = class extends Error {
    };
    exports2.BufferError = BufferError;
    var WriteBuffer = class {
      constructor() {
        __publicField(this, "_rawBuffer");
        __publicField(this, "buffer");
        __publicField(this, "size");
        __publicField(this, "pos");
        this.size = BUFFER_INC_SIZE;
        this.pos = 0;
        this._rawBuffer = new Uint8Array(this.size);
        this.buffer = new DataView(this._rawBuffer.buffer);
      }
      get position() {
        return this.pos;
      }
      reset() {
        this.pos = 0;
      }
      ensureAlloced(extraLength) {
        const newSize = this.pos + extraLength;
        if (newSize > this.size) {
          this.__realloc(newSize);
        }
      }
      __realloc(newSize) {
        newSize += BUFFER_INC_SIZE;
        const newBuffer = new Uint8Array(newSize);
        newBuffer.set(this._rawBuffer);
        this._rawBuffer = newBuffer;
        this.buffer = new DataView(this._rawBuffer.buffer);
        this.size = newSize;
      }
      writeChar(ch) {
        this.ensureAlloced(1);
        this.buffer.setUint8(this.pos, ch);
        this.pos++;
        return this;
      }
      writeString(s6) {
        return this.writeBytes(exports2.utf8Encoder.encode(s6));
      }
      writeBytes(buf) {
        this.ensureAlloced(buf.length + 4);
        this.buffer.setInt32(this.pos, buf.length);
        this.pos += 4;
        this._rawBuffer.set(buf, this.pos);
        this.pos += buf.length;
        return this;
      }
      writeInt16(i6) {
        this.ensureAlloced(2);
        this.buffer.setInt16(this.pos, i6);
        this.pos += 2;
        return this;
      }
      writeInt32(i6) {
        this.ensureAlloced(4);
        this.buffer.setInt32(this.pos, i6);
        this.pos += 4;
        return this;
      }
      writeFloat32(i6) {
        this.ensureAlloced(4);
        this.buffer.setFloat32(this.pos, i6);
        this.pos += 4;
        return this;
      }
      writeFloat64(i6) {
        this.ensureAlloced(8);
        this.buffer.setFloat64(this.pos, i6);
        this.pos += 8;
        return this;
      }
      writeUInt8(i6) {
        this.ensureAlloced(1);
        this.buffer.setUint8(this.pos, i6);
        this.pos += 1;
        return this;
      }
      writeUInt16(i6) {
        this.ensureAlloced(2);
        this.buffer.setUint16(this.pos, i6);
        this.pos += 2;
        return this;
      }
      writeUInt32(i6) {
        this.ensureAlloced(4);
        this.buffer.setUint32(this.pos, i6);
        this.pos += 4;
        return this;
      }
      writeInt64(i6) {
        this.ensureAlloced(8);
        const hi = Math.floor(i6 / 4294967296);
        const lo = i6 - hi * 4294967296;
        this.buffer.setInt32(this.pos, hi);
        this.buffer.setUint32(this.pos + 4, lo);
        this.pos += 8;
        return this;
      }
      writeBigInt64(i6) {
        let ii = i6;
        if (ii < 0n) {
          ii = 18446744073709551616n + i6;
        }
        const hi = ii >> 32n;
        const lo = ii & 0xffffffffn;
        this.writeUInt32(Number(hi));
        this.writeUInt32(Number(lo));
        return this;
      }
      writeBuffer(buf) {
        const len = buf.length;
        this.ensureAlloced(len);
        this._rawBuffer.set(buf, this.pos);
        this.pos += len;
        return this;
      }
      writeDeferredSize() {
        const startPos = this.pos;
        this.writeInt32(0);
        return () => {
          this.buffer.setInt32(startPos, this.pos - (startPos + 4));
        };
      }
      unwrap() {
        return this._rawBuffer.subarray(0, this.pos);
      }
    };
    exports2.WriteBuffer = WriteBuffer;
    var WriteMessageBuffer = class {
      constructor() {
        __publicField(this, "buffer");
        __publicField(this, "messagePos");
        this.messagePos = -1;
        this.buffer = new WriteBuffer();
      }
      reset() {
        this.messagePos = -1;
        this.buffer.reset();
        return this;
      }
      beginMessage(mtype) {
        if (this.messagePos >= 0) {
          throw new BufferError("cannot begin a new message: the previous message is not finished");
        }
        this.messagePos = this.buffer.position;
        this.buffer.writeChar(mtype);
        this.buffer.writeInt32(0);
        return this;
      }
      endMessage() {
        if (this.messagePos < 0) {
          throw new BufferError("cannot end the message: no current message");
        }
        this.buffer.buffer.setInt32(this.messagePos + 1, this.buffer.position - this.messagePos - 1);
        this.messagePos = -1;
        return this;
      }
      writeChar(ch) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeChar: no current message");
        }
        this.buffer.writeChar(ch);
        return this;
      }
      writeString(s6) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeString: no current message");
        }
        this.buffer.writeString(s6);
        return this;
      }
      writeBytes(val2) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeBytes: no current message");
        }
        this.buffer.writeBytes(val2);
        return this;
      }
      writeInt16(i6) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeInt16: no current message");
        }
        this.buffer.writeInt16(i6);
        return this;
      }
      writeInt32(i6) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeInt32: no current message");
        }
        this.buffer.writeInt32(i6);
        return this;
      }
      writeUInt16(i6) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeInt16: no current message");
        }
        this.buffer.writeUInt16(i6);
        return this;
      }
      writeUInt32(i6) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeInt32: no current message");
        }
        this.buffer.writeUInt32(i6);
        return this;
      }
      writeBigInt64(i6) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeChar: no current message");
        }
        this.buffer.writeBigInt64(i6);
        return this;
      }
      writeFlags(h6, l5) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeChar: no current message");
        }
        this.buffer.writeUInt32(h6);
        this.buffer.writeUInt32(l5);
        return this;
      }
      writeBuffer(buf) {
        if (this.messagePos < 0) {
          throw new BufferError("cannot writeBuffer: no current message");
        }
        this.buffer.writeBuffer(buf);
        return this;
      }
      writeSync() {
        if (this.messagePos >= 0) {
          throw new BufferError("cannot writeSync: the previous message is not finished");
        }
        this.buffer.writeBuffer(SYNC_MESSAGE);
        return this;
      }
      writeFlush() {
        if (this.messagePos >= 0) {
          throw new BufferError("cannot writeFlush: the previous message is not finished");
        }
        this.buffer.writeBuffer(FLUSH_MESSAGE);
        return this;
      }
      unwrap() {
        if (this.messagePos >= 0) {
          throw new BufferError("cannot unwrap: an unfinished message is in the buffer");
        }
        return this.buffer.unwrap();
      }
    };
    exports2.WriteMessageBuffer = WriteMessageBuffer;
    var SYNC_MESSAGE = new WriteMessageBuffer().beginMessage(chars.$S).endMessage().unwrap();
    var FLUSH_MESSAGE = new WriteMessageBuffer().beginMessage(chars.$H).endMessage().unwrap();
    var byteToHex2 = [];
    for (let i6 = 0; i6 < 256; ++i6) {
      byteToHex2.push((i6 + 256).toString(16).slice(1));
    }
    function uuidToBuffer(uuid) {
      const buf = new Uint8Array(16);
      for (let i6 = 0; i6 < 16; i6++) {
        buf[i6] = parseInt(uuid.slice(i6 * 2, i6 * 2 + 2), 16);
      }
      return buf;
    }
    var ReadMessageBuffer = class {
      constructor() {
        __publicField(this, "bufs");
        __publicField(this, "len");
        __publicField(this, "buf0");
        __publicField(this, "pos0");
        __publicField(this, "len0");
        __publicField(this, "curMessageType");
        __publicField(this, "curMessageLen");
        __publicField(this, "curMessageLenUnread");
        __publicField(this, "curMessageReady");
        this.bufs = [];
        this.buf0 = null;
        this.pos0 = 0;
        this.len0 = 0;
        this.len = 0;
        this.curMessageType = 0;
        this.curMessageLen = 0;
        this.curMessageLenUnread = 0;
        this.curMessageReady = false;
      }
      get length() {
        return this.len;
      }
      feed(buf) {
        if (this.buf0 == null || this.pos0 === this.len0 && this.bufs.length === 0) {
          this.buf0 = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
          this.len0 = buf.byteLength;
          this.pos0 = 0;
          this.len = this.len0;
        } else {
          this.feedEnqueue(buf);
        }
      }
      feedEnqueue(buf) {
        this.bufs.push(buf);
        this.len += buf.byteLength;
      }
      ensureFirstBuf() {
        if (this.pos0 === this.len0) {
          this.__nextBuf();
        }
        const buf0 = this.buf0;
        if (buf0 == null || buf0.byteLength < 1) {
          throw new BufferError("empty buffer");
        }
        return buf0;
      }
      checkOverread(size) {
        if (this.curMessageLenUnread < size || size > this.len) {
          throw new BufferError("buffer overread");
        }
      }
      __nextBuf() {
        const nextBuf = this.bufs.shift();
        if (nextBuf == null) {
          throw new BufferError("buffer overread");
        }
        this.buf0 = new DataView(nextBuf.buffer, nextBuf.byteOffset, nextBuf.byteLength);
        this.pos0 = 0;
        this.len0 = nextBuf.byteLength;
      }
      discardBuffer(size) {
        this.ensureFirstBuf();
        while (true) {
          if (this.pos0 + size > this.len0) {
            const nread = this.len0 - this.pos0;
            this.pos0 = this.len0;
            this.len -= nread;
            size -= nread;
            this.ensureFirstBuf();
          } else {
            this.pos0 += size;
            this.len -= size;
            break;
          }
        }
      }
      _finishMessage() {
        this.curMessageLen = 0;
        this.curMessageLenUnread = 0;
        this.curMessageReady = false;
        this.curMessageType = 0;
      }
      __readBufferCopy(buf0, size) {
        const ret = new Uint8Array(size);
        let retPos = 0;
        while (true) {
          if (this.pos0 + size > this.len0) {
            const nread = this.len0 - this.pos0;
            ret.set(new Uint8Array(buf0.buffer, buf0.byteOffset + this.pos0, nread), retPos);
            retPos += nread;
            this.pos0 = this.len0;
            this.len -= nread;
            size -= nread;
            buf0 = this.ensureFirstBuf();
          } else {
            ret.set(new Uint8Array(buf0.buffer, buf0.byteOffset + this.pos0, size), retPos);
            this.pos0 += size;
            this.len -= size;
            break;
          }
        }
        return ret;
      }
      _readBuffer(size) {
        if (size === 0) {
          return EMPTY_BUFFER;
        }
        const buf0 = this.ensureFirstBuf();
        if (this.pos0 + size <= this.len0) {
          const ret = new Uint8Array(buf0.buffer, buf0.byteOffset + this.pos0, size);
          this.pos0 += size;
          this.len -= size;
          return ret;
        }
        return this.__readBufferCopy(buf0, size);
      }
      readBuffer(size) {
        this.checkOverread(size);
        const buf = this._readBuffer(size);
        this.curMessageLenUnread -= size;
        return buf;
      }
      readUUID() {
        const buf = this.readBuffer(16);
        return byteToHex2[buf[0]] + byteToHex2[buf[1]] + byteToHex2[buf[2]] + byteToHex2[buf[3]] + byteToHex2[buf[4]] + byteToHex2[buf[5]] + byteToHex2[buf[6]] + byteToHex2[buf[7]] + byteToHex2[buf[8]] + byteToHex2[buf[9]] + byteToHex2[buf[10]] + byteToHex2[buf[11]] + byteToHex2[buf[12]] + byteToHex2[buf[13]] + byteToHex2[buf[14]] + byteToHex2[buf[15]];
      }
      readChar() {
        this.checkOverread(1);
        const buf0 = this.ensureFirstBuf();
        const ret = buf0.getUint8(this.pos0);
        this.pos0++;
        this.curMessageLenUnread--;
        this.len--;
        return ret;
      }
      readInt16() {
        this.checkOverread(2);
        const buf0 = this.ensureFirstBuf();
        if (this.pos0 + 2 <= this.len0) {
          const ret = buf0.getInt16(this.pos0);
          this.pos0 += 2;
          this.curMessageLenUnread -= 2;
          this.len -= 2;
          return ret;
        }
        const buf = this._readBuffer(2);
        this.curMessageLenUnread -= 2;
        return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getInt16(0);
      }
      readInt32() {
        this.checkOverread(4);
        const buf0 = this.ensureFirstBuf();
        if (this.pos0 + 4 <= this.len0) {
          const ret = buf0.getInt32(this.pos0);
          this.pos0 += 4;
          this.curMessageLenUnread -= 4;
          this.len -= 4;
          return ret;
        }
        const buf = this._readBuffer(4);
        this.curMessageLenUnread -= 4;
        return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getInt32(0);
      }
      readUInt16() {
        this.checkOverread(2);
        const buf0 = this.ensureFirstBuf();
        if (this.pos0 + 2 <= this.len0) {
          const ret = buf0.getUint16(this.pos0);
          this.pos0 += 2;
          this.curMessageLenUnread -= 2;
          this.len -= 2;
          return ret;
        }
        const buf = this._readBuffer(2);
        this.curMessageLenUnread -= 2;
        return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getUint16(0);
      }
      readUInt32() {
        this.checkOverread(4);
        const buf0 = this.ensureFirstBuf();
        if (this.pos0 + 4 <= this.len0) {
          const ret = buf0.getUint32(this.pos0);
          this.pos0 += 4;
          this.curMessageLenUnread -= 4;
          this.len -= 4;
          return ret;
        }
        const buf = this._readBuffer(4);
        this.curMessageLenUnread -= 4;
        return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getUint32(0);
      }
      readBigInt64() {
        this.checkOverread(8);
        const buf0 = this.ensureFirstBuf();
        if (this.pos0 + 8 <= this.len0) {
          const ret = buf0.getBigInt64(this.pos0);
          this.pos0 += 8;
          this.curMessageLenUnread -= 8;
          this.len -= 8;
          return ret;
        }
        const buf = this._readBuffer(8);
        this.curMessageLenUnread -= 8;
        return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getBigInt64(0);
      }
      readString() {
        const len = this.readInt32();
        const buf = this.readBuffer(len);
        return exports2.utf8Decoder.decode(buf);
      }
      readLenPrefixedBuffer() {
        const len = this.readInt32();
        return this.readBuffer(len);
      }
      takeMessage() {
        if (this.curMessageReady) {
          return true;
        }
        if (this.curMessageType === 0) {
          if (this.len < 1) {
            return false;
          }
          const buf0 = this.ensureFirstBuf();
          this.curMessageType = buf0.getUint8(this.pos0);
          this.pos0++;
          this.len--;
        }
        if (this.curMessageLen === 0) {
          if (this.len < 4) {
            return false;
          }
          const buf0 = this.ensureFirstBuf();
          if (this.pos0 + 4 <= this.len0) {
            this.curMessageLen = buf0.getInt32(this.pos0);
            this.pos0 += 4;
            this.len -= 4;
          } else {
            const buf = this._readBuffer(4);
            this.curMessageLen = new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getInt32(0);
          }
          this.curMessageLenUnread = this.curMessageLen - 4;
        }
        if (this.len < this.curMessageLenUnread) {
          return false;
        }
        this.curMessageReady = true;
        return true;
      }
      getMessageType() {
        return this.curMessageType;
      }
      takeMessageType(mtype) {
        if (this.curMessageReady) {
          return this.curMessageType === mtype;
        }
        if (this.len >= 1) {
          const buf0 = this.ensureFirstBuf();
          const unreadMessageType = buf0.getUint8(this.pos0);
          return mtype === unreadMessageType && this.takeMessage();
        }
        return false;
      }
      putMessage() {
        if (!this.curMessageReady) {
          throw new BufferError("cannot put message: no message taken");
        }
        if (this.curMessageLenUnread !== this.curMessageLen - 4) {
          throw new BufferError("cannot put message: message is partially read");
        }
        this.curMessageReady = false;
      }
      discardMessage() {
        if (!this.curMessageReady) {
          throw new BufferError("no message to discard");
        }
        if (this.curMessageLenUnread > 0) {
          this.discardBuffer(this.curMessageLenUnread);
        }
        this._finishMessage();
      }
      consumeMessage() {
        if (!this.curMessageReady) {
          throw new BufferError("no message to consume");
        }
        let buf;
        if (this.curMessageLenUnread > 0) {
          buf = this._readBuffer(this.curMessageLenUnread);
          this.curMessageLenUnread = 0;
        } else {
          buf = EMPTY_BUFFER;
        }
        this._finishMessage();
        return buf;
      }
      consumeMessageInto(frb) {
        if (!this.curMessageReady) {
          throw new BufferError("no message to consume");
        }
        if (this.curMessageLenUnread > 0) {
          if (this.pos0 + this.curMessageLenUnread <= this.len0) {
            ReadBuffer.init(frb, new Uint8Array(this.buf0.buffer, this.buf0.byteOffset + this.pos0, this.curMessageLenUnread));
            this.pos0 += this.curMessageLenUnread;
            this.len -= this.curMessageLenUnread;
          } else {
            const buf = this._readBuffer(this.curMessageLenUnread);
            ReadBuffer.init(frb, buf);
          }
          this.curMessageLenUnread = 0;
        } else {
          ReadBuffer.init(frb, EMPTY_BUFFER);
        }
        this._finishMessage();
      }
      finishMessage() {
        if (this.curMessageType === 0 || !this.curMessageReady) {
          return;
        }
        if (this.curMessageLenUnread) {
          throw new BufferError(`cannot finishMessage: unread data in message "${chars.chr(this.curMessageType)}"`);
        }
        this._finishMessage();
      }
    };
    exports2.ReadMessageBuffer = ReadMessageBuffer;
    var ReadBuffer = class {
      constructor(buf) {
        __publicField(this, "_rawBuffer");
        __publicField(this, "buffer");
        __publicField(this, "pos");
        __publicField(this, "len");
        this._rawBuffer = buf;
        this.buffer = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
        this.len = buf.length;
        this.pos = 0;
      }
      get position() {
        return this.pos;
      }
      get length() {
        return this.len - this.pos;
      }
      finish(message) {
        if (this.len !== this.pos) {
          throw new BufferError(message ?? "unexpected trailing data in buffer");
        }
      }
      discard(size) {
        if (this.pos + size > this.len) {
          throw new BufferError("buffer overread");
        }
        this.pos += size;
      }
      readUInt8() {
        if (this.pos + 1 > this.len) {
          throw new BufferError("buffer overread");
        }
        const num = this.buffer.getUint8(this.pos);
        this.pos++;
        return num;
      }
      readUInt16() {
        if (this.pos + 2 > this.len) {
          throw new BufferError("buffer overread");
        }
        const num = this.buffer.getUint16(this.pos);
        this.pos += 2;
        return num;
      }
      readInt8() {
        if (this.pos + 1 > this.len) {
          throw new BufferError("buffer overread");
        }
        const num = this.buffer.getInt8(this.pos);
        this.pos++;
        return num;
      }
      readInt16() {
        if (this.pos + 2 > this.len) {
          throw new BufferError("buffer overread");
        }
        const num = this.buffer.getInt16(this.pos);
        this.pos += 2;
        return num;
      }
      readInt32() {
        if (this.pos + 4 > this.len) {
          throw new BufferError("buffer overread");
        }
        const num = this.buffer.getInt32(this.pos);
        this.pos += 4;
        return num;
      }
      readFloat32() {
        if (this.pos + 4 > this.len) {
          throw new BufferError("buffer overread");
        }
        const num = this.buffer.getFloat32(this.pos);
        this.pos += 4;
        return num;
      }
      readFloat64(le) {
        if (this.pos + 8 > this.len) {
          throw new BufferError("buffer overread");
        }
        const num = this.buffer.getFloat64(this.pos, le);
        this.pos += 8;
        return num;
      }
      readUInt32(le) {
        if (this.pos + 4 > this.len) {
          throw new BufferError("buffer overread");
        }
        const num = this.buffer.getUint32(this.pos, le);
        this.pos += 4;
        return num;
      }
      reportInt64Overflow(hi, lo) {
        const bhi = BigInt(hi);
        const blo = BigInt(lo >>> 0);
        const num = bhi * BigInt(4294967296) + blo;
        throw new BufferError(`integer overflow: cannot unpack <std::int64>'${num.toString()}' into JavaScript Number type without losing precision`);
      }
      readInt64() {
        if (this.pos + 8 > this.len) {
          throw new BufferError("buffer overread");
        }
        const hi = this.buffer.getInt32(this.pos);
        const lo = this.buffer.getInt32(this.pos + 4);
        this.pos += 8;
        if (hi === 0) {
          return lo >>> 0;
        } else if (hi >= -2097152 && hi < 2097152) {
          return hi * 4294967296 + (lo >>> 0);
        }
        return this.reportInt64Overflow(hi, lo);
      }
      readBigInt64() {
        if (this.pos + 8 > this.len) {
          throw new BufferError("buffer overread");
        }
        const ret = this.buffer.getBigInt64(this.pos);
        this.pos += 8;
        return ret;
      }
      readBoolean() {
        return this.readUInt8() !== 0;
      }
      readBuffer(size) {
        if (this.pos + size > this.len) {
          throw new BufferError("buffer overread");
        }
        const buf = this._rawBuffer.subarray(this.pos, this.pos + size);
        this.pos += size;
        return buf;
      }
      readUUIDBytes() {
        return this.readBuffer(16);
      }
      readUUID(dash = "") {
        if (this.pos + 16 > this.len) {
          throw new BufferError("buffer overread");
        }
        const buf = this._rawBuffer;
        const pos = this.pos;
        const uuid = byteToHex2[buf[pos + 0]] + byteToHex2[buf[pos + 1]] + byteToHex2[buf[pos + 2]] + byteToHex2[buf[pos + 3]] + dash + byteToHex2[buf[pos + 4]] + byteToHex2[buf[pos + 5]] + dash + byteToHex2[buf[pos + 6]] + byteToHex2[buf[pos + 7]] + dash + byteToHex2[buf[pos + 8]] + byteToHex2[buf[pos + 9]] + dash + byteToHex2[buf[pos + 10]] + byteToHex2[buf[pos + 11]] + byteToHex2[buf[pos + 12]] + byteToHex2[buf[pos + 13]] + byteToHex2[buf[pos + 14]] + byteToHex2[buf[pos + 15]];
        this.pos += 16;
        return uuid;
      }
      readString() {
        const len = this.readUInt32();
        const buf = this.readBuffer(len);
        return exports2.utf8Decoder.decode(buf);
      }
      consumeAsString() {
        if (this.pos === this.len) {
          return "";
        }
        const res = exports2.utf8Decoder.decode(this._rawBuffer.subarray(this.pos, this.len));
        this.pos = this.len;
        return res;
      }
      consumeAsBuffer() {
        const res = this._rawBuffer.subarray(this.pos, this.len);
        this.pos = this.len;
        return res;
      }
      sliceInto(frb, size) {
        if (this.pos + size > this.len) {
          throw new BufferError("buffer overread");
        }
        frb._rawBuffer = this._rawBuffer;
        frb.buffer = this.buffer;
        frb.pos = this.pos;
        frb.len = this.pos + size;
        this.pos += size;
      }
      static init(frb, buffer) {
        frb._rawBuffer = buffer;
        frb.buffer = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
        frb.pos = 0;
        frb.len = buffer.byteLength;
      }
      static alloc() {
        return new this(EMPTY_BUFFER);
      }
    };
    exports2.ReadBuffer = ReadBuffer;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/base.js
var require_base = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/base.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ErrorAttr = exports2.GelError = void 0;
    exports2.prettyPrintError = prettyPrintError;
    var buffer_1 = require_buffer();
    var GelError = class extends Error {
      constructor(message, options) {
        super(void 0, options);
        __publicField(this, "_message");
        __publicField(this, "_query");
        __publicField(this, "_attrs");
        Object.defineProperties(this, {
          _message: { writable: true, enumerable: false },
          _query: { writable: true, enumerable: false },
          _attrs: { writable: true, enumerable: false }
        });
        this._message = message ?? "";
      }
      get message() {
        return this._message + (this._query && this._attrs ? prettyPrintError(this._attrs, this._query) : "");
      }
      get name() {
        return this.constructor.name;
      }
      hasTag(tag) {
        const error_type = this.constructor;
        return error_type.tags[tag] ?? false;
      }
    };
    __publicField(GelError, "tags", {});
    exports2.GelError = GelError;
    var ErrorAttr;
    (function(ErrorAttr2) {
      ErrorAttr2[ErrorAttr2["hint"] = 1] = "hint";
      ErrorAttr2[ErrorAttr2["details"] = 2] = "details";
      ErrorAttr2[ErrorAttr2["serverTraceback"] = 257] = "serverTraceback";
      ErrorAttr2[ErrorAttr2["positionStart"] = -15] = "positionStart";
      ErrorAttr2[ErrorAttr2["positionEnd"] = -14] = "positionEnd";
      ErrorAttr2[ErrorAttr2["lineStart"] = -13] = "lineStart";
      ErrorAttr2[ErrorAttr2["columnStart"] = -12] = "columnStart";
      ErrorAttr2[ErrorAttr2["utf16ColumnStart"] = -11] = "utf16ColumnStart";
      ErrorAttr2[ErrorAttr2["lineEnd"] = -10] = "lineEnd";
      ErrorAttr2[ErrorAttr2["columnEnd"] = -9] = "columnEnd";
      ErrorAttr2[ErrorAttr2["utf16ColumnEnd"] = -8] = "utf16ColumnEnd";
      ErrorAttr2[ErrorAttr2["characterStart"] = -7] = "characterStart";
      ErrorAttr2[ErrorAttr2["characterEnd"] = -6] = "characterEnd";
    })(ErrorAttr || (exports2.ErrorAttr = ErrorAttr = {}));
    function tryParseInt(val2) {
      if (val2 == null)
        return null;
      try {
        return parseInt(val2 instanceof Uint8Array ? buffer_1.utf8Decoder.decode(val2) : val2, 10);
      } catch {
        return null;
      }
    }
    function readAttrStr(val2) {
      return val2 instanceof Uint8Array ? buffer_1.utf8Decoder.decode(val2) : val2 ?? "";
    }
    function prettyPrintError(attrs, query) {
      let errMessage = "\n";
      const lineStart = tryParseInt(attrs.get(ErrorAttr.lineStart));
      const lineEnd = tryParseInt(attrs.get(ErrorAttr.lineEnd));
      const colStart = tryParseInt(attrs.get(ErrorAttr.utf16ColumnStart));
      const colEnd = tryParseInt(attrs.get(ErrorAttr.utf16ColumnEnd));
      if (lineStart != null && lineEnd != null && colStart != null && colEnd != null) {
        const queryLines = query.split("\n");
        const lineNoWidth = lineEnd.toString().length;
        errMessage += "|".padStart(lineNoWidth + 3) + "\n";
        for (let i6 = lineStart; i6 < lineEnd + 1; i6++) {
          const line = queryLines[i6 - 1];
          const start = i6 === lineStart ? colStart : 0;
          const end = i6 === lineEnd ? colEnd : line.length;
          errMessage += ` ${i6.toString().padStart(lineNoWidth)} | ${line}
`;
          errMessage += `${"|".padStart(lineNoWidth + 3)} ${"".padStart(end - start, "^").padStart(end)}
`;
        }
      }
      if (attrs.has(ErrorAttr.details)) {
        errMessage += `Details: ${readAttrStr(attrs.get(ErrorAttr.details))}
`;
      }
      if (attrs.has(ErrorAttr.hint)) {
        errMessage += `Hint: ${readAttrStr(attrs.get(ErrorAttr.hint))}
`;
      }
      return errMessage;
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/tags.js
var require_tags = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/tags.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SHOULD_RETRY = exports2.SHOULD_RECONNECT = void 0;
    exports2.SHOULD_RECONNECT = Symbol("SHOULD_RECONNECT");
    exports2.SHOULD_RETRY = Symbol("SHOULD_RETRY");
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/index.js
var require_errors = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/index.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      var desc = Object.getOwnPropertyDescriptor(m6, k5);
      if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m6[k5];
        } };
      }
      Object.defineProperty(o5, k22, desc);
    } : function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      o5[k22] = m6[k5];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v6) {
      Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
    } : function(o5, v6) {
      o5["default"] = v6;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    var __exportStar = exports2 && exports2.__exportStar || function(m6, exports3) {
      for (var p5 in m6) if (p5 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p5)) __createBinding(exports3, m6, p5);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DuplicatePropertyDefinitionError = exports2.DuplicateLinkDefinitionError = exports2.DuplicateModuleDefinitionError = exports2.DuplicateDefinitionError = exports2.InvalidCastDefinitionError = exports2.InvalidConstraintDefinitionError = exports2.InvalidFunctionDefinitionError = exports2.InvalidAliasDefinitionError = exports2.InvalidOperatorDefinitionError = exports2.InvalidDatabaseDefinitionError = exports2.InvalidUserDefinitionError = exports2.InvalidPropertyDefinitionError = exports2.InvalidLinkDefinitionError = exports2.InvalidModuleDefinitionError = exports2.InvalidDefinitionError = exports2.SchemaDefinitionError = exports2.SchemaError = exports2.DeprecatedScopingError = exports2.UnknownParameterError = exports2.UnknownDatabaseError = exports2.UnknownUserError = exports2.UnknownPropertyError = exports2.UnknownLinkError = exports2.UnknownModuleError = exports2.InvalidReferenceError = exports2.InvalidPropertyTargetError = exports2.InvalidLinkTargetError = exports2.InvalidTargetError = exports2.InvalidTypeError = exports2.GraphQLSyntaxError = exports2.SchemaSyntaxError = exports2.EdgeQLSyntaxError = exports2.InvalidSyntaxError = exports2.QueryError = exports2.UnsafeIsolationLevelError = exports2.DisabledCapabilityError = exports2.UnsupportedCapabilityError = exports2.CapabilityError = exports2.ResultCardinalityMismatchError = exports2.StateMismatchError = exports2.ParameterTypeMismatchError = exports2.InputDataError = exports2.UnexpectedMessageError = exports2.TypeSpecNotFoundError = exports2.UnsupportedProtocolVersionError = exports2.BinaryProtocolError = exports2.ProtocolError = exports2.UnsupportedFeatureError = exports2.InternalServerError = exports2.GelError = void 0;
    exports2.QueryArgumentError = exports2.InterfaceError = exports2.ClientConnectionClosedError = exports2.ClientConnectionTimeoutError = exports2.ClientConnectionFailedTemporarilyError = exports2.ClientConnectionFailedError = exports2.ClientConnectionError = exports2.ClientError = exports2.MigrationStatusMessage = exports2.StatusMessage = exports2.WarningMessage = exports2.LogMessage = exports2.UnsupportedBackendFeatureError = exports2.BackendError = exports2.ServerBlockedError = exports2.UnknownTenantError = exports2.ServerOfflineError = exports2.BackendUnavailableError = exports2.AvailabilityError = exports2.AuthenticationError = exports2.AccessError = exports2.ConfigurationError = exports2.WatchError = exports2.TransactionDeadlockError = exports2.TransactionSerializationError = exports2.TransactionConflictError = exports2.TransactionError = exports2.MissingRequiredError = exports2.CardinalityViolationError = exports2.ConstraintViolationError = exports2.IntegrityError = exports2.QueryAssertionError = exports2.AccessPolicyError = exports2.NumericOutOfRangeError = exports2.DivisionByZeroError = exports2.InvalidValueError = exports2.ExecutionError = exports2.IdleTransactionTimeoutError = exports2.TransactionTimeoutError = exports2.QueryTimeoutError = exports2.IdleSessionTimeoutError = exports2.SessionTimeoutError = exports2.DuplicateMigrationError = exports2.DuplicateCastDefinitionError = exports2.DuplicateConstraintDefinitionError = exports2.DuplicateFunctionDefinitionError = exports2.DuplicateViewDefinitionError = exports2.DuplicateOperatorDefinitionError = exports2.DuplicateDatabaseDefinitionError = exports2.DuplicateUserDefinitionError = void 0;
    exports2.InternalClientError = exports2.NoDataError = exports2.InvalidArgumentError = exports2.UnknownArgumentError = exports2.MissingArgumentError = void 0;
    var base_1 = require_base();
    var tags = __importStar(require_tags());
    var base_2 = require_base();
    Object.defineProperty(exports2, "GelError", { enumerable: true, get: function() {
      return base_2.GelError;
    } });
    __exportStar(require_tags(), exports2);
    var InternalServerError = class extends base_1.GelError {
      get code() {
        return 16777216;
      }
    };
    exports2.InternalServerError = InternalServerError;
    var UnsupportedFeatureError = class extends base_1.GelError {
      get code() {
        return 33554432;
      }
    };
    exports2.UnsupportedFeatureError = UnsupportedFeatureError;
    var ProtocolError = class extends base_1.GelError {
      get code() {
        return 50331648;
      }
    };
    exports2.ProtocolError = ProtocolError;
    var BinaryProtocolError = class extends ProtocolError {
      get code() {
        return 50397184;
      }
    };
    exports2.BinaryProtocolError = BinaryProtocolError;
    var UnsupportedProtocolVersionError = class extends BinaryProtocolError {
      get code() {
        return 50397185;
      }
    };
    exports2.UnsupportedProtocolVersionError = UnsupportedProtocolVersionError;
    var TypeSpecNotFoundError = class extends BinaryProtocolError {
      get code() {
        return 50397186;
      }
    };
    exports2.TypeSpecNotFoundError = TypeSpecNotFoundError;
    var UnexpectedMessageError = class extends BinaryProtocolError {
      get code() {
        return 50397187;
      }
    };
    exports2.UnexpectedMessageError = UnexpectedMessageError;
    var InputDataError = class extends ProtocolError {
      get code() {
        return 50462720;
      }
    };
    exports2.InputDataError = InputDataError;
    var ParameterTypeMismatchError = class extends InputDataError {
      get code() {
        return 50462976;
      }
    };
    exports2.ParameterTypeMismatchError = ParameterTypeMismatchError;
    var StateMismatchError = class extends InputDataError {
      get code() {
        return 50463232;
      }
    };
    __publicField(StateMismatchError, "tags", { [tags.SHOULD_RETRY]: true });
    exports2.StateMismatchError = StateMismatchError;
    var ResultCardinalityMismatchError = class extends ProtocolError {
      get code() {
        return 50528256;
      }
    };
    exports2.ResultCardinalityMismatchError = ResultCardinalityMismatchError;
    var CapabilityError = class extends ProtocolError {
      get code() {
        return 50593792;
      }
    };
    exports2.CapabilityError = CapabilityError;
    var UnsupportedCapabilityError = class extends CapabilityError {
      get code() {
        return 50594048;
      }
    };
    exports2.UnsupportedCapabilityError = UnsupportedCapabilityError;
    var DisabledCapabilityError = class extends CapabilityError {
      get code() {
        return 50594304;
      }
    };
    exports2.DisabledCapabilityError = DisabledCapabilityError;
    var UnsafeIsolationLevelError = class extends CapabilityError {
      get code() {
        return 50594560;
      }
    };
    exports2.UnsafeIsolationLevelError = UnsafeIsolationLevelError;
    var QueryError = class extends base_1.GelError {
      get code() {
        return 67108864;
      }
    };
    exports2.QueryError = QueryError;
    var InvalidSyntaxError = class extends QueryError {
      get code() {
        return 67174400;
      }
    };
    exports2.InvalidSyntaxError = InvalidSyntaxError;
    var EdgeQLSyntaxError = class extends InvalidSyntaxError {
      get code() {
        return 67174656;
      }
    };
    exports2.EdgeQLSyntaxError = EdgeQLSyntaxError;
    var SchemaSyntaxError = class extends InvalidSyntaxError {
      get code() {
        return 67174912;
      }
    };
    exports2.SchemaSyntaxError = SchemaSyntaxError;
    var GraphQLSyntaxError = class extends InvalidSyntaxError {
      get code() {
        return 67175168;
      }
    };
    exports2.GraphQLSyntaxError = GraphQLSyntaxError;
    var InvalidTypeError = class extends QueryError {
      get code() {
        return 67239936;
      }
    };
    exports2.InvalidTypeError = InvalidTypeError;
    var InvalidTargetError = class extends InvalidTypeError {
      get code() {
        return 67240192;
      }
    };
    exports2.InvalidTargetError = InvalidTargetError;
    var InvalidLinkTargetError = class extends InvalidTargetError {
      get code() {
        return 67240193;
      }
    };
    exports2.InvalidLinkTargetError = InvalidLinkTargetError;
    var InvalidPropertyTargetError = class extends InvalidTargetError {
      get code() {
        return 67240194;
      }
    };
    exports2.InvalidPropertyTargetError = InvalidPropertyTargetError;
    var InvalidReferenceError = class extends QueryError {
      get code() {
        return 67305472;
      }
    };
    exports2.InvalidReferenceError = InvalidReferenceError;
    var UnknownModuleError = class extends InvalidReferenceError {
      get code() {
        return 67305473;
      }
    };
    exports2.UnknownModuleError = UnknownModuleError;
    var UnknownLinkError = class extends InvalidReferenceError {
      get code() {
        return 67305474;
      }
    };
    exports2.UnknownLinkError = UnknownLinkError;
    var UnknownPropertyError = class extends InvalidReferenceError {
      get code() {
        return 67305475;
      }
    };
    exports2.UnknownPropertyError = UnknownPropertyError;
    var UnknownUserError = class extends InvalidReferenceError {
      get code() {
        return 67305476;
      }
    };
    exports2.UnknownUserError = UnknownUserError;
    var UnknownDatabaseError = class extends InvalidReferenceError {
      get code() {
        return 67305477;
      }
    };
    exports2.UnknownDatabaseError = UnknownDatabaseError;
    var UnknownParameterError = class extends InvalidReferenceError {
      get code() {
        return 67305478;
      }
    };
    exports2.UnknownParameterError = UnknownParameterError;
    var DeprecatedScopingError = class extends InvalidReferenceError {
      get code() {
        return 67305479;
      }
    };
    exports2.DeprecatedScopingError = DeprecatedScopingError;
    var SchemaError = class extends QueryError {
      get code() {
        return 67371008;
      }
    };
    exports2.SchemaError = SchemaError;
    var SchemaDefinitionError = class extends QueryError {
      get code() {
        return 67436544;
      }
    };
    exports2.SchemaDefinitionError = SchemaDefinitionError;
    var InvalidDefinitionError = class extends SchemaDefinitionError {
      get code() {
        return 67436800;
      }
    };
    exports2.InvalidDefinitionError = InvalidDefinitionError;
    var InvalidModuleDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436801;
      }
    };
    exports2.InvalidModuleDefinitionError = InvalidModuleDefinitionError;
    var InvalidLinkDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436802;
      }
    };
    exports2.InvalidLinkDefinitionError = InvalidLinkDefinitionError;
    var InvalidPropertyDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436803;
      }
    };
    exports2.InvalidPropertyDefinitionError = InvalidPropertyDefinitionError;
    var InvalidUserDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436804;
      }
    };
    exports2.InvalidUserDefinitionError = InvalidUserDefinitionError;
    var InvalidDatabaseDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436805;
      }
    };
    exports2.InvalidDatabaseDefinitionError = InvalidDatabaseDefinitionError;
    var InvalidOperatorDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436806;
      }
    };
    exports2.InvalidOperatorDefinitionError = InvalidOperatorDefinitionError;
    var InvalidAliasDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436807;
      }
    };
    exports2.InvalidAliasDefinitionError = InvalidAliasDefinitionError;
    var InvalidFunctionDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436808;
      }
    };
    exports2.InvalidFunctionDefinitionError = InvalidFunctionDefinitionError;
    var InvalidConstraintDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436809;
      }
    };
    exports2.InvalidConstraintDefinitionError = InvalidConstraintDefinitionError;
    var InvalidCastDefinitionError = class extends InvalidDefinitionError {
      get code() {
        return 67436810;
      }
    };
    exports2.InvalidCastDefinitionError = InvalidCastDefinitionError;
    var DuplicateDefinitionError = class extends SchemaDefinitionError {
      get code() {
        return 67437056;
      }
    };
    exports2.DuplicateDefinitionError = DuplicateDefinitionError;
    var DuplicateModuleDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437057;
      }
    };
    exports2.DuplicateModuleDefinitionError = DuplicateModuleDefinitionError;
    var DuplicateLinkDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437058;
      }
    };
    exports2.DuplicateLinkDefinitionError = DuplicateLinkDefinitionError;
    var DuplicatePropertyDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437059;
      }
    };
    exports2.DuplicatePropertyDefinitionError = DuplicatePropertyDefinitionError;
    var DuplicateUserDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437060;
      }
    };
    exports2.DuplicateUserDefinitionError = DuplicateUserDefinitionError;
    var DuplicateDatabaseDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437061;
      }
    };
    exports2.DuplicateDatabaseDefinitionError = DuplicateDatabaseDefinitionError;
    var DuplicateOperatorDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437062;
      }
    };
    exports2.DuplicateOperatorDefinitionError = DuplicateOperatorDefinitionError;
    var DuplicateViewDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437063;
      }
    };
    exports2.DuplicateViewDefinitionError = DuplicateViewDefinitionError;
    var DuplicateFunctionDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437064;
      }
    };
    exports2.DuplicateFunctionDefinitionError = DuplicateFunctionDefinitionError;
    var DuplicateConstraintDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437065;
      }
    };
    exports2.DuplicateConstraintDefinitionError = DuplicateConstraintDefinitionError;
    var DuplicateCastDefinitionError = class extends DuplicateDefinitionError {
      get code() {
        return 67437066;
      }
    };
    exports2.DuplicateCastDefinitionError = DuplicateCastDefinitionError;
    var DuplicateMigrationError = class extends DuplicateDefinitionError {
      get code() {
        return 67437067;
      }
    };
    exports2.DuplicateMigrationError = DuplicateMigrationError;
    var SessionTimeoutError = class extends QueryError {
      get code() {
        return 67502080;
      }
    };
    exports2.SessionTimeoutError = SessionTimeoutError;
    var IdleSessionTimeoutError = class extends SessionTimeoutError {
      get code() {
        return 67502336;
      }
    };
    __publicField(IdleSessionTimeoutError, "tags", { [tags.SHOULD_RETRY]: true });
    exports2.IdleSessionTimeoutError = IdleSessionTimeoutError;
    var QueryTimeoutError = class extends SessionTimeoutError {
      get code() {
        return 67502592;
      }
    };
    exports2.QueryTimeoutError = QueryTimeoutError;
    var TransactionTimeoutError = class extends SessionTimeoutError {
      get code() {
        return 67504640;
      }
    };
    exports2.TransactionTimeoutError = TransactionTimeoutError;
    var IdleTransactionTimeoutError = class extends TransactionTimeoutError {
      get code() {
        return 67504641;
      }
    };
    exports2.IdleTransactionTimeoutError = IdleTransactionTimeoutError;
    var ExecutionError = class extends base_1.GelError {
      get code() {
        return 83886080;
      }
    };
    exports2.ExecutionError = ExecutionError;
    var InvalidValueError = class extends ExecutionError {
      get code() {
        return 83951616;
      }
    };
    exports2.InvalidValueError = InvalidValueError;
    var DivisionByZeroError = class extends InvalidValueError {
      get code() {
        return 83951617;
      }
    };
    exports2.DivisionByZeroError = DivisionByZeroError;
    var NumericOutOfRangeError = class extends InvalidValueError {
      get code() {
        return 83951618;
      }
    };
    exports2.NumericOutOfRangeError = NumericOutOfRangeError;
    var AccessPolicyError = class extends InvalidValueError {
      get code() {
        return 83951619;
      }
    };
    exports2.AccessPolicyError = AccessPolicyError;
    var QueryAssertionError = class extends InvalidValueError {
      get code() {
        return 83951620;
      }
    };
    exports2.QueryAssertionError = QueryAssertionError;
    var IntegrityError = class extends ExecutionError {
      get code() {
        return 84017152;
      }
    };
    exports2.IntegrityError = IntegrityError;
    var ConstraintViolationError = class extends IntegrityError {
      get code() {
        return 84017153;
      }
    };
    exports2.ConstraintViolationError = ConstraintViolationError;
    var CardinalityViolationError = class extends IntegrityError {
      get code() {
        return 84017154;
      }
    };
    exports2.CardinalityViolationError = CardinalityViolationError;
    var MissingRequiredError = class extends IntegrityError {
      get code() {
        return 84017155;
      }
    };
    exports2.MissingRequiredError = MissingRequiredError;
    var TransactionError = class extends ExecutionError {
      get code() {
        return 84082688;
      }
    };
    exports2.TransactionError = TransactionError;
    var TransactionConflictError = class extends TransactionError {
      get code() {
        return 84082944;
      }
    };
    __publicField(TransactionConflictError, "tags", { [tags.SHOULD_RETRY]: true });
    exports2.TransactionConflictError = TransactionConflictError;
    var TransactionSerializationError = class extends TransactionConflictError {
      get code() {
        return 84082945;
      }
    };
    __publicField(TransactionSerializationError, "tags", { [tags.SHOULD_RETRY]: true });
    exports2.TransactionSerializationError = TransactionSerializationError;
    var TransactionDeadlockError = class extends TransactionConflictError {
      get code() {
        return 84082946;
      }
    };
    __publicField(TransactionDeadlockError, "tags", { [tags.SHOULD_RETRY]: true });
    exports2.TransactionDeadlockError = TransactionDeadlockError;
    var WatchError = class extends ExecutionError {
      get code() {
        return 84148224;
      }
    };
    exports2.WatchError = WatchError;
    var ConfigurationError = class extends base_1.GelError {
      get code() {
        return 100663296;
      }
    };
    exports2.ConfigurationError = ConfigurationError;
    var AccessError = class extends base_1.GelError {
      get code() {
        return 117440512;
      }
    };
    exports2.AccessError = AccessError;
    var AuthenticationError = class extends AccessError {
      get code() {
        return 117506048;
      }
    };
    exports2.AuthenticationError = AuthenticationError;
    var AvailabilityError = class extends base_1.GelError {
      get code() {
        return 134217728;
      }
    };
    exports2.AvailabilityError = AvailabilityError;
    var BackendUnavailableError = class extends AvailabilityError {
      get code() {
        return 134217729;
      }
    };
    __publicField(BackendUnavailableError, "tags", { [tags.SHOULD_RETRY]: true });
    exports2.BackendUnavailableError = BackendUnavailableError;
    var ServerOfflineError = class extends AvailabilityError {
      get code() {
        return 134217730;
      }
    };
    __publicField(ServerOfflineError, "tags", {
      [tags.SHOULD_RECONNECT]: true,
      [tags.SHOULD_RETRY]: true
    });
    exports2.ServerOfflineError = ServerOfflineError;
    var UnknownTenantError = class extends AvailabilityError {
      get code() {
        return 134217731;
      }
    };
    __publicField(UnknownTenantError, "tags", {
      [tags.SHOULD_RECONNECT]: true,
      [tags.SHOULD_RETRY]: true
    });
    exports2.UnknownTenantError = UnknownTenantError;
    var ServerBlockedError = class extends AvailabilityError {
      get code() {
        return 134217732;
      }
    };
    exports2.ServerBlockedError = ServerBlockedError;
    var BackendError = class extends base_1.GelError {
      get code() {
        return 150994944;
      }
    };
    exports2.BackendError = BackendError;
    var UnsupportedBackendFeatureError = class extends BackendError {
      get code() {
        return 150995200;
      }
    };
    exports2.UnsupportedBackendFeatureError = UnsupportedBackendFeatureError;
    var LogMessage = class extends base_1.GelError {
      get code() {
        return 4026531840;
      }
    };
    exports2.LogMessage = LogMessage;
    var WarningMessage = class extends LogMessage {
      get code() {
        return 4026597376;
      }
    };
    exports2.WarningMessage = WarningMessage;
    var StatusMessage = class extends LogMessage {
      get code() {
        return 4026662912;
      }
    };
    exports2.StatusMessage = StatusMessage;
    var MigrationStatusMessage = class extends StatusMessage {
      get code() {
        return 4026662913;
      }
    };
    exports2.MigrationStatusMessage = MigrationStatusMessage;
    var ClientError = class extends base_1.GelError {
      get code() {
        return 4278190080;
      }
    };
    exports2.ClientError = ClientError;
    var ClientConnectionError = class extends ClientError {
      get code() {
        return 4278255616;
      }
    };
    exports2.ClientConnectionError = ClientConnectionError;
    var ClientConnectionFailedError = class extends ClientConnectionError {
      get code() {
        return 4278255872;
      }
    };
    exports2.ClientConnectionFailedError = ClientConnectionFailedError;
    var ClientConnectionFailedTemporarilyError = class extends ClientConnectionFailedError {
      get code() {
        return 4278255873;
      }
    };
    __publicField(ClientConnectionFailedTemporarilyError, "tags", {
      [tags.SHOULD_RECONNECT]: true,
      [tags.SHOULD_RETRY]: true
    });
    exports2.ClientConnectionFailedTemporarilyError = ClientConnectionFailedTemporarilyError;
    var ClientConnectionTimeoutError = class extends ClientConnectionError {
      get code() {
        return 4278256128;
      }
    };
    __publicField(ClientConnectionTimeoutError, "tags", {
      [tags.SHOULD_RECONNECT]: true,
      [tags.SHOULD_RETRY]: true
    });
    exports2.ClientConnectionTimeoutError = ClientConnectionTimeoutError;
    var ClientConnectionClosedError = class extends ClientConnectionError {
      get code() {
        return 4278256384;
      }
    };
    __publicField(ClientConnectionClosedError, "tags", {
      [tags.SHOULD_RECONNECT]: true,
      [tags.SHOULD_RETRY]: true
    });
    exports2.ClientConnectionClosedError = ClientConnectionClosedError;
    var InterfaceError = class extends ClientError {
      get code() {
        return 4278321152;
      }
    };
    exports2.InterfaceError = InterfaceError;
    var QueryArgumentError = class extends InterfaceError {
      get code() {
        return 4278321408;
      }
    };
    exports2.QueryArgumentError = QueryArgumentError;
    var MissingArgumentError = class extends QueryArgumentError {
      get code() {
        return 4278321409;
      }
    };
    exports2.MissingArgumentError = MissingArgumentError;
    var UnknownArgumentError = class extends QueryArgumentError {
      get code() {
        return 4278321410;
      }
    };
    exports2.UnknownArgumentError = UnknownArgumentError;
    var InvalidArgumentError = class extends QueryArgumentError {
      get code() {
        return 4278321411;
      }
    };
    exports2.InvalidArgumentError = InvalidArgumentError;
    var NoDataError = class extends ClientError {
      get code() {
        return 4278386688;
      }
    };
    exports2.NoDataError = NoDataError;
    var InternalClientError = class extends ClientError {
      get code() {
        return 4278452224;
      }
    };
    exports2.InternalClientError = InternalClientError;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/lru.js
var require_lru = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/lru.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var errors_1 = require_errors();
    var Node3 = class {
      constructor(key, value) {
        __publicField(this, "key");
        __publicField(this, "value");
        __publicField(this, "next");
        __publicField(this, "prev");
        this.key = key;
        this.value = value;
        this.next = null;
        this.prev = null;
      }
    };
    var Deque = class {
      constructor() {
        __publicField(this, "head");
        __publicField(this, "tail");
        __publicField(this, "len");
        this.head = null;
        this.tail = null;
        this.len = 0;
      }
      get length() {
        return this.len;
      }
      push(key, value) {
        const node = new Node3(key, value);
        if (this.head == null) {
          this.head = node;
          this.tail = node;
        } else {
          this.head.prev = node;
          node.next = this.head;
          this.head = node;
        }
        this.len++;
        return node;
      }
      moveToTop(node) {
        if (node.prev == null) {
          return;
        }
        const prev = node.prev;
        const next = node.next;
        prev.next = next;
        if (next != null) {
          next.prev = prev;
        }
        if (this.tail === node) {
          this.tail = prev;
        }
        node.prev = null;
        node.next = this.head;
        this.head.prev = node;
        this.head = node;
      }
      deleteBottom() {
        if (!this.len || !this.tail || !this.head) {
          return null;
        }
        if (this.tail === this.head) {
          this.len = 0;
          const node = this.tail;
          this.tail = null;
          this.head = null;
          return node;
        }
        const tail = this.tail;
        const beforeLast = this.tail.prev;
        beforeLast.next = null;
        this.tail.prev = null;
        this.tail.next = null;
        this.tail = beforeLast;
        this.len--;
        return tail;
      }
    };
    var LRU = class {
      constructor({ capacity }) {
        __publicField(this, "capacity");
        __publicField(this, "map");
        __publicField(this, "deque");
        if (capacity <= 0) {
          throw new TypeError("capacity is expected to be greater than 0");
        }
        this.capacity = capacity;
        this.map = /* @__PURE__ */ new Map();
        this.deque = new Deque();
      }
      get length() {
        const len = this.map.size;
        if (len !== this.deque.length) {
          throw new errors_1.InternalClientError("deque & map disagree on elements count");
        }
        return len;
      }
      has(key) {
        return this.map.has(key);
      }
      get(key) {
        const node = this.map.get(key);
        if (node != null) {
          this.deque.moveToTop(node);
          return node.value;
        }
        return void 0;
      }
      set(key, value) {
        const existingNode = this.map.get(key);
        if (existingNode != null) {
          existingNode.value = value;
          this.deque.moveToTop(existingNode);
        } else {
          const newNode = this.deque.push(key, value);
          this.map.set(key, newNode);
          while (this.deque.length > this.capacity) {
            const bottomNode = this.deque.deleteBottom();
            this.map.delete(bottomNode.key);
          }
        }
      }
      *keys() {
        let node = this.deque.head;
        while (node != null) {
          yield node.key;
          node = node.next;
        }
      }
      *entries() {
        let node = this.deque.head;
        while (node != null) {
          yield [node.key, node.value];
          node = node.next;
        }
      }
      *values() {
        let node = this.deque.head;
        while (node != null) {
          yield node.value;
          node = node.next;
        }
      }
    };
    exports2.default = LRU;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/consts.js
var require_consts = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/consts.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.KNOWN_TYPENAMES = exports2.KNOWN_TYPES = exports2.INVALID_CODEC_ID = exports2.NULL_CODEC_ID = void 0;
    exports2.NULL_CODEC_ID = "00000000000000000000000000000000";
    exports2.INVALID_CODEC_ID = "ffffffffffffffffffffffffffffffff";
    exports2.KNOWN_TYPES = /* @__PURE__ */ new Map([
      ["00000000000000000000000000000001", "anytype"],
      ["00000000000000000000000000000002", "anytuple"],
      ["00000000000000000000000000000003", "anyobject"],
      ["000000000000000000000000000000f0", "std"],
      ["000000000000000000000000000000ff", "empty-tuple"],
      ["00000000000000000000000000000100", "std::uuid"],
      ["00000000000000000000000000000101", "std::str"],
      ["00000000000000000000000000000102", "std::bytes"],
      ["00000000000000000000000000000103", "std::int16"],
      ["00000000000000000000000000000104", "std::int32"],
      ["00000000000000000000000000000105", "std::int64"],
      ["00000000000000000000000000000106", "std::float32"],
      ["00000000000000000000000000000107", "std::float64"],
      ["00000000000000000000000000000108", "std::decimal"],
      ["00000000000000000000000000000109", "std::bool"],
      ["0000000000000000000000000000010a", "std::datetime"],
      ["0000000000000000000000000000010b", "cal::local_datetime"],
      ["0000000000000000000000000000010c", "cal::local_date"],
      ["0000000000000000000000000000010d", "cal::local_time"],
      ["0000000000000000000000000000010e", "std::duration"],
      ["0000000000000000000000000000010f", "std::json"],
      ["00000000000000000000000000000110", "std::bigint"],
      ["00000000000000000000000000000111", "cal::relative_duration"],
      ["00000000000000000000000000000112", "cal::date_duration"],
      ["00000000000000000000000000000130", "cfg::memory"],
      ["00000000000000000000000001000001", "std::pg::json"],
      ["00000000000000000000000001000002", "std::pg::timestamptz"],
      ["00000000000000000000000001000003", "std::pg::timestamp"],
      ["00000000000000000000000001000004", "std::pg::date"],
      ["00000000000000000000000001000005", "std::pg::interval"],
      ["9565dd8804f511eea6910b6ebe179825", "ext::pgvector::vector"],
      ["4ba84534188e43b4a7cecea2af0f405b", "ext::pgvector::halfvec"],
      ["003e434dcac2430ab238fb39d73447d2", "ext::pgvector::sparsevec"],
      ["44c901c0d922489483c8061bd05e4840", "ext::postgis::geometry"],
      ["4d7388783a5f4821ab769d8e7d6b32c4", "ext::postgis::geography"],
      ["7fae553663114f608eb9096a5d972f48", "ext::postgis::box2d"],
      ["c1a50ff8fded48b085c24905a8481433", "ext::postgis::box3d"]
    ]);
    exports2.KNOWN_TYPENAMES = (() => {
      const res = /* @__PURE__ */ new Map();
      for (const [id, name] of exports2.KNOWN_TYPES.entries()) {
        res.set(name, id);
      }
      return res;
    })();
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/ifaces.js
var require_ifaces = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/ifaces.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ScalarCodec = exports2.Codec = void 0;
    var buffer_1 = require_buffer();
    var consts_1 = require_consts();
    var Codec = class {
      constructor(tid) {
        __publicField(this, "tid");
        __publicField(this, "tidBuffer");
        this.tid = tid;
        this.tidBuffer = (0, buffer_1.uuidToBuffer)(tid);
      }
      getKnownTypeName() {
        return "anytype";
      }
    };
    exports2.Codec = Codec;
    var ScalarCodec = class extends Codec {
      constructor(tid, typeName) {
        super(tid);
        __publicField(this, "typeName");
        __publicField(this, "ancestors", null);
        __publicField(this, "tsType", "unknown");
        __publicField(this, "tsModule", null);
        this.typeName = typeName;
      }
      derive(tid, typeName, ancestors) {
        const self2 = this.constructor;
        const codec = new self2(tid, typeName);
        codec.ancestors = ancestors;
        return codec;
      }
      getSubcodecs() {
        return [];
      }
      getKind() {
        return "scalar";
      }
      getKnownTypeName() {
        if (this.typeName) {
          return this.typeName;
        }
        return consts_1.KNOWN_TYPES.get(this.tid) || "anytype";
      }
    };
    exports2.ScalarCodec = ScalarCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/boolean.js
var require_boolean = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/boolean.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BoolCodec = void 0;
    var ifaces_1 = require_ifaces();
    var errors_1 = require_errors();
    var BoolCodec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "boolean");
      }
      encode(buf, object, ctx) {
        const val2 = ctx.preEncode(this, object);
        const typeOf = typeof val2;
        if (typeOf !== "boolean" && typeOf !== "number") {
          throw new errors_1.InvalidArgumentError(`a boolean or a number was expected, got "${val2}"`);
        }
        buf.writeInt32(1);
        buf.writeChar(val2 ? 1 : 0);
      }
      decode(buf, ctx) {
        return ctx.postDecode(this, buf.readUInt8() !== 0);
      }
    };
    exports2.BoolCodec = BoolCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/numbers.js
var require_numbers = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/numbers.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Float64Codec = exports2.Float32Codec = exports2.Int16Codec = exports2.Int32Codec = exports2.Int64Codec = void 0;
    var ifaces_1 = require_ifaces();
    var errors_1 = require_errors();
    var Int64Codec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "number");
      }
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const val2 = ctx.preEncode(this, object);
          buf.writeInt32(8);
          buf.writeBigInt64(val2);
          return;
        }
        if (typeof object !== "number") {
          throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
        }
        buf.writeInt32(8);
        buf.writeInt64(object);
      }
      decode(buf, ctx) {
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, buf.readBigInt64());
        }
        return buf.readInt64();
      }
    };
    exports2.Int64Codec = Int64Codec;
    var Int32Codec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "number");
      }
      encode(buf, object, ctx) {
        object = ctx.preEncode(this, object);
        if (typeof object !== "number") {
          throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
        }
        buf.writeInt32(4);
        buf.writeInt32(object);
      }
      decode(buf, ctx) {
        return ctx.postDecode(this, buf.readInt32());
      }
    };
    exports2.Int32Codec = Int32Codec;
    var Int16Codec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "number");
      }
      encode(buf, object, ctx) {
        object = ctx.preEncode(this, object);
        if (typeof object !== "number") {
          throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
        }
        buf.writeInt32(2);
        buf.writeInt16(object);
      }
      decode(buf, ctx) {
        return ctx.postDecode(this, buf.readInt16());
      }
    };
    exports2.Int16Codec = Int16Codec;
    var Float32Codec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "number");
      }
      encode(buf, object, ctx) {
        object = ctx.preEncode(this, object);
        if (typeof object !== "number") {
          throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
        }
        buf.writeInt32(4);
        buf.writeFloat32(object);
      }
      decode(buf, ctx) {
        return ctx.postDecode(this, buf.readFloat32());
      }
    };
    exports2.Float32Codec = Float32Codec;
    var Float64Codec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "number");
      }
      encode(buf, object, ctx) {
        object = ctx.preEncode(this, object);
        if (typeof object !== "number") {
          throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
        }
        buf.writeInt32(8);
        buf.writeFloat64(object);
      }
      decode(buf, ctx) {
        return ctx.postDecode(this, buf.readFloat64());
      }
    };
    exports2.Float64Codec = Float64Codec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/numerics.js
var require_numerics = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/numerics.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DecimalStringCodec = exports2.BigIntCodec = void 0;
    var ifaces_1 = require_ifaces();
    var errors_1 = require_errors();
    var NUMERIC_POS = 0;
    var NUMERIC_NEG = 16384;
    var BigIntCodec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "bigint");
      }
      encode(buf, object, ctx) {
        object = ctx.preEncode(this, object);
        if (typeof object !== "bigint") {
          throw new errors_1.InvalidArgumentError(`a bigint was expected, got "${object}"`);
        }
        const digits = [];
        let sign = NUMERIC_POS;
        let uval = object;
        if (object === 0n) {
          buf.writeUInt32(8);
          buf.writeUInt32(0);
          buf.writeUInt16(NUMERIC_POS);
          buf.writeUInt16(0);
          return;
        }
        if (object < 0n) {
          sign = NUMERIC_NEG;
          uval = -uval;
        }
        while (uval) {
          const mod = uval % 10000n;
          uval /= 10000n;
          digits.push(mod);
        }
        buf.writeUInt32(8 + digits.length * 2);
        buf.writeUInt16(digits.length);
        buf.writeUInt16(digits.length - 1);
        buf.writeUInt16(sign);
        buf.writeUInt16(0);
        for (let i6 = digits.length - 1; i6 >= 0; i6--) {
          buf.writeUInt16(Number(digits[i6]));
        }
      }
      decode(buf, ctx) {
        const val2 = BigInt(decodeBigIntToString(buf));
        return ctx.postDecode(this, val2);
      }
    };
    exports2.BigIntCodec = BigIntCodec;
    var DecimalStringCodec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "string");
      }
      encode(buf, object, ctx) {
        object = ctx.preEncode(this, object);
        if (typeof object !== "string") {
          throw new errors_1.InvalidArgumentError(`a string was expected, got "${object}"`);
        }
        const match2 = object.match(/^(-?)([0-9]+)(?:\.([0-9]+))?(?:[eE]([-+]?[0-9]+))?$/);
        if (!match2) {
          throw new errors_1.InvalidArgumentError(`invalid decimal string "${object}"`);
        }
        const [_3, sign, int, _frac, _exp] = match2;
        const frac = _frac ?? "";
        const exp = _exp ? parseInt(_exp, 10) : 0;
        const sdigits = int.padStart(Math.ceil(int.length / 4) * 4, "0") + frac.padEnd(Math.ceil(frac.length / 4) * 4, "0");
        const digits = [];
        for (let i6 = 0, len = sdigits.length; i6 < len; i6 += 4) {
          digits.push(parseInt(sdigits.slice(i6, i6 + 4), 10));
        }
        buf.writeUInt32(8 + digits.length * 2);
        buf.writeUInt16(digits.length);
        buf.writeInt16(Math.ceil((int.length + exp) / 4) - 1);
        buf.writeUInt16(sign === "-" ? NUMERIC_NEG : NUMERIC_POS);
        buf.writeUInt16(Math.max(frac.length - exp, 0));
        for (let i6 = 0, len = digits.length; i6 < len; i6++) {
          buf.writeUInt16(digits[i6]);
        }
      }
      decode(buf, ctx) {
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, decodeDecimalToString(buf));
        }
        return decodeDecimalToString(buf);
      }
    };
    exports2.DecimalStringCodec = DecimalStringCodec;
    function decodeBigIntToString(buf) {
      const ndigits = buf.readUInt16();
      const weight = buf.readInt16();
      const sign = buf.readUInt16();
      const dscale = buf.readUInt16();
      let result = "";
      switch (sign) {
        case NUMERIC_POS:
          break;
        case NUMERIC_NEG:
          result += "-";
          break;
        default:
          throw new errors_1.ProtocolError("bad bigint sign data");
      }
      if (dscale !== 0) {
        throw new errors_1.ProtocolError("bigint data has fractional part");
      }
      if (ndigits === 0) {
        return "0";
      }
      let i6 = weight;
      let d5 = 0;
      while (i6 >= 0) {
        if (i6 <= weight && d5 < ndigits) {
          const digit = buf.readUInt16().toString();
          result += d5 > 0 ? digit.padStart(4, "0") : digit;
          d5++;
        } else {
          result += "0000";
        }
        i6--;
      }
      return result;
    }
    function decodeDecimalToString(buf) {
      const ndigits = buf.readUInt16();
      const weight = buf.readInt16();
      const sign = buf.readUInt16();
      const dscale = buf.readUInt16();
      let result = "";
      switch (sign) {
        case NUMERIC_POS:
          break;
        case NUMERIC_NEG:
          result += "-";
          break;
        default:
          throw new errors_1.ProtocolError("bad decimal sign data");
      }
      let d5 = 0;
      if (weight < 0) {
        d5 = weight + 1;
        result += "0";
      } else {
        for (d5 = 0; d5 <= weight; d5++) {
          const digit = d5 < ndigits ? buf.readUInt16() : 0;
          let sdigit = digit.toString();
          if (d5 > 0) {
            sdigit = sdigit.padStart(4, "0");
          }
          result += sdigit;
        }
      }
      if (dscale > 0) {
        result += ".";
        const end = result.length + dscale;
        for (let i6 = 0; i6 < dscale; d5++, i6 += 4) {
          const digit = d5 >= 0 && d5 < ndigits ? buf.readUInt16() : 0;
          result += digit.toString().padStart(4, "0");
        }
        result = result.slice(0, end);
      }
      return result;
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/text.js
var require_text = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/text.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.StrCodec = void 0;
    var buffer_1 = require_buffer();
    var ifaces_1 = require_ifaces();
    var errors_1 = require_errors();
    var StrCodec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "string");
      }
      encode(buf, object, ctx) {
        object = ctx.preEncode(this, object);
        if (typeof object !== "string") {
          throw new errors_1.InvalidArgumentError(`a string was expected, got "${object}"`);
        }
        const val2 = object;
        const strbuf = buffer_1.utf8Encoder.encode(val2);
        buf.writeInt32(strbuf.length);
        buf.writeBuffer(strbuf);
      }
      decode(buf, ctx) {
        return ctx.postDecode(this, buf.consumeAsString());
      }
    };
    exports2.StrCodec = StrCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/uuid.js
var require_uuid = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/uuid.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.UUIDCodec = void 0;
    var buffer_1 = require_buffer();
    var ifaces_1 = require_ifaces();
    var errors_1 = require_errors();
    function UUIDBufferFromString(uuid) {
      let uuidClean = uuid;
      if (uuidClean.length !== 32) {
        uuidClean = uuidClean.replace(/-/g, "");
        if (uuidClean.length !== 32) {
          throw new TypeError(`invalid UUID "${uuid}"`);
        }
      }
      try {
        return (0, buffer_1.uuidToBuffer)(uuidClean);
      } catch {
        throw new TypeError(`invalid UUID "${uuid}"`);
      }
    }
    var UUIDCodec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "string");
      }
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const val2 = ctx.preEncode(this, object);
          if (!(val2 instanceof Uint8Array)) {
            throw new errors_1.InvalidArgumentError(`a Uint8Array was expected from a custom UUID codec`);
          }
          if (val2.length != 16) {
            throw new errors_1.InvalidArgumentError(`a 16-element long Uint8Array was expected from a custom UUID codec`);
          }
          buf.writeInt32(16);
          buf.writeBuffer(val2);
          return;
        }
        if (typeof object === "string") {
          const ubuf = UUIDBufferFromString(object);
          buf.writeInt32(16);
          buf.writeBuffer(ubuf);
        } else {
          throw new errors_1.InvalidArgumentError(`cannot encode UUID "${object}": invalid type`);
        }
      }
      decode(buf, ctx) {
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, buf.readUUIDBytes());
        }
        return buf.readUUID("-");
      }
    };
    exports2.UUIDCodec = UUIDCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/bytes.js
var require_bytes = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/bytes.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BytesCodec = void 0;
    var ifaces_1 = require_ifaces();
    var errors_1 = require_errors();
    var BytesCodec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "Uint8Array");
      }
      encode(buf, object, ctx) {
        const val2 = ctx.preEncode(this, object);
        if (!(val2 instanceof Uint8Array)) {
          throw new errors_1.InvalidArgumentError(`a Uint8Array or Buffer was expected, got "${val2}"`);
        }
        buf.writeInt32(val2.length);
        buf.writeBuffer(val2);
      }
      decode(buf, ctx) {
        return ctx.postDecode(this, buf.consumeAsBuffer());
      }
    };
    exports2.BytesCodec = BytesCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/json.js
var require_json = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/json.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PgTextJSONStringCodec = exports2.PgTextJSONCodec = exports2.JSONCodec = void 0;
    var buffer_1 = require_buffer();
    var ifaces_1 = require_ifaces();
    var errors_1 = require_errors();
    var JSONCodec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "unknown");
        __publicField(this, "jsonFormat", 1);
      }
      encode(buf, object, ctx) {
        let val2;
        if (ctx.hasOverload(this)) {
          val2 = ctx.preEncode(this, object);
        } else {
          try {
            val2 = JSON.stringify(object);
          } catch (_err) {
            throw new errors_1.InvalidArgumentError(`a JSON-serializable value was expected, got "${object}"`);
          }
        }
        if (typeof val2 !== "string") {
          throw new errors_1.InvalidArgumentError(`a JSON-serializable value was expected, got "${object}"`);
        }
        const strbuf = buffer_1.utf8Encoder.encode(val2);
        if (this.jsonFormat !== null) {
          buf.writeInt32(strbuf.length + 1);
          buf.writeChar(this.jsonFormat);
        } else {
          buf.writeInt32(strbuf.length);
        }
        buf.writeBuffer(strbuf);
      }
      decode(buf, ctx) {
        if (this.jsonFormat !== null) {
          const format = buf.readUInt8();
          if (format !== this.jsonFormat) {
            throw new errors_1.ProtocolError(`unexpected JSON format ${format}`);
          }
        }
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, buf.consumeAsString());
        } else {
          return JSON.parse(buf.consumeAsString());
        }
      }
    };
    exports2.JSONCodec = JSONCodec;
    var PgTextJSONCodec = class extends JSONCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "jsonFormat", null);
      }
    };
    exports2.PgTextJSONCodec = PgTextJSONCodec;
    var PgTextJSONStringCodec = class extends ifaces_1.ScalarCodec {
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          object = ctx.preEncode(this, object);
        }
        if (typeof object !== "string") {
          throw new errors_1.InvalidArgumentError(`a string was expected, got "${object}"`);
        }
        const strbuf = buffer_1.utf8Encoder.encode(object);
        buf.writeInt32(strbuf.length);
        buf.writeBuffer(strbuf);
      }
      decode(buf, ctx) {
        return ctx.postDecode(this, buf.consumeAsString());
      }
    };
    exports2.PgTextJSONStringCodec = PgTextJSONStringCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/dateutil.js
var require_dateutil = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/dateutil.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isLeapYear = isLeapYear2;
    exports2.daysInMonth = daysInMonth;
    exports2.daysBeforeMonth = daysBeforeMonth;
    exports2.ymd2ord = ymd2ord;
    exports2.ord2ymd = ord2ymd;
    function isLeapYear2(year) {
      return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
    }
    function daysInMonth(year, month) {
      if (month === 2 && isLeapYear2(year)) {
        return 29;
      }
      return _DAYS_IN_MONTH[month];
    }
    function daysBeforeYear(year) {
      const y2 = year - 1;
      return y2 * 365 + Math.trunc(y2 / 4) - Math.trunc(y2 / 100) + Math.trunc(y2 / 400);
    }
    function daysBeforeMonth(year, month) {
      return _DAYS_BEFORE_MONTH[month] + (month > 2 && isLeapYear2(year) ? 1 : 0);
    }
    var _DI400Y = daysBeforeYear(401);
    var _DI100Y = daysBeforeYear(101);
    var _DI4Y = daysBeforeYear(5);
    var _DAYS_IN_MONTH = [-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    var _DAYS_BEFORE_MONTH = (() => {
      const dbf = [-1];
      let dbm = 0;
      for (let i6 = 1; i6 < _DAYS_IN_MONTH.length; i6++) {
        const dim = _DAYS_IN_MONTH[i6];
        dbf.push(dbm);
        dbm += dim;
      }
      return dbf;
    })();
    function ymd2ord(year, month, day) {
      return daysBeforeYear(year) + daysBeforeMonth(year, month) + day;
    }
    function divmod(dividend, divisor) {
      const quotient = Math.floor(dividend / divisor);
      return [quotient, dividend - divisor * quotient];
    }
    function ord2ymd(n5) {
      n5--;
      let n400;
      [n400, n5] = divmod(n5, _DI400Y);
      let year = n400 * 400 + 1;
      let n100;
      [n100, n5] = divmod(n5, _DI100Y);
      let n42;
      [n42, n5] = divmod(n5, _DI4Y);
      let n1;
      [n1, n5] = divmod(n5, 365);
      year += n100 * 100 + n42 * 4 + n1;
      if (n1 === 4 || n100 === 4) {
        return [year - 1, 12, 31];
      }
      const leapyear = n1 === 3 && (n42 !== 24 || n100 === 3);
      let month = n5 + 50 >> 5;
      let preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 && leapyear ? 1 : 0);
      if (preceding > n5) {
        month -= 1;
        preceding -= _DAYS_IN_MONTH[month] + (month === 2 && leapyear ? 1 : 0);
      }
      n5 -= preceding;
      return [year, month, n5 + 1];
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/datetime.js
var require_datetime = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/datetime.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DateDuration = exports2.RelativeDuration = exports2.Duration = exports2.LocalDateTime = exports2.LocalDate = exports2.localDateInstances = exports2.LocalTime = exports2.localTimeInstances = exports2.DATE_PRIVATE = void 0;
    exports2.LocalDateToOrdinal = LocalDateToOrdinal;
    exports2.LocalDateFromOrdinal = LocalDateFromOrdinal;
    exports2.parseHumanDurationString = parseHumanDurationString;
    var dateutil_1 = require_dateutil();
    exports2.DATE_PRIVATE = Symbol.for("gel.datetime");
    function toNumber(val2) {
      const n5 = Number(val2);
      if (Number.isNaN(n5)) {
        return 0;
      }
      return n5;
    }
    function assertInteger(val2) {
      if (!Number.isInteger(val2)) {
        throw new RangeError(`unsupported fractional value ${val2}`);
      }
      return val2;
    }
    exports2.localTimeInstances = /* @__PURE__ */ new WeakMap();
    var LocalTime = class {
      constructor(isoHour = 0, isoMinute = 0, isoSecond = 0, isoMillisecond = 0, isoMicrosecond = 0, isoNanosecond = 0) {
        __publicField(this, "hour");
        __publicField(this, "minute");
        __publicField(this, "second");
        __publicField(this, "millisecond");
        __publicField(this, "microsecond");
        __publicField(this, "nanosecond");
        isoHour = Math.floor(toNumber(isoHour));
        isoMinute = Math.floor(toNumber(isoMinute));
        isoSecond = Math.floor(toNumber(isoSecond));
        isoMillisecond = Math.floor(toNumber(isoMillisecond));
        isoMicrosecond = Math.floor(toNumber(isoMicrosecond));
        isoNanosecond = Math.floor(toNumber(isoNanosecond));
        if (isoHour < 0 || isoHour > 23) {
          throw new RangeError(`invalid number of hours ${isoHour}: expected a value in 0-23 range`);
        }
        if (isoMinute < 0 || isoMinute > 59) {
          throw new RangeError(`invalid number of minutes ${isoMinute}: expected a value in 0-59 range`);
        }
        if (isoSecond < 0 || isoSecond > 59) {
          throw new RangeError(`invalid number of seconds ${isoSecond}: expected a value in 0-59 range`);
        }
        if (isoMillisecond < 0 || isoMillisecond > 999) {
          throw new RangeError(`invalid number of milliseconds ${isoMillisecond}: expected a value in 0-999 range`);
        }
        if (isoMicrosecond < 0 || isoMicrosecond > 999) {
          throw new RangeError(`invalid number of microseconds ${isoMicrosecond}: expected a value in 0-999 range`);
        }
        if (isoNanosecond < 0 || isoNanosecond > 999) {
          throw new RangeError(`invalid number of nanoseconds ${isoNanosecond}: expected a value in 0-999 range`);
        }
        this.hour = isoHour;
        this.minute = isoMinute;
        this.second = isoSecond;
        this.millisecond = isoMillisecond;
        this.microsecond = isoMicrosecond;
        this.nanosecond = isoNanosecond;
        forwardJsonAsToString(this);
        throwOnValueOf(this, "LocalTime");
      }
      toString() {
        const hh = this.hour.toString().padStart(2, "0");
        const mm = this.minute.toString().padStart(2, "0");
        const ss = this.second.toString().padStart(2, "0");
        let repr = `${hh}:${mm}:${ss}`;
        if (this.millisecond || this.microsecond || this.nanosecond) {
          repr += `.${this.millisecond.toString().padStart(3, "0")}${this.microsecond.toString().padStart(3, "0")}${this.nanosecond.toString().padStart(3, "0")}`.replace(/(?:0+)$/, "");
        }
        return repr;
      }
    };
    exports2.LocalTime = LocalTime;
    exports2.localDateInstances = /* @__PURE__ */ new WeakMap();
    var LocalDate = class {
      constructor(isoYear, isoMonth, isoDay) {
        isoYear = Math.trunc(toNumber(isoYear));
        isoMonth = Math.floor(toNumber(isoMonth));
        isoDay = Math.floor(toNumber(isoDay));
        if (isoYear < -271820 || isoYear > 275759) {
          throw new RangeError(`invalid year ${isoYear}: expected a value in -271820-275759 range`);
        }
        if (isoMonth < 1 || isoMonth > 12) {
          throw new RangeError(`invalid month ${isoMonth}: expected a value in 1-12 range`);
        }
        const maxDays = (0, dateutil_1.daysInMonth)(isoYear, isoMonth);
        if (isoDay < 1 || isoDay > maxDays) {
          throw new RangeError(`invalid number of days ${isoDay}: expected a value in 1-${maxDays} range`);
        }
        const date = new Date(Date.UTC(isoYear, isoMonth - 1, isoDay));
        if (isoYear >= 0 && isoYear <= 99) {
          date.setUTCFullYear(isoYear);
        }
        exports2.localDateInstances.set(this, date);
        forwardJsonAsToString(this);
        throwOnValueOf(this, "LocalDate");
      }
      get year() {
        return exports2.localDateInstances.get(this).getUTCFullYear();
      }
      get month() {
        return exports2.localDateInstances.get(this).getUTCMonth() + 1;
      }
      get day() {
        return exports2.localDateInstances.get(this).getUTCDate();
      }
      get dayOfWeek() {
        return (exports2.localDateInstances.get(this).getUTCDay() + 6) % 7 + 1;
      }
      get dayOfYear() {
        const date = exports2.localDateInstances.get(this);
        return (0, dateutil_1.daysBeforeMonth)(date.getUTCFullYear(), date.getUTCMonth() + 1) + date.getUTCDate();
      }
      get daysInWeek() {
        return 7;
      }
      get daysInMonth() {
        const date = exports2.localDateInstances.get(this);
        return (0, dateutil_1.daysInMonth)(date.getUTCFullYear(), date.getUTCMonth() + 1);
      }
      get daysInYear() {
        return this.inLeapYear ? 366 : 365;
      }
      get monthsInYear() {
        return 12;
      }
      get inLeapYear() {
        return (0, dateutil_1.isLeapYear)(exports2.localDateInstances.get(this).getUTCFullYear());
      }
      toString() {
        const year = this.year < 0 || this.year > 9999 ? (this.year < 0 ? "-" : "+") + Math.abs(this.year).toString().padStart(6, "0") : this.year.toString().padStart(4, "0");
        const month = this.month.toString().padStart(2, "0");
        const day = this.day.toString().padStart(2, "0");
        return `${year}-${month}-${day}`;
      }
    };
    exports2.LocalDate = LocalDate;
    function LocalDateToOrdinal(localdate) {
      return (0, dateutil_1.ymd2ord)(localdate.year, localdate.month, localdate.day);
    }
    function LocalDateFromOrdinal(ordinal) {
      const [year, month, day] = (0, dateutil_1.ord2ymd)(ordinal);
      return new LocalDate(year, month, day);
    }
    var LocalDateTime = class extends LocalDate {
      constructor(isoYear, isoMonth, isoDay, isoHour = 0, isoMinute = 0, isoSecond = 0, isoMillisecond = 0, isoMicrosecond = 0, isoNanosecond = 0) {
        super(isoYear, isoMonth, isoDay);
        const time = new LocalTime(isoHour, isoMinute, isoSecond, isoMillisecond, isoMicrosecond, isoNanosecond);
        exports2.localTimeInstances.set(this, time);
        throwOnValueOf(this, "LocalDateTime");
      }
      get hour() {
        return exports2.localTimeInstances.get(this).hour;
      }
      get minute() {
        return exports2.localTimeInstances.get(this).minute;
      }
      get second() {
        return exports2.localTimeInstances.get(this).second;
      }
      get millisecond() {
        return exports2.localTimeInstances.get(this).millisecond;
      }
      get microsecond() {
        return exports2.localTimeInstances.get(this).microsecond;
      }
      get nanosecond() {
        return exports2.localTimeInstances.get(this).nanosecond;
      }
      toString() {
        return `${super.toString()}T${exports2.localTimeInstances.get(this).toString()}`;
      }
    };
    exports2.LocalDateTime = LocalDateTime;
    var durationRegex2 = new RegExp(`^(\\-|\\+)?P(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)W)?(?:(\\d+)D)?(T(?:(\\d+)(\\.\\d{1,10})?H)?(?:(\\d+)(\\.\\d{1,10})?M)?(?:(\\d+)(\\.\\d{1,9})?S)?)?$`, "i");
    var Duration = class _Duration {
      constructor(years = 0, months = 0, weeks = 0, days = 0, hours = 0, minutes = 0, seconds = 0, milliseconds = 0, microseconds = 0, nanoseconds = 0) {
        __publicField(this, "years");
        __publicField(this, "months");
        __publicField(this, "weeks");
        __publicField(this, "days");
        __publicField(this, "hours");
        __publicField(this, "minutes");
        __publicField(this, "seconds");
        __publicField(this, "milliseconds");
        __publicField(this, "microseconds");
        __publicField(this, "nanoseconds");
        __publicField(this, "sign");
        years = assertInteger(toNumber(years));
        months = assertInteger(toNumber(months));
        weeks = assertInteger(toNumber(weeks));
        days = assertInteger(toNumber(days));
        hours = assertInteger(toNumber(hours));
        minutes = assertInteger(toNumber(minutes));
        seconds = assertInteger(toNumber(seconds));
        milliseconds = assertInteger(toNumber(milliseconds));
        microseconds = assertInteger(toNumber(microseconds));
        nanoseconds = assertInteger(toNumber(nanoseconds));
        const fields = [
          years,
          months,
          weeks,
          days,
          hours,
          minutes,
          seconds,
          milliseconds,
          microseconds,
          nanoseconds
        ];
        let sign = 0;
        for (const field of fields) {
          if (field === Infinity || field === -Infinity) {
            throw new RangeError("infinite values not allowed as duration fields");
          }
          const fieldSign = Math.sign(field);
          if (sign && fieldSign && fieldSign !== sign) {
            throw new RangeError("mixed-sign values not allowed as duration fields");
          }
          sign = sign || fieldSign;
        }
        this.years = years || 0;
        this.months = months || 0;
        this.weeks = weeks || 0;
        this.days = days || 0;
        this.hours = hours || 0;
        this.minutes = minutes || 0;
        this.seconds = seconds || 0;
        this.milliseconds = milliseconds || 0;
        this.microseconds = microseconds || 0;
        this.nanoseconds = nanoseconds || 0;
        this.sign = sign || 0;
        forwardJsonAsToString(this);
        throwOnValueOf(this, "TemporalDuration");
      }
      get blank() {
        return this.sign === 0;
      }
      toString() {
        let dateParts = "";
        if (this.years) {
          dateParts += BigInt(Math.abs(this.years)) + "Y";
        }
        if (this.months) {
          dateParts += BigInt(Math.abs(this.months)) + "M";
        }
        if (this.weeks) {
          dateParts += BigInt(Math.abs(this.weeks)) + "W";
        }
        if (this.days) {
          dateParts += BigInt(Math.abs(this.days)) + "D";
        }
        let timeParts = "";
        if (this.hours) {
          timeParts += BigInt(Math.abs(this.hours)) + "H";
        }
        if (this.minutes) {
          timeParts += BigInt(Math.abs(this.minutes)) + "M";
        }
        if (!dateParts && !timeParts || this.seconds || this.milliseconds || this.microseconds || this.nanoseconds) {
          const totalNanoseconds = (BigInt(Math.abs(this.seconds)) * BigInt(1e9) + BigInt(Math.abs(this.milliseconds)) * BigInt(1e6) + BigInt(Math.abs(this.microseconds)) * BigInt(1e3) + BigInt(Math.abs(this.nanoseconds))).toString().padStart(10, "0");
          const seconds = totalNanoseconds.slice(0, -9);
          const fracSeconds = totalNanoseconds.slice(-9).replace(/0+$/, "");
          timeParts += seconds + (fracSeconds.length ? "." + fracSeconds : "") + "S";
        }
        return (this.sign === -1 ? "-" : "") + "P" + dateParts + (timeParts ? "T" + timeParts : "");
      }
      static from(item) {
        let result;
        if (item instanceof _Duration) {
          result = item;
        }
        if (typeof item === "object") {
          if (item.years === void 0 && item.months === void 0 && item.weeks === void 0 && item.days === void 0 && item.hours === void 0 && item.minutes === void 0 && item.seconds === void 0 && item.milliseconds === void 0 && item.microseconds === void 0 && item.nanoseconds === void 0) {
            throw new TypeError(`invalid duration-like`);
          }
          result = item;
        } else {
          const str = String(item);
          const matches = str.match(durationRegex2);
          if (!matches) {
            throw new RangeError(`invalid duration: ${str}`);
          }
          const [_duration, _sign, years, months, weeks, days, _time, hours, fHours, minutes, fMinutes, seconds, fSeconds] = matches;
          if (_duration.length < 3 || _time.length === 1) {
            throw new RangeError(`invalid duration: ${str}`);
          }
          const sign = _sign === "-" ? -1 : 1;
          result = {};
          if (years) {
            result.years = sign * Number(years);
          }
          if (months) {
            result.months = sign * Number(months);
          }
          if (weeks) {
            result.weeks = sign * Number(weeks);
          }
          if (days) {
            result.days = sign * Number(days);
          }
          if (hours) {
            result.hours = sign * Number(hours);
          }
          if (fHours) {
            if (minutes || fMinutes || seconds || fSeconds) {
              throw new RangeError("only the smallest unit can be fractional");
            }
            result.minutes = Number(fHours) * 60;
          } else {
            result.minutes = toNumber(minutes);
          }
          if (fMinutes) {
            if (seconds || fSeconds) {
              throw new RangeError("only the smallest unit can be fractional");
            }
            result.seconds = Number(fMinutes) * 60;
          } else if (seconds) {
            result.seconds = Number(seconds);
          } else {
            result.seconds = result.minutes % 1 * 60;
          }
          if (fSeconds) {
            const ns = fSeconds.slice(1).padEnd(9, "0");
            result.milliseconds = Number(ns.slice(0, 3));
            result.microseconds = Number(ns.slice(3, 6));
            result.nanoseconds = sign * Number(ns.slice(6));
          } else {
            result.milliseconds = result.seconds % 1 * 1e3;
            result.microseconds = result.milliseconds % 1 * 1e3;
            result.nanoseconds = sign * Math.floor(result.microseconds % 1 * 1e3);
          }
          result.minutes = sign * Math.floor(result.minutes);
          result.seconds = sign * Math.floor(result.seconds);
          result.milliseconds = sign * Math.floor(result.milliseconds);
          result.microseconds = sign * Math.floor(result.microseconds);
        }
        return new _Duration(result.years, result.months, result.weeks, result.days, result.hours, result.minutes, result.seconds, result.milliseconds, result.microseconds, result.nanoseconds);
      }
    };
    exports2.Duration = Duration;
    var RelativeDuration = class {
      constructor(years = 0, months = 0, weeks = 0, days = 0, hours = 0, minutes = 0, seconds = 0, milliseconds = 0, microseconds = 0) {
        __publicField(this, "years");
        __publicField(this, "months");
        __publicField(this, "weeks");
        __publicField(this, "days");
        __publicField(this, "hours");
        __publicField(this, "minutes");
        __publicField(this, "seconds");
        __publicField(this, "milliseconds");
        __publicField(this, "microseconds");
        this.years = Math.trunc(years) || 0;
        this.months = Math.trunc(months) || 0;
        this.weeks = Math.trunc(weeks) || 0;
        this.days = Math.trunc(days) || 0;
        this.hours = Math.trunc(hours) || 0;
        this.minutes = Math.trunc(minutes) || 0;
        this.seconds = Math.trunc(seconds) || 0;
        this.milliseconds = Math.trunc(milliseconds) || 0;
        this.microseconds = Math.trunc(microseconds) || 0;
        forwardJsonAsToString(this);
        throwOnValueOf(this, "RelativeDuration");
      }
      toString() {
        let str = "P";
        if (this.years) {
          str += `${this.years}Y`;
        }
        if (this.months) {
          str += `${this.months}M`;
        }
        const days = this.days + 7 * this.weeks;
        if (days) {
          str += `${days}D`;
        }
        let timeParts = "";
        if (this.hours) {
          timeParts += `${this.hours}H`;
        }
        if (this.minutes) {
          timeParts += `${this.minutes}M`;
        }
        const seconds = this.seconds + this.milliseconds / 1e3 + this.microseconds / 1e6;
        if (seconds !== 0) {
          timeParts += `${seconds}S`;
        }
        if (timeParts) {
          str += `T${timeParts}`;
        }
        if (str === "P") {
          return "PT0S";
        }
        return str;
      }
    };
    exports2.RelativeDuration = RelativeDuration;
    var DateDuration = class {
      constructor(years = 0, months = 0, weeks = 0, days = 0) {
        __publicField(this, "years");
        __publicField(this, "months");
        __publicField(this, "weeks");
        __publicField(this, "days");
        this.years = Math.trunc(years) || 0;
        this.months = Math.trunc(months) || 0;
        this.weeks = Math.trunc(weeks) || 0;
        this.days = Math.trunc(days) || 0;
        forwardJsonAsToString(this);
        throwOnValueOf(this, "DateDuration");
      }
      toString() {
        let str = "P";
        if (this.years) {
          str += `${this.years}Y`;
        }
        if (this.months) {
          str += `${this.months}M`;
        }
        const days = this.days + 7 * this.weeks;
        if (days) {
          str += `${days}D`;
        }
        if (str === "P") {
          return "PT0S";
        }
        return str;
      }
    };
    exports2.DateDuration = DateDuration;
    var humanDurationPrefixes = {
      h: 36e5,
      hou: 36e5,
      m: 6e4,
      min: 6e4,
      s: 1e3,
      sec: 1e3,
      ms: 1,
      mil: 1
    };
    function parseHumanDurationString(durationStr) {
      const regex = /(\d+|\d+\.\d+|\.\d+)\s*(hours?|minutes?|seconds?|milliseconds?|ms|h|m|s)\s*/g;
      let duration = 0;
      const seen = /* @__PURE__ */ new Set();
      let match2 = regex.exec(durationStr);
      let lastIndex = 0;
      while (match2) {
        if (match2.index !== lastIndex) {
          throw new Error(`invalid duration "${durationStr}"`);
        }
        const mult = humanDurationPrefixes[match2[2].slice(0, 3)];
        if (seen.has(mult)) {
          throw new Error(`invalid duration "${durationStr}"`);
        }
        duration += Number(match2[1]) * mult;
        seen.add(mult);
        lastIndex = regex.lastIndex;
        match2 = regex.exec(durationStr);
      }
      if (lastIndex !== durationStr.length) {
        throw new Error(`invalid duration "${durationStr}"`);
      }
      return duration;
    }
    var forwardJsonAsToString = (obj) => {
      Object.defineProperty(obj, "toJSON", {
        value: () => obj.toString(),
        enumerable: false,
        configurable: true
      });
    };
    var throwOnValueOf = (obj, typename) => {
      Object.defineProperty(obj, "valueOf", {
        value: () => {
          throw new TypeError(`Not possible to compare ${typename}`);
        },
        enumerable: false,
        configurable: true
      });
    };
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/datetime.js
var require_datetime2 = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/datetime.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DateDurationCodec = exports2.RelativeDurationCodec = exports2.DurationCodec = exports2.LocalTimeCodec = exports2.LocalDateCodec = exports2.LocalDateTimeCodec = exports2.DateTimeCodec = void 0;
    exports2.checkValidGelDuration = checkValidGelDuration;
    var ifaces_1 = require_ifaces();
    var datetime_1 = require_datetime();
    var dateutil_1 = require_dateutil();
    var errors_1 = require_errors();
    var TIMESHIFT = 9466848e5;
    var BI_TIMESHIFT_US = BigInt(TIMESHIFT) * 1000n;
    var DATESHIFT_ORD = (0, dateutil_1.ymd2ord)(2e3, 1, 1);
    var DateTimeCodec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "Date");
      }
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const val2 = ctx.preEncode(this, object);
          if (typeof val2 != "bigint") {
            throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom std::datetime codec`);
          }
          buf.writeInt32(8);
          buf.writeBigInt64(val2 - BI_TIMESHIFT_US);
          return;
        }
        if (!(object instanceof Date)) {
          throw new errors_1.InvalidArgumentError(`a Date instance was expected, got "${object}"`);
        }
        const ms = object.getTime() - TIMESHIFT;
        const us = ms * 1e3;
        buf.writeInt32(8);
        buf.writeInt64(us);
      }
      decode(buf, ctx) {
        if (ctx.hasOverload(this)) {
          const us2 = buf.readBigInt64();
          return ctx.postDecode(this, us2 + BI_TIMESHIFT_US);
        }
        const us = Number(buf.readBigInt64());
        let ms = Math.round(us / 1e3);
        if (Math.abs(us % 1e3) === 500 && Math.abs(ms) % 2 === 1) {
          ms -= 1;
        }
        ms += TIMESHIFT;
        return new Date(ms);
      }
    };
    exports2.DateTimeCodec = DateTimeCodec;
    var LocalDateTimeCodec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "LocalDateTime");
        __publicField(this, "tsModule", "gel");
      }
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          let us2 = ctx.preEncode(this, object);
          if (typeof us2 != "bigint") {
            throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom cal::local_datetime codec`);
          }
          us2 -= BI_TIMESHIFT_US;
          buf.writeInt32(8);
          buf.writeBigInt64(us2);
          return;
        }
        if (!(object instanceof datetime_1.LocalDateTime)) {
          throw new errors_1.InvalidArgumentError(`a LocalDateTime instance was expected, got "${object}"`);
        }
        const ms = BigInt(datetime_1.localDateInstances.get(object).getTime() - TIMESHIFT);
        let us = ms * 1000n + BigInt(object.hour * 36e8 + object.minute * 6e7 + object.second * 1e6 + object.millisecond * 1e3 + object.microsecond);
        if (object.nanosecond === 500 && Math.abs(object.microsecond) % 2 === 1 || object.nanosecond > 500) {
          us += 1n;
        }
        buf.writeInt32(8);
        buf.writeBigInt64(us);
      }
      decode(buf, ctx) {
        const bi_us = buf.readBigInt64();
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, BigInt(bi_us + BI_TIMESHIFT_US));
        }
        const bi_ms = bi_us / 1000n;
        let us = Number(bi_us - bi_ms * 1000n);
        let ms = Number(bi_ms);
        if (us < 0) {
          us += 1e3;
          ms -= 1;
        }
        ms += TIMESHIFT;
        const date = new Date(ms);
        return new datetime_1.LocalDateTime(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds(), us);
      }
    };
    exports2.LocalDateTimeCodec = LocalDateTimeCodec;
    var LocalDateCodec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "LocalDate");
        __publicField(this, "tsModule", "gel");
      }
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const ret = ctx.preEncode(this, object);
          const ord2 = (0, dateutil_1.ymd2ord)(...ret);
          buf.writeInt32(4);
          buf.writeInt32(ord2 - DATESHIFT_ORD);
          return;
        }
        if (!(object instanceof datetime_1.LocalDate)) {
          throw new errors_1.InvalidArgumentError(`a LocalDate instance was expected, got "${object}"`);
        }
        const ord = (0, datetime_1.LocalDateToOrdinal)(object);
        buf.writeInt32(4);
        buf.writeInt32(ord - DATESHIFT_ORD);
      }
      decode(buf, ctx) {
        const ord = buf.readInt32() + DATESHIFT_ORD;
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, (0, dateutil_1.ord2ymd)(ord));
        }
        return (0, datetime_1.LocalDateFromOrdinal)(ord);
      }
    };
    exports2.LocalDateCodec = LocalDateCodec;
    var LocalTimeCodec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "LocalTime");
        __publicField(this, "tsModule", "gel");
      }
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const us2 = ctx.preEncode(this, object);
          if (typeof us2 != "bigint") {
            throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom cal::local_time codec`);
          }
          buf.writeInt32(8);
          buf.writeBigInt64(us2);
          return;
        }
        if (!(object instanceof datetime_1.LocalTime)) {
          throw new errors_1.InvalidArgumentError(`a LocalTime instance was expected, got "${object}"`);
        }
        let us = object.hour * 36e8 + object.minute * 6e7 + object.second * 1e6 + object.millisecond * 1e3 + object.microsecond;
        if (object.nanosecond === 500 && us % 2 === 1 || object.nanosecond > 500) {
          us += 1;
        }
        buf.writeInt32(8);
        buf.writeInt64(us);
      }
      decode(buf, ctx) {
        const bius = buf.readBigInt64();
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, bius);
        }
        let us = Number(bius);
        let seconds = Math.floor(us / 1e6);
        const ms = Math.floor(us % 1e6 / 1e3);
        us = us % 1e6 - ms * 1e3;
        let minutes = Math.floor(seconds / 60);
        seconds = Math.floor(seconds % 60);
        const hours = Math.floor(minutes / 60);
        minutes = Math.floor(minutes % 60);
        return new datetime_1.LocalTime(hours, minutes, seconds, ms, us);
      }
    };
    exports2.LocalTimeCodec = LocalTimeCodec;
    var unencodableDurationFields = [
      "years",
      "months",
      "weeks",
      "days"
    ];
    function checkValidGelDuration(duration) {
      for (const field of unencodableDurationFields) {
        if (duration[field] !== 0) {
          return field;
        }
      }
      return null;
    }
    var DurationCodec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "Duration");
        __publicField(this, "tsModule", "gel");
      }
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const us2 = ctx.preEncode(this, object);
          if (typeof us2 != "bigint") {
            throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom std::duration codec`);
          }
          buf.writeInt32(16);
          buf.writeBigInt64(us2);
          buf.writeInt32(0);
          buf.writeInt32(0);
          return;
        }
        if (!(object instanceof datetime_1.Duration)) {
          throw new errors_1.InvalidArgumentError(`a Duration instance was expected, got "${object}"`);
        }
        const invalidField = checkValidGelDuration(object);
        if (invalidField) {
          throw new errors_1.InvalidArgumentError(`Cannot encode a 'Duration' with a non-zero number of ${invalidField}`);
        }
        let us = BigInt(Math.abs(object.microseconds));
        us += BigInt(Math.abs(object.milliseconds)) * BigInt(1e3);
        us += BigInt(Math.abs(object.seconds)) * BigInt(1e6);
        us += BigInt(Math.abs(object.minutes)) * BigInt(6e7);
        us += BigInt(Math.abs(object.hours)) * BigInt(36e8);
        if (Math.abs(object.nanoseconds) === 500 && Math.abs(object.microseconds) % 2 === 1 || Math.abs(object.nanoseconds) > 500) {
          us += 1n;
        }
        if (object.sign < 0) {
          us *= -1n;
        }
        buf.writeInt32(16);
        buf.writeBigInt64(us);
        buf.writeInt32(0);
        buf.writeInt32(0);
      }
      decode(buf, ctx) {
        let bius = buf.readBigInt64();
        const days = buf.readInt32();
        const months = buf.readInt32();
        if (days !== 0) {
          throw new errors_1.ProtocolError("non-zero reserved bytes in duration");
        }
        if (months !== 0) {
          throw new errors_1.ProtocolError("non-zero reserved bytes in duration");
        }
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, bius);
        }
        let sign = 1;
        if (Number(bius) < 0) {
          sign = -1;
          bius *= -1n;
        }
        const biMillion = 1000000n;
        const biSeconds = bius / biMillion;
        let us = Number(bius - biSeconds * biMillion);
        const ms = Math.floor(us / 1e3);
        us = us % 1e3;
        let seconds = Number(biSeconds);
        let minutes = Math.floor(seconds / 60);
        seconds = Math.floor(seconds % 60);
        const hours = Math.floor(minutes / 60);
        minutes = Math.floor(minutes % 60);
        return new datetime_1.Duration(0, 0, 0, 0, hours * sign, minutes * sign, seconds * sign, ms * sign, us * sign);
      }
    };
    exports2.DurationCodec = DurationCodec;
    var RelativeDurationCodec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "RelativeDuration");
        __publicField(this, "tsModule", "gel");
      }
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const ret = ctx.preEncode(this, object);
          buf.writeInt32(16);
          buf.writeBigInt64(ret[2]);
          buf.writeInt32(ret[1]);
          buf.writeInt32(ret[0]);
          return;
        }
        if (!(object instanceof datetime_1.RelativeDuration)) {
          throw new errors_1.InvalidArgumentError(`
        a RelativeDuration instance was expected, got "${object}"
      `);
        }
        const us = BigInt(object.microseconds) + BigInt(object.milliseconds) * BigInt(1e3) + BigInt(object.seconds) * BigInt(1e6) + BigInt(object.minutes) * BigInt(6e7) + BigInt(object.hours) * BigInt(36e8);
        buf.writeInt32(16);
        buf.writeBigInt64(us);
        buf.writeInt32(object.days + 7 * object.weeks);
        buf.writeInt32(object.months + 12 * object.years);
      }
      decode(buf, ctx) {
        let bius = buf.readBigInt64();
        let days = buf.readInt32();
        let months = buf.readInt32();
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, [
            months,
            days,
            bius
          ]);
        }
        let sign = 1;
        if (Number(bius) < 0) {
          sign = -1;
          bius *= -1n;
        }
        const million = BigInt(1e6);
        const biSeconds = bius / million;
        let us = Number(bius - biSeconds * million);
        const ms = Math.trunc(us / 1e3);
        us = us % 1e3;
        let seconds = Number(biSeconds);
        let minutes = Math.trunc(seconds / 60);
        seconds = Math.trunc(seconds % 60);
        const hours = Math.trunc(minutes / 60);
        minutes = Math.trunc(minutes % 60);
        const weeks = Math.trunc(days / 7);
        days = Math.trunc(days % 7);
        const years = Math.trunc(months / 12);
        months = Math.trunc(months % 12);
        return new datetime_1.RelativeDuration(years, months, weeks, days, hours * sign, minutes * sign, seconds * sign, ms * sign, us * sign);
      }
    };
    exports2.RelativeDurationCodec = RelativeDurationCodec;
    var DateDurationCodec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "DateDuration");
        __publicField(this, "tsModule", "gel");
      }
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const ret = ctx.preEncode(this, object);
          buf.writeInt32(16);
          buf.writeInt64(0);
          buf.writeInt32(ret[1]);
          buf.writeInt32(ret[0]);
          return;
        }
        if (!(object instanceof datetime_1.DateDuration)) {
          throw new errors_1.InvalidArgumentError(`
        a DateDuration instance was expected, got "${object}"
      `);
        }
        buf.writeInt32(16);
        buf.writeInt64(0);
        buf.writeInt32(object.days + 7 * object.weeks);
        buf.writeInt32(object.months + 12 * object.years);
      }
      decode(buf, ctx) {
        buf.discard(8);
        let days = buf.readInt32();
        let months = buf.readInt32();
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, [months, days]);
        }
        const weeks = Math.trunc(days / 7);
        days = Math.trunc(days % 7);
        const years = Math.trunc(months / 12);
        months = Math.trunc(months % 12);
        return new datetime_1.DateDuration(years, months, weeks, days);
      }
    };
    exports2.DateDurationCodec = DateDurationCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/memory.js
var require_memory = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/memory.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ConfigMemory = void 0;
    var KiB = 1024;
    var MiB = 1024 * KiB;
    var GiB = 1024 * MiB;
    var TiB = 1024 * GiB;
    var PiB = 1024 * TiB;
    var ConfigMemory = class {
      constructor(bytes) {
        __publicField(this, "_bytes");
        this._bytes = bytes;
      }
      get bytes() {
        return Number(this._bytes);
      }
      get bytesBigInt() {
        return this._bytes;
      }
      get kibibytes() {
        return Number(this._bytes) / KiB;
      }
      get mebibytes() {
        return Number(this._bytes) / MiB;
      }
      get gibibytes() {
        return Number(this._bytes) / GiB;
      }
      get tebibytes() {
        return Number(this._bytes) / TiB;
      }
      get pebibytes() {
        return Number(this._bytes) / PiB;
      }
      toString() {
        const bytes = this._bytes;
        const bigPiB = BigInt(PiB);
        if (bytes >= bigPiB && Number(bytes % bigPiB) === 0) {
          return `${bytes / bigPiB}PiB`;
        }
        const bigTiB = BigInt(TiB);
        if (bytes >= bigTiB && Number(bytes % bigTiB) === 0) {
          return `${bytes / bigTiB}TiB`;
        }
        const bigGiB = BigInt(GiB);
        if (bytes >= bigGiB && Number(bytes % bigGiB) === 0) {
          return `${bytes / bigGiB}GiB`;
        }
        const bigMiB = BigInt(MiB);
        if (bytes >= bigMiB && Number(bytes % bigMiB) === 0) {
          return `${bytes / bigMiB}MiB`;
        }
        const bigKiB = BigInt(KiB);
        if (bytes >= bigKiB && Number(bytes % bigKiB) === 0) {
          return `${bytes / bigKiB}KiB`;
        }
        return `${bytes}B`;
      }
    };
    exports2.ConfigMemory = ConfigMemory;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/memory.js
var require_memory2 = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/memory.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ConfigMemoryCodec = void 0;
    var ifaces_1 = require_ifaces();
    var memory_1 = require_memory();
    var errors_1 = require_errors();
    var ConfigMemoryCodec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "ConfigMemory");
        __publicField(this, "tsModule", "gel");
      }
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const val2 = ctx.preEncode(this, object);
          if (typeof val2 != "bigint") {
            throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom cfg::memory codec`);
          }
          buf.writeInt32(8);
          buf.writeBigInt64(val2);
          return;
        }
        if (!(object instanceof memory_1.ConfigMemory)) {
          throw new errors_1.InvalidArgumentError(`a ConfigMemory instance was expected, got "${object}"`);
        }
        buf.writeInt32(8);
        buf.writeBigInt64(object._bytes);
      }
      decode(buf, ctx) {
        const val2 = buf.readBigInt64();
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, val2);
        }
        return new memory_1.ConfigMemory(val2);
      }
    };
    exports2.ConfigMemoryCodec = ConfigMemoryCodec;
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/messages.cjs
var require_messages = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/messages.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    var THIS_IS_NOT_AN_OBJECT = exports2.THIS_IS_NOT_AN_OBJECT = "This is not an object";
    var THIS_IS_NOT_A_FLOAT16ARRAY_OBJECT = exports2.THIS_IS_NOT_A_FLOAT16ARRAY_OBJECT = "This is not a Float16Array object";
    var THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY = exports2.THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY = "This constructor is not a subclass of Float16Array";
    var THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT = exports2.THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT = "The constructor property value is not an object";
    var SPECIES_CONSTRUCTOR_DIDNT_RETURN_TYPEDARRAY_OBJECT = exports2.SPECIES_CONSTRUCTOR_DIDNT_RETURN_TYPEDARRAY_OBJECT = "Species constructor didn't return TypedArray object";
    var DERIVED_CONSTRUCTOR_CREATED_TYPEDARRAY_OBJECT_WHICH_WAS_TOO_SMALL_LENGTH = exports2.DERIVED_CONSTRUCTOR_CREATED_TYPEDARRAY_OBJECT_WHICH_WAS_TOO_SMALL_LENGTH = "Derived constructor created TypedArray object which was too small length";
    var ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER = exports2.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER = "Attempting to access detached ArrayBuffer";
    var CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT = exports2.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT = "Cannot convert undefined or null to object";
    var CANNOT_MIX_BIGINT_AND_OTHER_TYPES = exports2.CANNOT_MIX_BIGINT_AND_OTHER_TYPES = "Cannot mix BigInt and other types, use explicit conversions";
    var ITERATOR_PROPERTY_IS_NOT_CALLABLE = exports2.ITERATOR_PROPERTY_IS_NOT_CALLABLE = "@@iterator property is not callable";
    var REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE = exports2.REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE = "Reduce of empty array with no initial value";
    var THE_COMPARISON_FUNCTION_MUST_BE_EITHER_A_FUNCTION_OR_UNDEFINED = exports2.THE_COMPARISON_FUNCTION_MUST_BE_EITHER_A_FUNCTION_OR_UNDEFINED = "The comparison function must be either a function or undefined";
    var OFFSET_IS_OUT_OF_BOUNDS = exports2.OFFSET_IS_OUT_OF_BOUNDS = "Offset is out of bounds";
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/primordials.cjs
var require_primordials = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/primordials.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    var _messages = require_messages();
    function uncurryThis(target) {
      return (thisArg, ...args) => {
        return ReflectApply(target, thisArg, args);
      };
    }
    function uncurryThisGetter(target, key) {
      return uncurryThis(ReflectGetOwnPropertyDescriptor(target, key).get);
    }
    var {
      apply: ReflectApply,
      construct: ReflectConstruct,
      defineProperty: ReflectDefineProperty,
      get: ReflectGet,
      getOwnPropertyDescriptor: ReflectGetOwnPropertyDescriptor,
      getPrototypeOf: ReflectGetPrototypeOf,
      has: ReflectHas,
      ownKeys: ReflectOwnKeys,
      set: ReflectSet,
      setPrototypeOf: ReflectSetPrototypeOf
    } = Reflect;
    exports2.ReflectSetPrototypeOf = ReflectSetPrototypeOf;
    exports2.ReflectSet = ReflectSet;
    exports2.ReflectOwnKeys = ReflectOwnKeys;
    exports2.ReflectHas = ReflectHas;
    exports2.ReflectGetPrototypeOf = ReflectGetPrototypeOf;
    exports2.ReflectGetOwnPropertyDescriptor = ReflectGetOwnPropertyDescriptor;
    exports2.ReflectGet = ReflectGet;
    exports2.ReflectDefineProperty = ReflectDefineProperty;
    exports2.ReflectConstruct = ReflectConstruct;
    exports2.ReflectApply = ReflectApply;
    var NativeProxy = exports2.NativeProxy = Proxy;
    var {
      EPSILON,
      MAX_SAFE_INTEGER,
      isFinite: NumberIsFinite,
      isNaN: NumberIsNaN
    } = Number;
    exports2.NumberIsNaN = NumberIsNaN;
    exports2.NumberIsFinite = NumberIsFinite;
    exports2.MAX_SAFE_INTEGER = MAX_SAFE_INTEGER;
    exports2.EPSILON = EPSILON;
    var {
      iterator: SymbolIterator,
      species: SymbolSpecies,
      toStringTag: SymbolToStringTag,
      for: SymbolFor
    } = Symbol;
    exports2.SymbolFor = SymbolFor;
    exports2.SymbolToStringTag = SymbolToStringTag;
    exports2.SymbolSpecies = SymbolSpecies;
    exports2.SymbolIterator = SymbolIterator;
    var NativeObject = exports2.NativeObject = Object;
    var {
      create: ObjectCreate,
      defineProperty: ObjectDefineProperty,
      freeze: ObjectFreeze,
      is: ObjectIs
    } = NativeObject;
    exports2.ObjectIs = ObjectIs;
    exports2.ObjectFreeze = ObjectFreeze;
    exports2.ObjectDefineProperty = ObjectDefineProperty;
    exports2.ObjectCreate = ObjectCreate;
    var ObjectPrototype = NativeObject.prototype;
    var ObjectPrototype__lookupGetter__ = exports2.ObjectPrototype__lookupGetter__ = ObjectPrototype.__lookupGetter__ ? uncurryThis(ObjectPrototype.__lookupGetter__) : (object, key) => {
      if (object == null) {
        throw NativeTypeError(_messages.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT);
      }
      let target = NativeObject(object);
      do {
        const descriptor = ReflectGetOwnPropertyDescriptor(target, key);
        if (descriptor !== void 0) {
          if (ObjectHasOwn(descriptor, "get")) {
            return descriptor.get;
          }
          return;
        }
      } while ((target = ReflectGetPrototypeOf(target)) !== null);
    };
    var ObjectHasOwn = exports2.ObjectHasOwn = NativeObject.hasOwn || uncurryThis(ObjectPrototype.hasOwnProperty);
    var NativeArray = Array;
    var ArrayIsArray = exports2.ArrayIsArray = NativeArray.isArray;
    var ArrayPrototype = NativeArray.prototype;
    var ArrayPrototypeJoin = exports2.ArrayPrototypeJoin = uncurryThis(ArrayPrototype.join);
    var ArrayPrototypePush = exports2.ArrayPrototypePush = uncurryThis(ArrayPrototype.push);
    var ArrayPrototypeToLocaleString = exports2.ArrayPrototypeToLocaleString = uncurryThis(ArrayPrototype.toLocaleString);
    var NativeArrayPrototypeSymbolIterator = exports2.NativeArrayPrototypeSymbolIterator = ArrayPrototype[SymbolIterator];
    var ArrayPrototypeSymbolIterator = exports2.ArrayPrototypeSymbolIterator = uncurryThis(NativeArrayPrototypeSymbolIterator);
    var {
      abs: MathAbs,
      trunc: MathTrunc
    } = Math;
    exports2.MathTrunc = MathTrunc;
    exports2.MathAbs = MathAbs;
    var NativeArrayBuffer = exports2.NativeArrayBuffer = ArrayBuffer;
    var ArrayBufferIsView = exports2.ArrayBufferIsView = NativeArrayBuffer.isView;
    var ArrayBufferPrototype = NativeArrayBuffer.prototype;
    var ArrayBufferPrototypeSlice = exports2.ArrayBufferPrototypeSlice = uncurryThis(ArrayBufferPrototype.slice);
    var ArrayBufferPrototypeGetByteLength = exports2.ArrayBufferPrototypeGetByteLength = uncurryThisGetter(ArrayBufferPrototype, "byteLength");
    var NativeSharedArrayBuffer = exports2.NativeSharedArrayBuffer = typeof SharedArrayBuffer !== "undefined" ? SharedArrayBuffer : null;
    var SharedArrayBufferPrototypeGetByteLength = exports2.SharedArrayBufferPrototypeGetByteLength = NativeSharedArrayBuffer && uncurryThisGetter(NativeSharedArrayBuffer.prototype, "byteLength");
    var TypedArray = exports2.TypedArray = ReflectGetPrototypeOf(Uint8Array);
    var TypedArrayFrom = TypedArray.from;
    var TypedArrayPrototype = exports2.TypedArrayPrototype = TypedArray.prototype;
    var NativeTypedArrayPrototypeSymbolIterator = exports2.NativeTypedArrayPrototypeSymbolIterator = TypedArrayPrototype[SymbolIterator];
    var TypedArrayPrototypeKeys = exports2.TypedArrayPrototypeKeys = uncurryThis(TypedArrayPrototype.keys);
    var TypedArrayPrototypeValues = exports2.TypedArrayPrototypeValues = uncurryThis(TypedArrayPrototype.values);
    var TypedArrayPrototypeEntries = exports2.TypedArrayPrototypeEntries = uncurryThis(TypedArrayPrototype.entries);
    var TypedArrayPrototypeSet = exports2.TypedArrayPrototypeSet = uncurryThis(TypedArrayPrototype.set);
    var TypedArrayPrototypeReverse = exports2.TypedArrayPrototypeReverse = uncurryThis(TypedArrayPrototype.reverse);
    var TypedArrayPrototypeFill = exports2.TypedArrayPrototypeFill = uncurryThis(TypedArrayPrototype.fill);
    var TypedArrayPrototypeCopyWithin = exports2.TypedArrayPrototypeCopyWithin = uncurryThis(TypedArrayPrototype.copyWithin);
    var TypedArrayPrototypeSort = exports2.TypedArrayPrototypeSort = uncurryThis(TypedArrayPrototype.sort);
    var TypedArrayPrototypeSlice = exports2.TypedArrayPrototypeSlice = uncurryThis(TypedArrayPrototype.slice);
    var TypedArrayPrototypeSubarray = exports2.TypedArrayPrototypeSubarray = uncurryThis(TypedArrayPrototype.subarray);
    var TypedArrayPrototypeGetBuffer = exports2.TypedArrayPrototypeGetBuffer = uncurryThisGetter(TypedArrayPrototype, "buffer");
    var TypedArrayPrototypeGetByteOffset = exports2.TypedArrayPrototypeGetByteOffset = uncurryThisGetter(TypedArrayPrototype, "byteOffset");
    var TypedArrayPrototypeGetLength = exports2.TypedArrayPrototypeGetLength = uncurryThisGetter(TypedArrayPrototype, "length");
    var TypedArrayPrototypeGetSymbolToStringTag = exports2.TypedArrayPrototypeGetSymbolToStringTag = uncurryThisGetter(TypedArrayPrototype, SymbolToStringTag);
    var NativeUint8Array = exports2.NativeUint8Array = Uint8Array;
    var NativeUint16Array = exports2.NativeUint16Array = Uint16Array;
    var Uint16ArrayFrom = (...args) => {
      return ReflectApply(TypedArrayFrom, NativeUint16Array, args);
    };
    exports2.Uint16ArrayFrom = Uint16ArrayFrom;
    var NativeUint32Array = exports2.NativeUint32Array = Uint32Array;
    var NativeFloat32Array = exports2.NativeFloat32Array = Float32Array;
    var ArrayIteratorPrototype = exports2.ArrayIteratorPrototype = ReflectGetPrototypeOf([][SymbolIterator]());
    var ArrayIteratorPrototypeNext = exports2.ArrayIteratorPrototypeNext = uncurryThis(ArrayIteratorPrototype.next);
    var GeneratorPrototypeNext = exports2.GeneratorPrototypeNext = uncurryThis(function* () {
    }().next);
    var IteratorPrototype = exports2.IteratorPrototype = ReflectGetPrototypeOf(ArrayIteratorPrototype);
    var DataViewPrototype = DataView.prototype;
    var DataViewPrototypeGetUint16 = exports2.DataViewPrototypeGetUint16 = uncurryThis(DataViewPrototype.getUint16);
    var DataViewPrototypeSetUint16 = exports2.DataViewPrototypeSetUint16 = uncurryThis(DataViewPrototype.setUint16);
    var NativeTypeError = exports2.NativeTypeError = TypeError;
    var NativeRangeError = exports2.NativeRangeError = RangeError;
    var NativeWeakSet = exports2.NativeWeakSet = WeakSet;
    var WeakSetPrototype = NativeWeakSet.prototype;
    var WeakSetPrototypeAdd = exports2.WeakSetPrototypeAdd = uncurryThis(WeakSetPrototype.add);
    var WeakSetPrototypeHas = exports2.WeakSetPrototypeHas = uncurryThis(WeakSetPrototype.has);
    var NativeWeakMap = exports2.NativeWeakMap = WeakMap;
    var WeakMapPrototype = NativeWeakMap.prototype;
    var WeakMapPrototypeGet = exports2.WeakMapPrototypeGet = uncurryThis(WeakMapPrototype.get);
    var WeakMapPrototypeHas = exports2.WeakMapPrototypeHas = uncurryThis(WeakMapPrototype.has);
    var WeakMapPrototypeSet = exports2.WeakMapPrototypeSet = uncurryThis(WeakMapPrototype.set);
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/arrayIterator.cjs
var require_arrayIterator = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/arrayIterator.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.safeIfNeeded = safeIfNeeded;
    exports2.wrap = wrap;
    var _primordials = require_primordials();
    var arrayIterators = new _primordials.NativeWeakMap();
    var SafeIteratorPrototype = (0, _primordials.ObjectCreate)(null, {
      next: {
        value: function next() {
          const arrayIterator = (0, _primordials.WeakMapPrototypeGet)(arrayIterators, this);
          return (0, _primordials.ArrayIteratorPrototypeNext)(arrayIterator);
        }
      },
      [_primordials.SymbolIterator]: {
        value: function values() {
          return this;
        }
      }
    });
    function safeIfNeeded(array2) {
      if (array2[_primordials.SymbolIterator] === _primordials.NativeArrayPrototypeSymbolIterator && _primordials.ArrayIteratorPrototype.next === _primordials.ArrayIteratorPrototypeNext) {
        return array2;
      }
      const safe = (0, _primordials.ObjectCreate)(SafeIteratorPrototype);
      (0, _primordials.WeakMapPrototypeSet)(arrayIterators, safe, (0, _primordials.ArrayPrototypeSymbolIterator)(array2));
      return safe;
    }
    var generators = new _primordials.NativeWeakMap();
    var DummyArrayIteratorPrototype = (0, _primordials.ObjectCreate)(_primordials.IteratorPrototype, {
      next: {
        value: function next() {
          const generator = (0, _primordials.WeakMapPrototypeGet)(generators, this);
          return (0, _primordials.GeneratorPrototypeNext)(generator);
        },
        writable: true,
        configurable: true
      }
    });
    for (const key of (0, _primordials.ReflectOwnKeys)(_primordials.ArrayIteratorPrototype)) {
      if (key === "next") {
        continue;
      }
      (0, _primordials.ObjectDefineProperty)(DummyArrayIteratorPrototype, key, (0, _primordials.ReflectGetOwnPropertyDescriptor)(_primordials.ArrayIteratorPrototype, key));
    }
    function wrap(generator) {
      const dummy = (0, _primordials.ObjectCreate)(DummyArrayIteratorPrototype);
      (0, _primordials.WeakMapPrototypeSet)(generators, dummy, generator);
      return dummy;
    }
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/is.cjs
var require_is = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/is.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.isAnyArrayBuffer = isAnyArrayBuffer;
    exports2.isCanonicalIntegerIndexString = isCanonicalIntegerIndexString;
    exports2.isNativeBigIntTypedArray = isNativeBigIntTypedArray;
    exports2.isNativeTypedArray = isNativeTypedArray;
    exports2.isObject = isObject;
    exports2.isObjectLike = isObjectLike;
    exports2.isOrdinaryArray = isOrdinaryArray;
    exports2.isOrdinaryNativeTypedArray = isOrdinaryNativeTypedArray;
    exports2.isSharedArrayBuffer = isSharedArrayBuffer;
    var _primordials = require_primordials();
    function isObject(value) {
      return value !== null && typeof value === "object" || typeof value === "function";
    }
    function isObjectLike(value) {
      return value !== null && typeof value === "object";
    }
    function isNativeTypedArray(value) {
      return (0, _primordials.TypedArrayPrototypeGetSymbolToStringTag)(value) !== void 0;
    }
    function isNativeBigIntTypedArray(value) {
      const typedArrayName = (0, _primordials.TypedArrayPrototypeGetSymbolToStringTag)(value);
      return typedArrayName === "BigInt64Array" || typedArrayName === "BigUint64Array";
    }
    function isArrayBuffer2(value) {
      try {
        if ((0, _primordials.ArrayIsArray)(value)) {
          return false;
        }
        (0, _primordials.ArrayBufferPrototypeGetByteLength)(value);
        return true;
      } catch (e6) {
        return false;
      }
    }
    function isSharedArrayBuffer(value) {
      if (_primordials.NativeSharedArrayBuffer === null) {
        return false;
      }
      try {
        (0, _primordials.SharedArrayBufferPrototypeGetByteLength)(value);
        return true;
      } catch (e6) {
        return false;
      }
    }
    function isAnyArrayBuffer(value) {
      return isArrayBuffer2(value) || isSharedArrayBuffer(value);
    }
    function isOrdinaryArray(value) {
      if (!(0, _primordials.ArrayIsArray)(value)) {
        return false;
      }
      return value[_primordials.SymbolIterator] === _primordials.NativeArrayPrototypeSymbolIterator && _primordials.ArrayIteratorPrototype.next === _primordials.ArrayIteratorPrototypeNext;
    }
    function isOrdinaryNativeTypedArray(value) {
      if (!isNativeTypedArray(value)) {
        return false;
      }
      return value[_primordials.SymbolIterator] === _primordials.NativeTypedArrayPrototypeSymbolIterator && _primordials.ArrayIteratorPrototype.next === _primordials.ArrayIteratorPrototypeNext;
    }
    function isCanonicalIntegerIndexString(value) {
      if (typeof value !== "string") {
        return false;
      }
      const number = +value;
      if (value !== number + "") {
        return false;
      }
      if (!(0, _primordials.NumberIsFinite)(number)) {
        return false;
      }
      return number === (0, _primordials.MathTrunc)(number);
    }
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/brand.cjs
var require_brand = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/brand.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.hasFloat16ArrayBrand = hasFloat16ArrayBrand;
    var _is = require_is();
    var _messages = require_messages();
    var _primordials = require_primordials();
    var brand = exports2.brand = (0, _primordials.SymbolFor)("__Float16Array__");
    function hasFloat16ArrayBrand(target) {
      if (!(0, _is.isObjectLike)(target)) {
        return false;
      }
      const prototype = (0, _primordials.ReflectGetPrototypeOf)(target);
      if (!(0, _is.isObjectLike)(prototype)) {
        return false;
      }
      const constructor = prototype.constructor;
      if (constructor === void 0) {
        return false;
      }
      if (!(0, _is.isObject)(constructor)) {
        throw (0, _primordials.NativeTypeError)(_messages.THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT);
      }
      return (0, _primordials.ReflectHas)(constructor, brand);
    }
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/converter.cjs
var require_converter = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/converter.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.convertToNumber = convertToNumber;
    exports2.roundToFloat16 = roundToFloat16;
    exports2.roundToFloat16Bits = roundToFloat16Bits;
    var _primordials = require_primordials();
    var INVERSE_OF_EPSILON = 1 / _primordials.EPSILON;
    function roundTiesToEven(num) {
      return num + INVERSE_OF_EPSILON - INVERSE_OF_EPSILON;
    }
    var FLOAT16_MIN_VALUE = 6103515625e-14;
    var FLOAT16_MAX_VALUE = 65504;
    var FLOAT16_EPSILON = 9765625e-10;
    var FLOAT16_EPSILON_MULTIPLIED_BY_FLOAT16_MIN_VALUE = FLOAT16_EPSILON * FLOAT16_MIN_VALUE;
    var FLOAT16_EPSILON_DEVIDED_BY_EPSILON = FLOAT16_EPSILON * INVERSE_OF_EPSILON;
    function roundToFloat16(num) {
      const number = +num;
      if (!(0, _primordials.NumberIsFinite)(number) || number === 0) {
        return number;
      }
      const sign = number > 0 ? 1 : -1;
      const absolute = (0, _primordials.MathAbs)(number);
      if (absolute < FLOAT16_MIN_VALUE) {
        return sign * roundTiesToEven(absolute / FLOAT16_EPSILON_MULTIPLIED_BY_FLOAT16_MIN_VALUE) * FLOAT16_EPSILON_MULTIPLIED_BY_FLOAT16_MIN_VALUE;
      }
      const temp = (1 + FLOAT16_EPSILON_DEVIDED_BY_EPSILON) * absolute;
      const result = temp - (temp - absolute);
      if (result > FLOAT16_MAX_VALUE || (0, _primordials.NumberIsNaN)(result)) {
        return sign * Infinity;
      }
      return sign * result;
    }
    var buffer = new _primordials.NativeArrayBuffer(4);
    var floatView = new _primordials.NativeFloat32Array(buffer);
    var uint32View = new _primordials.NativeUint32Array(buffer);
    var baseTable = new _primordials.NativeUint16Array(512);
    var shiftTable = new _primordials.NativeUint8Array(512);
    for (let i6 = 0; i6 < 256; ++i6) {
      const e6 = i6 - 127;
      if (e6 < -24) {
        baseTable[i6] = 0;
        baseTable[i6 | 256] = 32768;
        shiftTable[i6] = 24;
        shiftTable[i6 | 256] = 24;
      } else if (e6 < -14) {
        baseTable[i6] = 1024 >> -e6 - 14;
        baseTable[i6 | 256] = 1024 >> -e6 - 14 | 32768;
        shiftTable[i6] = -e6 - 1;
        shiftTable[i6 | 256] = -e6 - 1;
      } else if (e6 <= 15) {
        baseTable[i6] = e6 + 15 << 10;
        baseTable[i6 | 256] = e6 + 15 << 10 | 32768;
        shiftTable[i6] = 13;
        shiftTable[i6 | 256] = 13;
      } else if (e6 < 128) {
        baseTable[i6] = 31744;
        baseTable[i6 | 256] = 64512;
        shiftTable[i6] = 24;
        shiftTable[i6 | 256] = 24;
      } else {
        baseTable[i6] = 31744;
        baseTable[i6 | 256] = 64512;
        shiftTable[i6] = 13;
        shiftTable[i6 | 256] = 13;
      }
    }
    function roundToFloat16Bits(num) {
      floatView[0] = roundToFloat16(num);
      const f7 = uint32View[0];
      const e6 = f7 >> 23 & 511;
      return baseTable[e6] + ((f7 & 8388607) >> shiftTable[e6]);
    }
    var mantissaTable = new _primordials.NativeUint32Array(2048);
    for (let i6 = 1; i6 < 1024; ++i6) {
      let m6 = i6 << 13;
      let e6 = 0;
      while ((m6 & 8388608) === 0) {
        m6 <<= 1;
        e6 -= 8388608;
      }
      m6 &= ~8388608;
      e6 += 947912704;
      mantissaTable[i6] = m6 | e6;
    }
    for (let i6 = 1024; i6 < 2048; ++i6) {
      mantissaTable[i6] = 939524096 + (i6 - 1024 << 13);
    }
    var exponentTable = new _primordials.NativeUint32Array(64);
    for (let i6 = 1; i6 < 31; ++i6) {
      exponentTable[i6] = i6 << 23;
    }
    exponentTable[31] = 1199570944;
    exponentTable[32] = 2147483648;
    for (let i6 = 33; i6 < 63; ++i6) {
      exponentTable[i6] = 2147483648 + (i6 - 32 << 23);
    }
    exponentTable[63] = 3347054592;
    var offsetTable = new _primordials.NativeUint16Array(64);
    for (let i6 = 1; i6 < 64; ++i6) {
      if (i6 !== 32) {
        offsetTable[i6] = 1024;
      }
    }
    function convertToNumber(float16bits) {
      const i6 = float16bits >> 10;
      uint32View[0] = mantissaTable[offsetTable[i6] + (float16bits & 1023)] + exponentTable[i6];
      return floatView[0];
    }
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/spec.cjs
var require_spec = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/spec.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.IsDetachedBuffer = IsDetachedBuffer;
    exports2.SpeciesConstructor = SpeciesConstructor;
    exports2.ToIntegerOrInfinity = ToIntegerOrInfinity;
    exports2.ToLength = ToLength;
    exports2.defaultCompare = defaultCompare;
    var _is = require_is();
    var _messages = require_messages();
    var _primordials = require_primordials();
    function ToIntegerOrInfinity(target) {
      const number = +target;
      if ((0, _primordials.NumberIsNaN)(number) || number === 0) {
        return 0;
      }
      return (0, _primordials.MathTrunc)(number);
    }
    function ToLength(target) {
      const length = ToIntegerOrInfinity(target);
      if (length < 0) {
        return 0;
      }
      return length < _primordials.MAX_SAFE_INTEGER ? length : _primordials.MAX_SAFE_INTEGER;
    }
    function SpeciesConstructor(target, defaultConstructor) {
      if (!(0, _is.isObject)(target)) {
        throw (0, _primordials.NativeTypeError)(_messages.THIS_IS_NOT_AN_OBJECT);
      }
      const constructor = target.constructor;
      if (constructor === void 0) {
        return defaultConstructor;
      }
      if (!(0, _is.isObject)(constructor)) {
        throw (0, _primordials.NativeTypeError)(_messages.THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT);
      }
      const species = constructor[_primordials.SymbolSpecies];
      if (species == null) {
        return defaultConstructor;
      }
      return species;
    }
    function IsDetachedBuffer(buffer) {
      if ((0, _is.isSharedArrayBuffer)(buffer)) {
        return false;
      }
      try {
        (0, _primordials.ArrayBufferPrototypeSlice)(buffer, 0, 0);
        return false;
      } catch (e6) {
      }
      return true;
    }
    function defaultCompare(x5, y2) {
      const isXNaN = (0, _primordials.NumberIsNaN)(x5);
      const isYNaN = (0, _primordials.NumberIsNaN)(y2);
      if (isXNaN && isYNaN) {
        return 0;
      }
      if (isXNaN) {
        return 1;
      }
      if (isYNaN) {
        return -1;
      }
      if (x5 < y2) {
        return -1;
      }
      if (x5 > y2) {
        return 1;
      }
      if (x5 === 0 && y2 === 0) {
        const isXPlusZero = (0, _primordials.ObjectIs)(x5, 0);
        const isYPlusZero = (0, _primordials.ObjectIs)(y2, 0);
        if (!isXPlusZero && isYPlusZero) {
          return -1;
        }
        if (isXPlusZero && !isYPlusZero) {
          return 1;
        }
      }
      return 0;
    }
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/Float16Array.cjs
var require_Float16Array = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/Float16Array.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.isFloat16Array = isFloat16Array;
    var _arrayIterator = require_arrayIterator();
    var _brand = require_brand();
    var _converter = require_converter();
    var _is = require_is();
    var _messages = require_messages();
    var _primordials = require_primordials();
    var _spec = require_spec();
    var BYTES_PER_ELEMENT = 2;
    var float16bitsArrays = new _primordials.NativeWeakMap();
    function isFloat16Array(target) {
      return (0, _primordials.WeakMapPrototypeHas)(float16bitsArrays, target) || !(0, _primordials.ArrayBufferIsView)(target) && (0, _brand.hasFloat16ArrayBrand)(target);
    }
    function assertFloat16Array(target) {
      if (!isFloat16Array(target)) {
        throw (0, _primordials.NativeTypeError)(_messages.THIS_IS_NOT_A_FLOAT16ARRAY_OBJECT);
      }
    }
    function assertSpeciesTypedArray(target, count) {
      const isTargetFloat16Array = isFloat16Array(target);
      const isTargetTypedArray = (0, _is.isNativeTypedArray)(target);
      if (!isTargetFloat16Array && !isTargetTypedArray) {
        throw (0, _primordials.NativeTypeError)(_messages.SPECIES_CONSTRUCTOR_DIDNT_RETURN_TYPEDARRAY_OBJECT);
      }
      if (typeof count === "number") {
        let length;
        if (isTargetFloat16Array) {
          const float16bitsArray = getFloat16BitsArray(target);
          length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        } else {
          length = (0, _primordials.TypedArrayPrototypeGetLength)(target);
        }
        if (length < count) {
          throw (0, _primordials.NativeTypeError)(_messages.DERIVED_CONSTRUCTOR_CREATED_TYPEDARRAY_OBJECT_WHICH_WAS_TOO_SMALL_LENGTH);
        }
      }
      if ((0, _is.isNativeBigIntTypedArray)(target)) {
        throw (0, _primordials.NativeTypeError)(_messages.CANNOT_MIX_BIGINT_AND_OTHER_TYPES);
      }
    }
    function getFloat16BitsArray(float16) {
      const float16bitsArray = (0, _primordials.WeakMapPrototypeGet)(float16bitsArrays, float16);
      if (float16bitsArray !== void 0) {
        const buffer2 = (0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray);
        if ((0, _spec.IsDetachedBuffer)(buffer2)) {
          throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
        }
        return float16bitsArray;
      }
      const buffer = float16.buffer;
      if ((0, _spec.IsDetachedBuffer)(buffer)) {
        throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
      }
      const cloned = (0, _primordials.ReflectConstruct)(Float16Array, [buffer, float16.byteOffset, float16.length], float16.constructor);
      return (0, _primordials.WeakMapPrototypeGet)(float16bitsArrays, cloned);
    }
    function copyToArray(float16bitsArray) {
      const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
      const array2 = [];
      for (let i6 = 0; i6 < length; ++i6) {
        array2[i6] = (0, _converter.convertToNumber)(float16bitsArray[i6]);
      }
      return array2;
    }
    var TypedArrayPrototypeGetters = new _primordials.NativeWeakSet();
    for (const key of (0, _primordials.ReflectOwnKeys)(_primordials.TypedArrayPrototype)) {
      if (key === _primordials.SymbolToStringTag) {
        continue;
      }
      const descriptor = (0, _primordials.ReflectGetOwnPropertyDescriptor)(_primordials.TypedArrayPrototype, key);
      if ((0, _primordials.ObjectHasOwn)(descriptor, "get") && typeof descriptor.get === "function") {
        (0, _primordials.WeakSetPrototypeAdd)(TypedArrayPrototypeGetters, descriptor.get);
      }
    }
    var handler = (0, _primordials.ObjectFreeze)({
      get(target, key, receiver) {
        if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key)) {
          return (0, _converter.convertToNumber)((0, _primordials.ReflectGet)(target, key));
        }
        if ((0, _primordials.WeakSetPrototypeHas)(TypedArrayPrototypeGetters, (0, _primordials.ObjectPrototype__lookupGetter__)(target, key))) {
          return (0, _primordials.ReflectGet)(target, key);
        }
        return (0, _primordials.ReflectGet)(target, key, receiver);
      },
      set(target, key, value, receiver) {
        if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key)) {
          return (0, _primordials.ReflectSet)(target, key, (0, _converter.roundToFloat16Bits)(value));
        }
        return (0, _primordials.ReflectSet)(target, key, value, receiver);
      },
      getOwnPropertyDescriptor(target, key) {
        if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key)) {
          const descriptor = (0, _primordials.ReflectGetOwnPropertyDescriptor)(target, key);
          descriptor.value = (0, _converter.convertToNumber)(descriptor.value);
          return descriptor;
        }
        return (0, _primordials.ReflectGetOwnPropertyDescriptor)(target, key);
      },
      defineProperty(target, key, descriptor) {
        if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key) && (0, _primordials.ObjectHasOwn)(descriptor, "value")) {
          descriptor.value = (0, _converter.roundToFloat16Bits)(descriptor.value);
          return (0, _primordials.ReflectDefineProperty)(target, key, descriptor);
        }
        return (0, _primordials.ReflectDefineProperty)(target, key, descriptor);
      }
    });
    var Float16Array = class _Float16Array {
      constructor(input, _byteOffset, _length) {
        let float16bitsArray;
        if (isFloat16Array(input)) {
          float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, [getFloat16BitsArray(input)], new.target);
        } else if ((0, _is.isObject)(input) && !(0, _is.isAnyArrayBuffer)(input)) {
          let list;
          let length;
          if ((0, _is.isNativeTypedArray)(input)) {
            list = input;
            length = (0, _primordials.TypedArrayPrototypeGetLength)(input);
            const buffer = (0, _primordials.TypedArrayPrototypeGetBuffer)(input);
            if ((0, _spec.IsDetachedBuffer)(buffer)) {
              throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
            }
            if ((0, _is.isNativeBigIntTypedArray)(input)) {
              throw (0, _primordials.NativeTypeError)(_messages.CANNOT_MIX_BIGINT_AND_OTHER_TYPES);
            }
            const data = new _primordials.NativeArrayBuffer(length * BYTES_PER_ELEMENT);
            float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, [data], new.target);
          } else {
            const iterator = input[_primordials.SymbolIterator];
            if (iterator != null && typeof iterator !== "function") {
              throw (0, _primordials.NativeTypeError)(_messages.ITERATOR_PROPERTY_IS_NOT_CALLABLE);
            }
            if (iterator != null) {
              if ((0, _is.isOrdinaryArray)(input)) {
                list = input;
                length = input.length;
              } else {
                list = [...input];
                length = list.length;
              }
            } else {
              list = input;
              length = (0, _spec.ToLength)(list.length);
            }
            float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, [length], new.target);
          }
          for (let i6 = 0; i6 < length; ++i6) {
            float16bitsArray[i6] = (0, _converter.roundToFloat16Bits)(list[i6]);
          }
        } else {
          float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, arguments, new.target);
        }
        const proxy = new _primordials.NativeProxy(float16bitsArray, handler);
        (0, _primordials.WeakMapPrototypeSet)(float16bitsArrays, proxy, float16bitsArray);
        return proxy;
      }
      static from(src, ...opts) {
        const Constructor = this;
        if (!(0, _primordials.ReflectHas)(Constructor, _brand.brand)) {
          throw (0, _primordials.NativeTypeError)(_messages.THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY);
        }
        if (Constructor === _Float16Array) {
          if (isFloat16Array(src) && opts.length === 0) {
            const float16bitsArray = getFloat16BitsArray(src);
            const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
            return new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
          }
          if (opts.length === 0) {
            return new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.Uint16ArrayFrom)(src, _converter.roundToFloat16Bits)));
          }
          const mapFunc = opts[0];
          const thisArg = opts[1];
          return new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.Uint16ArrayFrom)(src, function(val2, ...args) {
            return (0, _converter.roundToFloat16Bits)((0, _primordials.ReflectApply)(mapFunc, this, [val2, ...(0, _arrayIterator.safeIfNeeded)(args)]));
          }, thisArg)));
        }
        let list;
        let length;
        const iterator = src[_primordials.SymbolIterator];
        if (iterator != null && typeof iterator !== "function") {
          throw (0, _primordials.NativeTypeError)(_messages.ITERATOR_PROPERTY_IS_NOT_CALLABLE);
        }
        if (iterator != null) {
          if ((0, _is.isOrdinaryArray)(src)) {
            list = src;
            length = src.length;
          } else if ((0, _is.isOrdinaryNativeTypedArray)(src)) {
            list = src;
            length = (0, _primordials.TypedArrayPrototypeGetLength)(src);
          } else {
            list = [...src];
            length = list.length;
          }
        } else {
          if (src == null) {
            throw (0, _primordials.NativeTypeError)(_messages.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT);
          }
          list = (0, _primordials.NativeObject)(src);
          length = (0, _spec.ToLength)(list.length);
        }
        const array2 = new Constructor(length);
        if (opts.length === 0) {
          for (let i6 = 0; i6 < length; ++i6) {
            array2[i6] = list[i6];
          }
        } else {
          const mapFunc = opts[0];
          const thisArg = opts[1];
          for (let i6 = 0; i6 < length; ++i6) {
            array2[i6] = (0, _primordials.ReflectApply)(mapFunc, thisArg, [list[i6], i6]);
          }
        }
        return array2;
      }
      static of(...items) {
        const Constructor = this;
        if (!(0, _primordials.ReflectHas)(Constructor, _brand.brand)) {
          throw (0, _primordials.NativeTypeError)(_messages.THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY);
        }
        const length = items.length;
        if (Constructor === _Float16Array) {
          const proxy = new _Float16Array(length);
          const float16bitsArray = getFloat16BitsArray(proxy);
          for (let i6 = 0; i6 < length; ++i6) {
            float16bitsArray[i6] = (0, _converter.roundToFloat16Bits)(items[i6]);
          }
          return proxy;
        }
        const array2 = new Constructor(length);
        for (let i6 = 0; i6 < length; ++i6) {
          array2[i6] = items[i6];
        }
        return array2;
      }
      keys() {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        return (0, _primordials.TypedArrayPrototypeKeys)(float16bitsArray);
      }
      values() {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        return (0, _arrayIterator.wrap)(function* () {
          for (const val2 of (0, _primordials.TypedArrayPrototypeValues)(float16bitsArray)) {
            yield (0, _converter.convertToNumber)(val2);
          }
        }());
      }
      entries() {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        return (0, _arrayIterator.wrap)(function* () {
          for (const [i6, val2] of (0, _primordials.TypedArrayPrototypeEntries)(float16bitsArray)) {
            yield [i6, (0, _converter.convertToNumber)(val2)];
          }
        }());
      }
      at(index6) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const relativeIndex = (0, _spec.ToIntegerOrInfinity)(index6);
        const k5 = relativeIndex >= 0 ? relativeIndex : length + relativeIndex;
        if (k5 < 0 || k5 >= length) {
          return;
        }
        return (0, _converter.convertToNumber)(float16bitsArray[k5]);
      }
      with(index6, value) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const relativeIndex = (0, _spec.ToIntegerOrInfinity)(index6);
        const k5 = relativeIndex >= 0 ? relativeIndex : length + relativeIndex;
        const number = +value;
        if (k5 < 0 || k5 >= length) {
          throw (0, _primordials.NativeRangeError)(_messages.OFFSET_IS_OUT_OF_BOUNDS);
        }
        const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
        const cloned = new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
        const array2 = getFloat16BitsArray(cloned);
        array2[k5] = (0, _converter.roundToFloat16Bits)(number);
        return cloned;
      }
      map(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const thisArg = opts[0];
        const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, _Float16Array);
        if (Constructor === _Float16Array) {
          const proxy = new _Float16Array(length);
          const array3 = getFloat16BitsArray(proxy);
          for (let i6 = 0; i6 < length; ++i6) {
            const val2 = (0, _converter.convertToNumber)(float16bitsArray[i6]);
            array3[i6] = (0, _converter.roundToFloat16Bits)((0, _primordials.ReflectApply)(callback, thisArg, [val2, i6, this]));
          }
          return proxy;
        }
        const array2 = new Constructor(length);
        assertSpeciesTypedArray(array2, length);
        for (let i6 = 0; i6 < length; ++i6) {
          const val2 = (0, _converter.convertToNumber)(float16bitsArray[i6]);
          array2[i6] = (0, _primordials.ReflectApply)(callback, thisArg, [val2, i6, this]);
        }
        return array2;
      }
      filter(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const thisArg = opts[0];
        const kept = [];
        for (let i6 = 0; i6 < length; ++i6) {
          const val2 = (0, _converter.convertToNumber)(float16bitsArray[i6]);
          if ((0, _primordials.ReflectApply)(callback, thisArg, [val2, i6, this])) {
            (0, _primordials.ArrayPrototypePush)(kept, val2);
          }
        }
        const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, _Float16Array);
        const array2 = new Constructor(kept);
        assertSpeciesTypedArray(array2);
        return array2;
      }
      reduce(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        if (length === 0 && opts.length === 0) {
          throw (0, _primordials.NativeTypeError)(_messages.REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE);
        }
        let accumulator, start;
        if (opts.length === 0) {
          accumulator = (0, _converter.convertToNumber)(float16bitsArray[0]);
          start = 1;
        } else {
          accumulator = opts[0];
          start = 0;
        }
        for (let i6 = start; i6 < length; ++i6) {
          accumulator = callback(accumulator, (0, _converter.convertToNumber)(float16bitsArray[i6]), i6, this);
        }
        return accumulator;
      }
      reduceRight(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        if (length === 0 && opts.length === 0) {
          throw (0, _primordials.NativeTypeError)(_messages.REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE);
        }
        let accumulator, start;
        if (opts.length === 0) {
          accumulator = (0, _converter.convertToNumber)(float16bitsArray[length - 1]);
          start = length - 2;
        } else {
          accumulator = opts[0];
          start = length - 1;
        }
        for (let i6 = start; i6 >= 0; --i6) {
          accumulator = callback(accumulator, (0, _converter.convertToNumber)(float16bitsArray[i6]), i6, this);
        }
        return accumulator;
      }
      forEach(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const thisArg = opts[0];
        for (let i6 = 0; i6 < length; ++i6) {
          (0, _primordials.ReflectApply)(callback, thisArg, [(0, _converter.convertToNumber)(float16bitsArray[i6]), i6, this]);
        }
      }
      find(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const thisArg = opts[0];
        for (let i6 = 0; i6 < length; ++i6) {
          const value = (0, _converter.convertToNumber)(float16bitsArray[i6]);
          if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i6, this])) {
            return value;
          }
        }
      }
      findIndex(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const thisArg = opts[0];
        for (let i6 = 0; i6 < length; ++i6) {
          const value = (0, _converter.convertToNumber)(float16bitsArray[i6]);
          if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i6, this])) {
            return i6;
          }
        }
        return -1;
      }
      findLast(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const thisArg = opts[0];
        for (let i6 = length - 1; i6 >= 0; --i6) {
          const value = (0, _converter.convertToNumber)(float16bitsArray[i6]);
          if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i6, this])) {
            return value;
          }
        }
      }
      findLastIndex(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const thisArg = opts[0];
        for (let i6 = length - 1; i6 >= 0; --i6) {
          const value = (0, _converter.convertToNumber)(float16bitsArray[i6]);
          if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i6, this])) {
            return i6;
          }
        }
        return -1;
      }
      every(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const thisArg = opts[0];
        for (let i6 = 0; i6 < length; ++i6) {
          if (!(0, _primordials.ReflectApply)(callback, thisArg, [(0, _converter.convertToNumber)(float16bitsArray[i6]), i6, this])) {
            return false;
          }
        }
        return true;
      }
      some(callback, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const thisArg = opts[0];
        for (let i6 = 0; i6 < length; ++i6) {
          if ((0, _primordials.ReflectApply)(callback, thisArg, [(0, _converter.convertToNumber)(float16bitsArray[i6]), i6, this])) {
            return true;
          }
        }
        return false;
      }
      set(input, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const targetOffset = (0, _spec.ToIntegerOrInfinity)(opts[0]);
        if (targetOffset < 0) {
          throw (0, _primordials.NativeRangeError)(_messages.OFFSET_IS_OUT_OF_BOUNDS);
        }
        if (input == null) {
          throw (0, _primordials.NativeTypeError)(_messages.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT);
        }
        if ((0, _is.isNativeBigIntTypedArray)(input)) {
          throw (0, _primordials.NativeTypeError)(_messages.CANNOT_MIX_BIGINT_AND_OTHER_TYPES);
        }
        if (isFloat16Array(input)) {
          return (0, _primordials.TypedArrayPrototypeSet)(getFloat16BitsArray(this), getFloat16BitsArray(input), targetOffset);
        }
        if ((0, _is.isNativeTypedArray)(input)) {
          const buffer = (0, _primordials.TypedArrayPrototypeGetBuffer)(input);
          if ((0, _spec.IsDetachedBuffer)(buffer)) {
            throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
          }
        }
        const targetLength = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const src = (0, _primordials.NativeObject)(input);
        const srcLength = (0, _spec.ToLength)(src.length);
        if (targetOffset === Infinity || srcLength + targetOffset > targetLength) {
          throw (0, _primordials.NativeRangeError)(_messages.OFFSET_IS_OUT_OF_BOUNDS);
        }
        for (let i6 = 0; i6 < srcLength; ++i6) {
          float16bitsArray[i6 + targetOffset] = (0, _converter.roundToFloat16Bits)(src[i6]);
        }
      }
      reverse() {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        (0, _primordials.TypedArrayPrototypeReverse)(float16bitsArray);
        return this;
      }
      toReversed() {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
        const cloned = new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
        const clonedFloat16bitsArray = getFloat16BitsArray(cloned);
        (0, _primordials.TypedArrayPrototypeReverse)(clonedFloat16bitsArray);
        return cloned;
      }
      fill(value, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        (0, _primordials.TypedArrayPrototypeFill)(float16bitsArray, (0, _converter.roundToFloat16Bits)(value), ...(0, _arrayIterator.safeIfNeeded)(opts));
        return this;
      }
      copyWithin(target, start, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        (0, _primordials.TypedArrayPrototypeCopyWithin)(float16bitsArray, target, start, ...(0, _arrayIterator.safeIfNeeded)(opts));
        return this;
      }
      sort(compareFn) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const sortCompare = compareFn !== void 0 ? compareFn : _spec.defaultCompare;
        (0, _primordials.TypedArrayPrototypeSort)(float16bitsArray, (x5, y2) => {
          return sortCompare((0, _converter.convertToNumber)(x5), (0, _converter.convertToNumber)(y2));
        });
        return this;
      }
      toSorted(compareFn) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        if (compareFn !== void 0 && typeof compareFn !== "function") {
          throw new _primordials.NativeTypeError(_messages.THE_COMPARISON_FUNCTION_MUST_BE_EITHER_A_FUNCTION_OR_UNDEFINED);
        }
        const sortCompare = compareFn !== void 0 ? compareFn : _spec.defaultCompare;
        const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
        const cloned = new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
        const clonedFloat16bitsArray = getFloat16BitsArray(cloned);
        (0, _primordials.TypedArrayPrototypeSort)(clonedFloat16bitsArray, (x5, y2) => {
          return sortCompare((0, _converter.convertToNumber)(x5), (0, _converter.convertToNumber)(y2));
        });
        return cloned;
      }
      slice(start, end) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, _Float16Array);
        if (Constructor === _Float16Array) {
          const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
          return new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16, start, end)));
        }
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        const relativeStart = (0, _spec.ToIntegerOrInfinity)(start);
        const relativeEnd = end === void 0 ? length : (0, _spec.ToIntegerOrInfinity)(end);
        let k5;
        if (relativeStart === -Infinity) {
          k5 = 0;
        } else if (relativeStart < 0) {
          k5 = length + relativeStart > 0 ? length + relativeStart : 0;
        } else {
          k5 = length < relativeStart ? length : relativeStart;
        }
        let final;
        if (relativeEnd === -Infinity) {
          final = 0;
        } else if (relativeEnd < 0) {
          final = length + relativeEnd > 0 ? length + relativeEnd : 0;
        } else {
          final = length < relativeEnd ? length : relativeEnd;
        }
        const count = final - k5 > 0 ? final - k5 : 0;
        const array2 = new Constructor(count);
        assertSpeciesTypedArray(array2, count);
        if (count === 0) {
          return array2;
        }
        const buffer = (0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray);
        if ((0, _spec.IsDetachedBuffer)(buffer)) {
          throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
        }
        let n5 = 0;
        while (k5 < final) {
          array2[n5] = (0, _converter.convertToNumber)(float16bitsArray[k5]);
          ++k5;
          ++n5;
        }
        return array2;
      }
      subarray(begin, end) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, _Float16Array);
        const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
        const uint16Subarray = (0, _primordials.TypedArrayPrototypeSubarray)(uint16, begin, end);
        const array2 = new Constructor((0, _primordials.TypedArrayPrototypeGetBuffer)(uint16Subarray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(uint16Subarray), (0, _primordials.TypedArrayPrototypeGetLength)(uint16Subarray));
        assertSpeciesTypedArray(array2);
        return array2;
      }
      indexOf(element, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        let from = (0, _spec.ToIntegerOrInfinity)(opts[0]);
        if (from === Infinity) {
          return -1;
        }
        if (from < 0) {
          from += length;
          if (from < 0) {
            from = 0;
          }
        }
        for (let i6 = from; i6 < length; ++i6) {
          if ((0, _primordials.ObjectHasOwn)(float16bitsArray, i6) && (0, _converter.convertToNumber)(float16bitsArray[i6]) === element) {
            return i6;
          }
        }
        return -1;
      }
      lastIndexOf(element, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        let from = opts.length >= 1 ? (0, _spec.ToIntegerOrInfinity)(opts[0]) : length - 1;
        if (from === -Infinity) {
          return -1;
        }
        if (from >= 0) {
          from = from < length - 1 ? from : length - 1;
        } else {
          from += length;
        }
        for (let i6 = from; i6 >= 0; --i6) {
          if ((0, _primordials.ObjectHasOwn)(float16bitsArray, i6) && (0, _converter.convertToNumber)(float16bitsArray[i6]) === element) {
            return i6;
          }
        }
        return -1;
      }
      includes(element, ...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
        let from = (0, _spec.ToIntegerOrInfinity)(opts[0]);
        if (from === Infinity) {
          return false;
        }
        if (from < 0) {
          from += length;
          if (from < 0) {
            from = 0;
          }
        }
        const isNaN2 = (0, _primordials.NumberIsNaN)(element);
        for (let i6 = from; i6 < length; ++i6) {
          const value = (0, _converter.convertToNumber)(float16bitsArray[i6]);
          if (isNaN2 && (0, _primordials.NumberIsNaN)(value)) {
            return true;
          }
          if (value === element) {
            return true;
          }
        }
        return false;
      }
      join(separator) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const array2 = copyToArray(float16bitsArray);
        return (0, _primordials.ArrayPrototypeJoin)(array2, separator);
      }
      toLocaleString(...opts) {
        assertFloat16Array(this);
        const float16bitsArray = getFloat16BitsArray(this);
        const array2 = copyToArray(float16bitsArray);
        return (0, _primordials.ArrayPrototypeToLocaleString)(array2, ...(0, _arrayIterator.safeIfNeeded)(opts));
      }
      get [_primordials.SymbolToStringTag]() {
        if (isFloat16Array(this)) {
          return "Float16Array";
        }
      }
    };
    exports2.Float16Array = Float16Array;
    (0, _primordials.ObjectDefineProperty)(Float16Array, "BYTES_PER_ELEMENT", {
      value: BYTES_PER_ELEMENT
    });
    (0, _primordials.ObjectDefineProperty)(Float16Array, _brand.brand, {});
    (0, _primordials.ReflectSetPrototypeOf)(Float16Array, _primordials.TypedArray);
    var Float16ArrayPrototype = Float16Array.prototype;
    (0, _primordials.ObjectDefineProperty)(Float16ArrayPrototype, "BYTES_PER_ELEMENT", {
      value: BYTES_PER_ELEMENT
    });
    (0, _primordials.ObjectDefineProperty)(Float16ArrayPrototype, _primordials.SymbolIterator, {
      value: Float16ArrayPrototype.values,
      writable: true,
      configurable: true
    });
    (0, _primordials.ReflectSetPrototypeOf)(Float16ArrayPrototype, _primordials.TypedArrayPrototype);
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/isTypedArray.cjs
var require_isTypedArray = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/isTypedArray.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.isTypedArray = isTypedArray;
    var _Float16Array = require_Float16Array();
    var _is = require_is();
    function isTypedArray(target) {
      return (0, _is.isNativeTypedArray)(target) || (0, _Float16Array.isFloat16Array)(target);
    }
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/DataView.cjs
var require_DataView = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/DataView.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.getFloat16 = getFloat16;
    exports2.setFloat16 = setFloat16;
    var _arrayIterator = require_arrayIterator();
    var _converter = require_converter();
    var _primordials = require_primordials();
    function getFloat16(dataView, byteOffset, ...opts) {
      return (0, _converter.convertToNumber)((0, _primordials.DataViewPrototypeGetUint16)(dataView, byteOffset, ...(0, _arrayIterator.safeIfNeeded)(opts)));
    }
    function setFloat16(dataView, byteOffset, value, ...opts) {
      return (0, _primordials.DataViewPrototypeSetUint16)(dataView, byteOffset, (0, _converter.roundToFloat16Bits)(value), ...(0, _arrayIterator.safeIfNeeded)(opts));
    }
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/f16round.cjs
var require_f16round = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/f16round.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.f16round = f16round;
    var _converter = require_converter();
    function f16round(x5) {
      return (0, _converter.roundToFloat16)(x5);
    }
  }
});

// ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/index.cjs
var require_lib2 = __commonJS({
  "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/index.cjs"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    var _Float16Array = require_Float16Array();
    exports2.Float16Array = _Float16Array.Float16Array;
    exports2.isFloat16Array = _Float16Array.isFloat16Array;
    var _isTypedArray = require_isTypedArray();
    exports2.isTypedArray = _isTypedArray.isTypedArray;
    var _DataView = require_DataView();
    exports2.getFloat16 = _DataView.getFloat16;
    exports2.setFloat16 = _DataView.setFloat16;
    var _f16round = require_f16round();
    exports2.f16round = _f16round.f16round;
    exports2.hfround = _f16round.f16round;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/utils.js
var require_utils2 = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/utils.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.setFloat16 = exports2.isFloat16Array = exports2.getFloat16 = exports2.Float16Array = void 0;
    exports2.getUniqueId = getUniqueId;
    exports2.sleep = sleep;
    exports2.versionEqual = versionEqual;
    exports2.versionGreaterThan = versionGreaterThan;
    exports2.versionGreaterThanOrEqual = versionGreaterThanOrEqual;
    exports2.getAuthenticatedFetch = getAuthenticatedFetch;
    var float16_1 = require_lib2();
    Object.defineProperty(exports2, "Float16Array", { enumerable: true, get: function() {
      return float16_1.Float16Array;
    } });
    Object.defineProperty(exports2, "getFloat16", { enumerable: true, get: function() {
      return float16_1.getFloat16;
    } });
    Object.defineProperty(exports2, "isFloat16Array", { enumerable: true, get: function() {
      return float16_1.isFloat16Array;
    } });
    Object.defineProperty(exports2, "setFloat16", { enumerable: true, get: function() {
      return float16_1.setFloat16;
    } });
    var idCounter = {};
    function getUniqueId(prefix2 = "") {
      if (!idCounter[prefix2]) {
        idCounter[prefix2] = 0;
      }
      const id = ++idCounter[prefix2];
      return `_gel_${prefix2}_${id.toString(16)}_`;
    }
    function sleep(durationMillis) {
      return new Promise((accept) => {
        setTimeout(() => accept(), durationMillis);
      });
    }
    function versionEqual(left, right) {
      return left[0] === right[0] && left[1] === right[1];
    }
    function versionGreaterThan(left, right) {
      if (left[0] > right[0]) {
        return true;
      }
      if (left[0] < right[0]) {
        return false;
      }
      return left[1] > right[1];
    }
    function versionGreaterThanOrEqual(left, right) {
      if (left[0] === right[0] && left[1] === right[1]) {
        return true;
      }
      return versionGreaterThan(left, right);
    }
    var _tokens = /* @__PURE__ */ new WeakMap();
    async function getAuthenticatedFetch(config, httpSCRAMAuth, basePath) {
      let token = config.secretKey ?? _tokens.get(config);
      const { address, tlsSecurity, database } = config;
      const protocol = tlsSecurity === "insecure" ? "http" : "https";
      const baseUrl = `${protocol}://${address[0]}:${address[1]}`;
      const databaseUrl = `${baseUrl}/db/${database}/${basePath ?? ""}`;
      if (!token && config.password != null) {
        token = await httpSCRAMAuth(baseUrl, config.user, config.password);
        _tokens.set(config, token);
      }
      return (input, init2) => {
        let path3;
        if (typeof input === "string") {
          path3 = input;
        } else if (input instanceof Request) {
          path3 = input.url;
        } else
          path3 = input.toString();
        const url = new URL(path3, databaseUrl);
        const headers = new Headers(init2?.headers);
        if (config.user !== void 0) {
          headers.append("X-EdgeDB-User", config.user);
        }
        if (token !== void 0) {
          headers.append("Authorization", `Bearer ${token}`);
        }
        return fetch(url, {
          ...init2,
          headers
        });
      };
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/pgvector.js
var require_pgvector = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/pgvector.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SparseVector = void 0;
    var SparseVector = class {
      constructor(length, indexesOrMap, values) {
        __publicField(this, "length");
        __publicField(this, "indexes");
        __publicField(this, "values");
        this.length = length;
        if (indexesOrMap instanceof Uint32Array) {
          if (indexesOrMap.length !== values?.length) {
            throw new Error("indexes array must be the same length as the data array");
          }
          if (indexesOrMap.length > length) {
            throw new Error("length of data cannot be larger than length of sparse vector");
          }
          this.values = values;
          this.indexes = indexesOrMap;
        } else {
          const entries = Object.entries(indexesOrMap);
          if (entries.length > length) {
            throw new Error("length of data cannot be larger than length of sparse vector");
          }
          this.indexes = new Uint32Array(entries.length);
          this.values = new Float32Array(entries.length);
          for (let i6 = 0; i6 < entries.length; i6++) {
            const index6 = parseInt(entries[i6][0], 10);
            const val2 = entries[i6][1];
            if (Number.isNaN(index6)) {
              throw new Error(`key ${entries[i6][0]} in data map is not an integer`);
            }
            if (index6 < 0 || index6 >= length) {
              throw new Error(`index ${index6} is out of range of sparse vector length`);
            }
            this.indexes[i6] = index6;
            if (typeof val2 !== "number") {
              throw new Error(`expected value at index ${index6} to be number, got ${typeof val2} ${val2}`);
            }
            if (val2 === 0) {
              throw new Error("elements in sparse vector cannot be 0");
            }
            this.values[i6] = val2;
          }
        }
        return new Proxy(this, {
          get(target, p5) {
            const index6 = typeof p5 === "string" ? parseInt(p5, 10) : NaN;
            if (!Number.isNaN(index6)) {
              if (index6 < 0 || index6 >= target.length)
                return void 0;
              const dataIndex = target.indexes.indexOf(index6);
              return dataIndex === -1 ? 0 : target.values[dataIndex];
            }
            return target[p5];
          }
        });
      }
      *[Symbol.iterator]() {
        let nextIndex = 0;
        for (let i6 = 0; i6 < this.length; i6++) {
          yield this.indexes[nextIndex] === i6 ? this.values[nextIndex++] : 0;
        }
      }
    };
    exports2.SparseVector = SparseVector;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/pgvector.js
var require_pgvector2 = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/pgvector.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PgVectorSparseVecCodec = exports2.PgVectorHalfVecCodec = exports2.PgVectorCodec = exports2.PG_VECTOR_MAX_DIM = void 0;
    var ifaces_1 = require_ifaces();
    var errors_1 = require_errors();
    var utils_1 = require_utils2();
    var pgvector_1 = require_pgvector();
    exports2.PG_VECTOR_MAX_DIM = (1 << 16) - 1;
    var PgVectorCodec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "Float32Array");
      }
      encode(buf, object, ctx) {
        object = ctx.preEncode(this, object);
        if (!(object instanceof Float32Array || Array.isArray(object))) {
          throw new errors_1.InvalidArgumentError(`a Float32Array or array of numbers was expected, got "${object}"`);
        }
        if (object.length > exports2.PG_VECTOR_MAX_DIM) {
          throw new errors_1.InvalidArgumentError("too many elements in array to encode into pgvector");
        }
        buf.writeInt32(4 + object.length * 4).writeUInt16(object.length).writeUInt16(0);
        if (object instanceof Float32Array) {
          for (const el of object) {
            buf.writeFloat32(el);
          }
        } else {
          for (const el of object) {
            if (typeof el !== "number") {
              throw new errors_1.InvalidArgumentError(`elements of vector array expected to be a numbers, got "${el}"`);
            }
            buf.writeFloat32(el);
          }
        }
      }
      decode(buf, ctx) {
        const dim = buf.readUInt16();
        buf.discard(2);
        const vecBuf = buf.readBuffer(dim * 4);
        const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
        const vec = new Float32Array(dim);
        for (let i6 = 0; i6 < dim; i6++) {
          vec[i6] = data.getFloat32(i6 * 4);
        }
        return ctx.postDecode(this, vec);
      }
    };
    exports2.PgVectorCodec = PgVectorCodec;
    var PgVectorHalfVecCodec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "Float16Array");
        __publicField(this, "tsModule", "gel");
      }
      encode(buf, object, ctx) {
        object = ctx.preEncode(this, object);
        if (!((0, utils_1.isFloat16Array)(object) || Array.isArray(object))) {
          throw new errors_1.InvalidArgumentError(`a Float16Array or array of numbers was expected, got "${object}"`);
        }
        if (object.length > exports2.PG_VECTOR_MAX_DIM) {
          throw new errors_1.InvalidArgumentError("too many elements in array to encode into pgvector");
        }
        buf.writeInt32(4 + object.length * 2).writeUInt16(object.length).writeUInt16(0);
        const vecBuf = new Uint8Array(object.length * 2);
        const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
        if ((0, utils_1.isFloat16Array)(object)) {
          for (let i6 = 0; i6 < object.length; i6++) {
            (0, utils_1.setFloat16)(data, i6 * 2, object[i6]);
          }
        } else {
          for (let i6 = 0; i6 < object.length; i6++) {
            if (typeof object[i6] !== "number") {
              throw new errors_1.InvalidArgumentError(`elements of vector array expected to be a numbers, got "${object[i6]}"`);
            }
            (0, utils_1.setFloat16)(data, i6 * 2, object[i6]);
          }
        }
        buf.writeBuffer(vecBuf);
      }
      decode(buf, ctx) {
        const dim = buf.readUInt16();
        buf.discard(2);
        const vecBuf = buf.readBuffer(dim * 2);
        const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
        const vec = new utils_1.Float16Array(dim);
        for (let i6 = 0; i6 < dim; i6++) {
          vec[i6] = (0, utils_1.getFloat16)(data, i6 * 2);
        }
        return ctx.postDecode(this, vec);
      }
    };
    exports2.PgVectorHalfVecCodec = PgVectorHalfVecCodec;
    var PgVectorSparseVecCodec = class extends ifaces_1.ScalarCodec {
      constructor() {
        super(...arguments);
        __publicField(this, "tsType", "SparseVector");
        __publicField(this, "tsModule", "gel");
      }
      encode(buf, object, ctx) {
        let dims;
        let indexes;
        let values;
        if (ctx.hasOverload(this)) {
          [dims, indexes, values] = ctx.preEncode(this, object);
        } else {
          if (!(object instanceof pgvector_1.SparseVector)) {
            throw new errors_1.InvalidArgumentError(`a SparseVector was expected, got "${object}"`);
          }
          dims = object.length;
          indexes = object.indexes;
          values = object.values;
        }
        const indexesLength = indexes.length;
        if (indexesLength > exports2.PG_VECTOR_MAX_DIM || indexesLength > dims) {
          throw new errors_1.InvalidArgumentError("too many elements in sparse vector value");
        }
        buf.writeUInt32(4 * (3 + indexesLength * 2)).writeUInt32(dims).writeUInt32(indexesLength).writeUInt32(0);
        const vecBuf = new Uint8Array(indexesLength * 8);
        const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
        for (let i6 = 0; i6 < indexesLength; i6++) {
          data.setUint32(i6 * 4, indexes[i6]);
        }
        for (let i6 = 0; i6 < indexesLength; i6++) {
          data.setFloat32((indexesLength + i6) * 4, values[i6]);
        }
        buf.writeBuffer(vecBuf);
      }
      decode(buf, ctx) {
        const dim = buf.readUInt32();
        const nnz = buf.readUInt32();
        buf.discard(4);
        const vecBuf = buf.readBuffer(nnz * 8);
        const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
        const indexes = new Uint32Array(nnz);
        for (let i6 = 0; i6 < nnz; i6++) {
          indexes[i6] = data.getUint32(i6 * 4);
        }
        const vecData = new Float32Array(nnz);
        for (let i6 = 0; i6 < nnz; i6++) {
          vecData[i6] = data.getFloat32((i6 + nnz) * 4);
        }
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, [
            dim,
            indexes,
            vecData
          ]);
        }
        return new pgvector_1.SparseVector(dim, indexes, vecData);
      }
    };
    exports2.PgVectorSparseVecCodec = PgVectorSparseVecCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/postgis.js
var require_postgis = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/postgis.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Box3D = exports2.Box2D = exports2.GeometryCollection = exports2.MultiSurface = exports2.TriangulatedIrregularNetwork = exports2.PolyhedralSurface = exports2.MultiPolygon = exports2.CurvePolygon = exports2.Triangle = exports2.Polygon = exports2.MultiCurve = exports2.CompoundCurve = exports2.MultiLineString = exports2.CircularString = exports2.LineString = exports2.MultiPoint = exports2.Point = exports2.Geometry = void 0;
    var Geometry = class {
    };
    exports2.Geometry = Geometry;
    function _pointToWKT(p5) {
      return `${p5.x} ${p5.y}${p5.z !== null ? ` ${p5.z}` : ""}${p5.m !== null ? ` ${p5.m}` : ""}`;
    }
    function _flagsToWKT(z2, m6) {
      return (z2 || m6 ? " " : "") + (z2 ? "Z" : "") + (m6 ? "M" : "");
    }
    function _sridWKTPrefix(srid, depth) {
      return srid !== null && depth === 0 ? `SRID=${srid}; ` : "";
    }
    function _indent(indent, depth) {
      if (!indent)
        return "";
      return "\n" + " ".repeat(indent * depth);
    }
    var Point = class extends Geometry {
      constructor(x5, y2, z2 = null, m6 = null, srid = null) {
        super();
        __publicField(this, "x");
        __publicField(this, "y");
        __publicField(this, "z");
        __publicField(this, "m");
        __publicField(this, "srid");
        this.x = x5;
        this.y = y2;
        this.z = z2;
        this.m = m6;
        this.srid = srid;
      }
      get hasZ() {
        return this.z !== null;
      }
      get hasM() {
        return this.m !== null;
      }
      toWKT(_indent2, _truncate = Infinity, depth = 0) {
        return `${_sridWKTPrefix(this.srid, depth)}POINT${_flagsToWKT(this.z !== null, this.m !== null)} ${Number.isNaN(this.x) ? "EMPTY" : "(" + _pointToWKT(this) + ")"}`;
      }
      equals(other) {
        return this.srid === other.srid && (Number.isNaN(this.x) ? this.hasZ === other.hasZ && this.hasM === other.hasM : this.x === other.x && this.y === other.y && this.z === other.z && this.m === other.m);
      }
    };
    exports2.Point = Point;
    var MultiPoint = class extends Geometry {
      constructor(geometries, hasZ, hasM, srid) {
        super();
        __publicField(this, "geometries");
        __publicField(this, "hasZ");
        __publicField(this, "hasM");
        __publicField(this, "srid");
        this.geometries = geometries;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
      }
      toWKT(indent, truncate = Infinity, depth = 0) {
        let wkt = `${_sridWKTPrefix(this.srid, depth)}MULTIPOINT${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.geometries.length === 0) {
          return wkt + "EMPTY";
        }
        wkt += `(`;
        let i6 = 0;
        while (i6 < this.geometries.length && wkt.length < truncate) {
          wkt += _indent(indent, depth + 1) + "(" + _pointToWKT(this.geometries[i6++]) + (i6 < this.geometries.length ? "), " : ")");
        }
        return wkt + _indent(indent, depth) + ")";
      }
    };
    exports2.MultiPoint = MultiPoint;
    function _linestringToWKT(points, indent, truncate = Infinity, depth = 0) {
      let wkt = `(`;
      let i6 = 0;
      while (i6 < points.length && wkt.length < truncate) {
        wkt += _indent(indent, depth + 1) + _pointToWKT(points[i6++]) + (i6 < points.length ? ", " : "");
      }
      return wkt + _indent(indent, depth) + ")";
    }
    var LineString = class extends Geometry {
      constructor(points, hasZ, hasM, srid) {
        super();
        __publicField(this, "points");
        __publicField(this, "hasZ");
        __publicField(this, "hasM");
        __publicField(this, "srid");
        this.points = points;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
        this._validate();
      }
      _validate() {
        if (this.points.length === 1) {
          throw new Error(`expected zero, or 2 or more points in LineString`);
        }
      }
      toWKT(indent, truncate = Infinity, depth = 0) {
        const wkt = `${_sridWKTPrefix(this.srid, depth)}${this.constructor._wktName}${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.points.length === 0) {
          return wkt + "EMPTY";
        }
        return wkt + _linestringToWKT(this.points, indent, truncate - wkt.length, depth);
      }
    };
    __publicField(LineString, "_wktName", "LINESTRING");
    exports2.LineString = LineString;
    var CircularString = class extends LineString {
      _validate() {
        if (this.points.length !== 0 && (this.points.length <= 1 || this.points.length % 2 !== 1)) {
          throw new Error(`expected zero points, or odd number of points greater than 1 in CircularString`);
        }
      }
    };
    __publicField(CircularString, "_wktName", "CIRCULARSTRING");
    exports2.CircularString = CircularString;
    function _multilinestringToWKT(lineStrings, indent, truncate = Infinity, depth = 0) {
      let wkt = `(`;
      let i6 = 0;
      while (i6 < lineStrings.length && wkt.length < truncate) {
        wkt += _indent(indent, depth + 1) + _linestringToWKT(lineStrings[i6++].points, indent, truncate - wkt.length, depth + 1) + (i6 < lineStrings.length ? ", " : "");
      }
      return wkt + _indent(indent, depth) + ")";
    }
    var MultiLineString = class extends Geometry {
      constructor(geometries, hasZ, hasM, srid) {
        super();
        __publicField(this, "geometries");
        __publicField(this, "hasZ");
        __publicField(this, "hasM");
        __publicField(this, "srid");
        this.geometries = geometries;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
      }
      toWKT(indent, truncate = Infinity, depth = 0) {
        const wkt = `${_sridWKTPrefix(this.srid, depth)}MULTILINESTRING${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.geometries.length === 0) {
          return wkt + "EMPTY";
        }
        return wkt + _multilinestringToWKT(this.geometries, indent, truncate - wkt.length, depth);
      }
    };
    exports2.MultiLineString = MultiLineString;
    var CompoundCurve = class extends Geometry {
      constructor(geometries, hasZ, hasM, srid) {
        super();
        __publicField(this, "geometries");
        __publicField(this, "hasZ");
        __publicField(this, "hasM");
        __publicField(this, "srid");
        this.geometries = geometries;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
        let lastPoint = null;
        for (const segment of geometries) {
          if (lastPoint && !segment.points[0].equals(lastPoint)) {
            throw new Error("segments in CompoundCurve do not join");
          }
          lastPoint = segment.points[segment.points.length - 1];
        }
      }
      toWKT(indent, truncate = Infinity, depth = 0) {
        let wkt = `${_sridWKTPrefix(this.srid, depth)}COMPOUNDCURVE${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.geometries.length === 0) {
          return wkt + "EMPTY";
        }
        wkt += "(";
        let i6 = 0;
        while (i6 < this.geometries.length && wkt.length < truncate) {
          wkt += _indent(indent, depth + 1) + (this.geometries[i6] instanceof CircularString ? "CIRCULARSTRING " : "LINESTRING ") + _linestringToWKT(this.geometries[i6++].points, indent, truncate - wkt.length, depth + 1) + (i6 < this.geometries.length ? ", " : "");
        }
        return wkt + _indent(indent, depth) + ")";
      }
    };
    exports2.CompoundCurve = CompoundCurve;
    var MultiCurve = class extends Geometry {
      constructor(geometries, hasZ, hasM, srid) {
        super();
        __publicField(this, "geometries");
        __publicField(this, "hasZ");
        __publicField(this, "hasM");
        __publicField(this, "srid");
        this.geometries = geometries;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
      }
      toWKT(indent, truncate = Infinity, depth = 0) {
        let wkt = `${_sridWKTPrefix(this.srid, depth)}MULTICURVE${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.geometries.length === 0) {
          return wkt + "EMPTY";
        }
        wkt += `(`;
        let i6 = 0;
        while (i6 < this.geometries.length && wkt.length < truncate) {
          wkt += _indent(indent, depth + 1) + this.geometries[i6++].toWKT(indent, truncate - wkt.length, depth + 1) + (i6 < this.geometries.length ? ", " : "");
        }
        return wkt + _indent(indent, depth) + ")";
      }
    };
    exports2.MultiCurve = MultiCurve;
    var Polygon = class extends Geometry {
      constructor(rings, hasZ, hasM, srid) {
        super();
        __publicField(this, "rings");
        __publicField(this, "hasZ");
        __publicField(this, "hasM");
        __publicField(this, "srid");
        this.rings = rings;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
        this._validate();
      }
      _validate() {
        if (this.rings.some((ring) => ring.points.length < 4 || !ring.points[0].equals(ring.points[ring.points.length - 1]))) {
          throw new Error("expected rings in Polygon to be closed and to have at least 4 points");
        }
      }
      toWKT(indent, truncate = Infinity, depth = 0) {
        const wkt = `${_sridWKTPrefix(this.srid, depth)}${this.constructor._wktName}${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.rings.length === 0) {
          return wkt + "EMPTY";
        }
        return wkt + _multilinestringToWKT(this.rings, indent, truncate - wkt.length, depth);
      }
    };
    __publicField(Polygon, "_wktName", "POLYGON");
    exports2.Polygon = Polygon;
    var Triangle = class extends Polygon {
      _validate() {
        if (this.rings.length > 1) {
          throw new Error("Triangle can only contain a single ring");
        }
        if (this.rings.some((ring) => ring.points.length !== 4 || !ring.points[0].equals(ring.points[ring.points.length - 1]))) {
          throw new Error("expected Triangle to be closed and to have exactly 4 points");
        }
      }
    };
    __publicField(Triangle, "_wktName", "TRIANGLE");
    exports2.Triangle = Triangle;
    var CurvePolygon = class extends Geometry {
      constructor(geometries, hasZ, hasM, srid) {
        super();
        __publicField(this, "geometries");
        __publicField(this, "hasZ");
        __publicField(this, "hasM");
        __publicField(this, "srid");
        this.geometries = geometries;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
        if (this.geometries.some((ring) => ring instanceof LineString && ring.points.length < 4 || (ring instanceof CompoundCurve ? !ring.geometries[0].points[0].equals(ring.geometries[ring.geometries.length - 1].points[ring.geometries[ring.geometries.length - 1].points.length - 1]) : !ring.points[0].equals(ring.points[ring.points.length - 1])))) {
          throw new Error("expected rings in CurvePolygon to be closed and LinearRings to have at least 4 points");
        }
      }
      toWKT(indent, truncate = Infinity, depth = 0) {
        let wkt = `${_sridWKTPrefix(this.srid, depth)}CURVEPOLYGON${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.geometries.length === 0) {
          return wkt + "EMPTY";
        }
        wkt += `(`;
        let i6 = 0;
        while (i6 < this.geometries.length && wkt.length < truncate) {
          wkt += _indent(indent, depth + 1) + this.geometries[i6++].toWKT(indent, truncate - wkt.length, depth + 1) + (i6 < this.geometries.length ? ", " : "");
        }
        return wkt + _indent(indent, depth) + ")";
      }
    };
    exports2.CurvePolygon = CurvePolygon;
    var MultiPolygon = class extends Geometry {
      constructor(geometries, hasZ, hasM, srid) {
        super();
        __publicField(this, "geometries");
        __publicField(this, "hasZ");
        __publicField(this, "hasM");
        __publicField(this, "srid");
        this.geometries = geometries;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
      }
      toWKT(indent, truncate = Infinity, depth = 0) {
        let wkt = `${_sridWKTPrefix(this.srid, depth)}${this.constructor._wktName}${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.geometries.length === 0) {
          return wkt + "EMPTY";
        }
        wkt += `(`;
        let i6 = 0;
        while (i6 < this.geometries.length && wkt.length < truncate) {
          wkt += _indent(indent, depth + 1) + _multilinestringToWKT(this.geometries[i6++].rings, indent, truncate - wkt.length, depth + 1) + (i6 < this.geometries.length ? ", " : "");
        }
        return wkt + _indent(indent, depth) + ")";
      }
    };
    __publicField(MultiPolygon, "_wktName", "MULTIPOLYGON");
    exports2.MultiPolygon = MultiPolygon;
    var PolyhedralSurface = class extends MultiPolygon {
    };
    __publicField(PolyhedralSurface, "_wktName", "POLYHEDRALSURFACE");
    exports2.PolyhedralSurface = PolyhedralSurface;
    var TriangulatedIrregularNetwork = class extends MultiPolygon {
    };
    __publicField(TriangulatedIrregularNetwork, "_wktName", "TIN");
    exports2.TriangulatedIrregularNetwork = TriangulatedIrregularNetwork;
    var MultiSurface = class extends Geometry {
      constructor(geometries, hasZ, hasM, srid) {
        super();
        __publicField(this, "geometries");
        __publicField(this, "hasZ");
        __publicField(this, "hasM");
        __publicField(this, "srid");
        this.geometries = geometries;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
      }
      toWKT(indent, truncate = Infinity, depth = 0) {
        let wkt = `${_sridWKTPrefix(this.srid, depth)}MULTISURFACE${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.geometries.length === 0) {
          return wkt + "EMPTY";
        }
        wkt += `(`;
        let i6 = 0;
        while (i6 < this.geometries.length && wkt.length < truncate) {
          wkt += _indent(indent, depth + 1) + this.geometries[i6++].toWKT(indent, truncate - wkt.length, depth + 1) + (i6 < this.geometries.length ? ", " : "");
        }
        return wkt + _indent(indent, depth) + ")";
      }
    };
    exports2.MultiSurface = MultiSurface;
    var GeometryCollection = class extends Geometry {
      constructor(geometries, hasZ, hasM, srid) {
        super();
        __publicField(this, "geometries");
        __publicField(this, "hasZ");
        __publicField(this, "hasM");
        __publicField(this, "srid");
        this.geometries = geometries;
        this.hasZ = hasZ;
        this.hasM = hasM;
        this.srid = srid;
      }
      toWKT(indent, truncate = Infinity, depth = 0) {
        let wkt = `${_sridWKTPrefix(this.srid, depth)}GEOMETRYCOLLECTION${_flagsToWKT(this.hasZ, this.hasM)} `;
        if (this.geometries.length === 0) {
          return wkt + "EMPTY";
        }
        wkt += `(`;
        let i6 = 0;
        while (i6 < this.geometries.length && wkt.length < truncate) {
          wkt += _indent(indent, depth + 1) + this.geometries[i6++].toWKT(indent, truncate - wkt.length, depth + 1) + (i6 < this.geometries.length ? ", " : "");
        }
        return wkt + _indent(indent, depth) + ")";
      }
    };
    exports2.GeometryCollection = GeometryCollection;
    var Box2D = class {
      constructor(min, max) {
        __publicField(this, "min");
        __publicField(this, "max");
        this.min = min;
        this.max = max;
      }
      toString() {
        return `BOX(${this.min[0]} ${this.min[1]}, ${this.max[0]} ${this.max[1]})`;
      }
    };
    exports2.Box2D = Box2D;
    var Box3D = class {
      constructor(min, max) {
        __publicField(this, "min");
        __publicField(this, "max");
        this.min = min;
        this.max = max;
      }
      toString() {
        return `BOX3D(${this.min[0]} ${this.min[1]} ${this.min[2]}, ${this.max[0]} ${this.max[1]} ${this.max[2]})`;
      }
    };
    exports2.Box3D = Box3D;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/postgis.js
var require_postgis2 = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/postgis.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PostgisBox3dCodec = exports2.PostgisBox2dCodec = exports2.PostgisGeometryCodec = void 0;
    var postgis_1 = require_postgis();
    var errors_1 = require_errors();
    var ifaces_1 = require_ifaces();
    var PostgisGeometryCodec = class extends ifaces_1.ScalarCodec {
      encode(buf, object, ctx) {
        if (ctx.hasOverload(this)) {
          const geomBuf = ctx.preEncode(this, object);
          buf.writeBytes(geomBuf);
        } else {
          if (!(object instanceof postgis_1.Geometry)) {
            throw new errors_1.InvalidArgumentError(`a Geometry object was expected, got "${object}"`);
          }
          const finalise = buf.writeDeferredSize();
          _encodeGeometry(buf, object);
          finalise();
        }
      }
      decode(buf, ctx) {
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, buf.consumeAsBuffer());
        }
        return _parseGeometry(buf);
      }
    };
    exports2.PostgisGeometryCodec = PostgisGeometryCodec;
    var PostgisBox2dCodec = class extends ifaces_1.ScalarCodec {
      encode(buf, object, ctx) {
        let min;
        let max;
        if (ctx.hasOverload(this)) {
          [min, max] = ctx.preEncode(this, object);
        } else {
          if (!(object instanceof postgis_1.Box2D)) {
            throw new errors_1.InvalidArgumentError(`a Box2D object was expected, got "${object}"`);
          }
          min = object.min;
          max = object.max;
        }
        const finalise = buf.writeDeferredSize();
        _encodeGeometry(buf, new postgis_1.Polygon([
          new postgis_1.LineString([
            new postgis_1.Point(min[0], min[1]),
            new postgis_1.Point(min[0], max[1]),
            new postgis_1.Point(max[0], max[1]),
            new postgis_1.Point(min[0], min[1])
          ], false, false, null)
        ], false, false, null));
        finalise();
      }
      decode(buf, ctx) {
        const poly = _parseGeometry(buf);
        if (poly.constructor !== postgis_1.Polygon || poly.hasZ || poly.rings.length !== 1 || poly.rings[0].points.length !== 5) {
          throw new errors_1.InternalClientError(`failed to decode ext::postgis::box2d type`);
        }
        const points = poly.rings[0].points;
        const min = [points[0].x, points[0].y];
        const max = [points[2].x, points[2].y];
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, [min, max]);
        }
        return new postgis_1.Box2D(min, max);
      }
    };
    exports2.PostgisBox2dCodec = PostgisBox2dCodec;
    var PostgisBox3dCodec = class extends ifaces_1.ScalarCodec {
      encode(buf, object, ctx) {
        let min;
        let max;
        if (ctx.hasOverload(this)) {
          [min, max] = ctx.preEncode(this, object);
        } else {
          if (!(object instanceof postgis_1.Box3D)) {
            throw new errors_1.InvalidArgumentError(`a Box3D object was expected, got "${object}"`);
          }
          min = object.min;
          max = object.max;
        }
        const finalise = buf.writeDeferredSize();
        _encodeGeometry(buf, new postgis_1.Polygon([
          new postgis_1.LineString([
            new postgis_1.Point(min[0], min[1], min[2]),
            new postgis_1.Point(min[0], max[1], max[2]),
            new postgis_1.Point(max[0], max[1], max[2]),
            new postgis_1.Point(min[0], min[1], min[2])
          ], true, false, null)
        ], true, false, null));
        finalise();
      }
      decode(buf, ctx) {
        const poly = _parseGeometry(buf);
        let min;
        let max;
        if (poly.constructor === postgis_1.Polygon && poly.rings.length === 1 && poly.rings[0].points.length === 5) {
          const points = poly.rings[0].points;
          min = points[0];
          max = points[2];
        } else if (poly.constructor === postgis_1.PolyhedralSurface && poly.geometries.length === 6 && poly.geometries[0].rings.length === 1 && poly.geometries[0].rings[0].points.length === 5) {
          min = poly.geometries[0].rings[0].points[0];
          max = poly.geometries[5].rings[0].points[2];
        } else {
          throw new errors_1.InternalClientError(`failed to decode ext::postgis::box3d type`);
        }
        if (ctx.hasOverload(this)) {
          return ctx.postDecode(this, [
            [min.x, min.y, min.z ?? 0],
            [max.x, max.y, max.z ?? 0]
          ]);
        }
        return new postgis_1.Box3D([min.x, min.y, min.z ?? 0], [max.x, max.y, max.z ?? 0]);
      }
    };
    exports2.PostgisBox3dCodec = PostgisBox3dCodec;
    var zFlag = 2147483648;
    var mFlag = 1073741824;
    var sridFlag = 536870912;
    var allFlags = zFlag | mFlag | sridFlag;
    function _parseGeometry(buf, srid = null) {
      const le = buf.readUInt8() === 1;
      let type = buf.readUInt32(le);
      const z2 = (type & zFlag) !== 0;
      const m6 = (type & mFlag) !== 0;
      if ((type & sridFlag) !== 0) {
        srid = buf.readUInt32(le);
      }
      type = type & ~allFlags;
      switch (type) {
        case 1:
          return _parsePoint(buf, le, z2, m6, srid);
        case 2:
          return _parseLineString(buf, postgis_1.LineString, le, z2, m6, srid);
        case 3:
          return _parsePolygon(buf, postgis_1.Polygon, le, z2, m6, srid);
        case 4:
          return _parseMultiPoint(buf, le, z2, m6, srid);
        case 5:
          return _parseMultiLineString(buf, le, z2, m6, srid);
        case 6:
          return _parseMultiPolygon(buf, postgis_1.MultiPolygon, le, z2, m6, srid);
        case 7:
          return _parseGeometryCollection(buf, le, z2, m6, srid);
        case 8:
          return _parseLineString(buf, postgis_1.CircularString, le, z2, m6, srid);
        case 9:
          return _parseCompoundCurve(buf, le, z2, m6, srid);
        case 10:
          return _parseMultiCurve(buf, postgis_1.CurvePolygon, le, z2, m6, srid);
        case 11:
          return _parseMultiCurve(buf, postgis_1.MultiCurve, le, z2, m6, srid);
        case 12:
          return _parseMultiSurface(buf, le, z2, m6, srid);
        case 15:
          return _parseMultiPolygon(buf, postgis_1.PolyhedralSurface, le, z2, m6, srid);
        case 16:
          return _parseMultiPolygon(buf, postgis_1.TriangulatedIrregularNetwork, le, z2, m6, srid);
        case 17:
          return _parsePolygon(buf, postgis_1.Triangle, le, z2, m6, srid);
        default:
          throw new Error(`unsupported wkb type: ${type}`);
      }
    }
    function _parsePoint(buf, le, z2, m6, srid) {
      return new postgis_1.Point(buf.readFloat64(le), buf.readFloat64(le), z2 ? buf.readFloat64(le) : null, m6 ? buf.readFloat64(le) : null, srid);
    }
    function _parseLineString(buf, cls, le, z2, m6, srid) {
      const pointCount = buf.readUInt32(le);
      const points = new Array(pointCount);
      for (let i6 = 0; i6 < pointCount; i6++) {
        points[i6] = _parsePoint(buf, le, z2, m6, srid);
      }
      return new cls(points, z2, m6, srid);
    }
    function _parsePolygon(buf, cls, le, z2, m6, srid) {
      const ringCount = buf.readUInt32(le);
      const rings = new Array(ringCount);
      for (let i6 = 0; i6 < ringCount; i6++) {
        rings[i6] = _parseLineString(buf, postgis_1.LineString, le, z2, m6, srid);
      }
      return new cls(rings, z2, m6, srid);
    }
    function _parseMultiPoint(buf, le, z2, m6, srid) {
      const pointCount = buf.readUInt32(le);
      const points = new Array(pointCount);
      for (let i6 = 0; i6 < pointCount; i6++) {
        buf.discard(5);
        points[i6] = _parsePoint(buf, le, z2, m6, srid);
      }
      return new postgis_1.MultiPoint(points, z2, m6, srid);
    }
    function _parseMultiLineString(buf, le, z2, m6, srid) {
      const lineStringCount = buf.readUInt32(le);
      const lineStrings = new Array(lineStringCount);
      for (let i6 = 0; i6 < lineStringCount; i6++) {
        buf.discard(5);
        lineStrings[i6] = _parseLineString(buf, postgis_1.LineString, le, z2, m6, srid);
      }
      return new postgis_1.MultiLineString(lineStrings, z2, m6, srid);
    }
    function _parseCompoundCurve(buf, le, z2, m6, srid) {
      const curveCount = buf.readUInt32(le);
      const curves = new Array(curveCount);
      for (let i6 = 0; i6 < curveCount; i6++) {
        buf.discard(1);
        const type = buf.readUInt32(le) & ~allFlags;
        switch (type) {
          case 2:
            curves[i6] = _parseLineString(buf, postgis_1.LineString, le, z2, m6, srid);
            break;
          case 8:
            curves[i6] = _parseLineString(buf, postgis_1.CircularString, le, z2, m6, srid);
            break;
          default:
            throw new Error(`unexpected type ${type} in CompoundCurve`);
        }
      }
      return new postgis_1.CompoundCurve(curves, z2, m6, srid);
    }
    function _parseMultiCurve(buf, cls, le, z2, m6, srid) {
      const curveCount = buf.readUInt32(le);
      const curves = new Array(curveCount);
      for (let i6 = 0; i6 < curveCount; i6++) {
        buf.discard(1);
        const type = buf.readUInt32(le) & ~allFlags;
        switch (type) {
          case 2:
            curves[i6] = _parseLineString(buf, postgis_1.LineString, le, z2, m6, srid);
            break;
          case 8:
            curves[i6] = _parseLineString(buf, postgis_1.CircularString, le, z2, m6, srid);
            break;
          case 9:
            curves[i6] = _parseCompoundCurve(buf, le, z2, m6, srid);
            break;
          default:
            throw new Error(`unexpected type ${type} in MultiCurve/CurvePolygon`);
        }
      }
      return new cls(curves, z2, m6, srid);
    }
    function _parseMultiPolygon(buf, cls, le, z2, m6, srid) {
      const polyCls = cls === postgis_1.TriangulatedIrregularNetwork ? postgis_1.Triangle : postgis_1.Polygon;
      const polyCount = buf.readUInt32(le);
      const polys = new Array(polyCount);
      for (let i6 = 0; i6 < polyCount; i6++) {
        buf.discard(5);
        polys[i6] = _parsePolygon(buf, polyCls, le, z2, m6, srid);
      }
      return new cls(polys, z2, m6, srid);
    }
    function _parseMultiSurface(buf, le, z2, m6, srid) {
      const surfaceCount = buf.readUInt32(le);
      const surfaces = new Array(surfaceCount);
      for (let i6 = 0; i6 < surfaceCount; i6++) {
        buf.discard(1);
        const type = buf.readUInt32(le) & ~allFlags;
        switch (type) {
          case 3:
            surfaces[i6] = _parsePolygon(buf, postgis_1.Polygon, le, z2, m6, srid);
            break;
          case 10:
            surfaces[i6] = _parseMultiCurve(buf, postgis_1.CurvePolygon, le, z2, m6, srid);
            break;
          default:
            throw new Error(`unexpected type ${type} in MultiSurface`);
        }
      }
      return new postgis_1.MultiSurface(surfaces, z2, m6, srid);
    }
    function _parseGeometryCollection(buf, le, z2, m6, srid) {
      const geometryCount = buf.readUInt32(le);
      const geometries = new Array(geometryCount);
      for (let i6 = 0; i6 < geometryCount; i6++) {
        geometries[i6] = _parseGeometry(buf, srid);
      }
      return new postgis_1.GeometryCollection(geometries, z2, m6, srid);
    }
    var geomTypes = /* @__PURE__ */ new Map([
      [postgis_1.Point, 1],
      [postgis_1.LineString, 2],
      [postgis_1.Polygon, 3],
      [postgis_1.MultiPoint, 4],
      [postgis_1.MultiLineString, 5],
      [postgis_1.MultiPolygon, 6],
      [postgis_1.GeometryCollection, 7],
      [postgis_1.CircularString, 8],
      [postgis_1.CompoundCurve, 9],
      [postgis_1.CurvePolygon, 10],
      [postgis_1.MultiCurve, 11],
      [postgis_1.MultiSurface, 12],
      [postgis_1.PolyhedralSurface, 15],
      [postgis_1.TriangulatedIrregularNetwork, 16],
      [postgis_1.Triangle, 17]
    ]);
    function _encodeGeometry(buf, geom) {
      buf.writeUInt8(0);
      const type = geomTypes.get(geom.constructor);
      if (!type) {
        throw new Error(`unknown geometry type ${geom}`);
      }
      buf.writeUInt32(type | (geom.hasZ ? zFlag : 0) | (geom.hasM ? mFlag : 0) | (geom.srid !== null ? sridFlag : 0));
      if (geom.srid !== null) {
        buf.writeUInt32(geom.srid);
      }
      if (geom instanceof postgis_1.Point) {
        _encodePoint(buf, geom);
        return;
      }
      if (geom instanceof postgis_1.LineString) {
        _encodeLineString(buf, geom);
        return;
      }
      if (geom instanceof postgis_1.Polygon) {
        buf.writeUInt32(geom.rings.length);
        for (const ring of geom.rings) {
          _encodeLineString(buf, ring);
        }
        return;
      }
      buf.writeUInt32(geom.geometries.length);
      for (const point of geom.geometries) {
        _encodeGeometry(buf, point);
      }
    }
    function _encodePoint(buf, point) {
      buf.writeFloat64(point.x);
      buf.writeFloat64(point.y);
      if (point.z !== null)
        buf.writeFloat64(point.z);
      if (point.m !== null)
        buf.writeFloat64(point.m);
    }
    function _encodeLineString(buf, linestring) {
      buf.writeUInt32(linestring.points.length);
      for (const point of linestring.points) {
        _encodePoint(buf, point);
      }
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/codecs.js
var require_codecs = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/codecs.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.INVALID_CODEC = exports2.NULL_CODEC = exports2.SCALAR_CODECS = exports2.NullCodec = void 0;
    var buffer_1 = require_buffer();
    var boolean_1 = require_boolean();
    var ifaces_1 = require_ifaces();
    var numbers_1 = require_numbers();
    var numerics_1 = require_numerics();
    var text_1 = require_text();
    var uuid_1 = require_uuid();
    var bytes_1 = require_bytes();
    var json_1 = require_json();
    var datetime_1 = require_datetime2();
    var memory_1 = require_memory2();
    var pgvector_1 = require_pgvector2();
    var postgis_1 = require_postgis2();
    var errors_1 = require_errors();
    var consts_1 = require_consts();
    var NullCodec = class extends ifaces_1.Codec {
      encode(_buf, _object) {
        throw new errors_1.InternalClientError("null codec cannot used to encode data");
      }
      decode(_buf, _ctx) {
        throw new errors_1.InternalClientError("null codec cannot used to decode data");
      }
      getSubcodecs() {
        return [];
      }
      getKind() {
        return "scalar";
      }
    };
    __publicField(NullCodec, "BUFFER", new buffer_1.WriteBuffer().writeInt32(0).unwrap());
    exports2.NullCodec = NullCodec;
    exports2.SCALAR_CODECS = /* @__PURE__ */ new Map();
    exports2.NULL_CODEC = new NullCodec(consts_1.NULL_CODEC_ID);
    exports2.INVALID_CODEC = new NullCodec(consts_1.INVALID_CODEC_ID);
    function registerScalarCodecs(codecs) {
      for (const [typename, type] of Object.entries(codecs)) {
        const id = consts_1.KNOWN_TYPENAMES.get(typename);
        if (id == null) {
          throw new errors_1.InternalClientError("unknown type name");
        }
        exports2.SCALAR_CODECS.set(id, new type(id, typename));
      }
    }
    registerScalarCodecs({
      "std::int16": numbers_1.Int16Codec,
      "std::int32": numbers_1.Int32Codec,
      "std::int64": numbers_1.Int64Codec,
      "std::float32": numbers_1.Float32Codec,
      "std::float64": numbers_1.Float64Codec,
      "std::bigint": numerics_1.BigIntCodec,
      "std::decimal": numerics_1.DecimalStringCodec,
      "std::bool": boolean_1.BoolCodec,
      "std::json": json_1.JSONCodec,
      "std::str": text_1.StrCodec,
      "std::bytes": bytes_1.BytesCodec,
      "std::uuid": uuid_1.UUIDCodec,
      "cal::local_date": datetime_1.LocalDateCodec,
      "cal::local_time": datetime_1.LocalTimeCodec,
      "cal::local_datetime": datetime_1.LocalDateTimeCodec,
      "std::datetime": datetime_1.DateTimeCodec,
      "std::duration": datetime_1.DurationCodec,
      "cal::relative_duration": datetime_1.RelativeDurationCodec,
      "cal::date_duration": datetime_1.DateDurationCodec,
      "cfg::memory": memory_1.ConfigMemoryCodec,
      "std::pg::json": json_1.PgTextJSONCodec,
      "std::pg::timestamptz": datetime_1.DateTimeCodec,
      "std::pg::timestamp": datetime_1.LocalDateTimeCodec,
      "std::pg::date": datetime_1.LocalDateCodec,
      "std::pg::interval": datetime_1.RelativeDurationCodec,
      "ext::pgvector::vector": pgvector_1.PgVectorCodec,
      "ext::pgvector::halfvec": pgvector_1.PgVectorHalfVecCodec,
      "ext::pgvector::sparsevec": pgvector_1.PgVectorSparseVecCodec,
      "ext::postgis::geometry": postgis_1.PostgisGeometryCodec,
      "ext::postgis::geography": postgis_1.PostgisGeometryCodec,
      "ext::postgis::box2d": postgis_1.PostgisBox2dCodec,
      "ext::postgis::box3d": postgis_1.PostgisBox3dCodec
    });
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/tuple.js
var require_tuple = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/tuple.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.EMPTY_TUPLE_CODEC = exports2.EMPTY_TUPLE_CODEC_ID = exports2.EmptyTupleCodec = exports2.TupleCodec = void 0;
    var consts_1 = require_consts();
    var ifaces_1 = require_ifaces();
    var buffer_1 = require_buffer();
    var errors_1 = require_errors();
    var TupleCodec = class extends ifaces_1.Codec {
      constructor(tid, typeName, codecs) {
        super(tid);
        __publicField(this, "subCodecs");
        __publicField(this, "typeName");
        this.subCodecs = codecs;
        this.typeName = typeName;
      }
      encode(buf, object, ctx) {
        if (!Array.isArray(object)) {
          throw new errors_1.InvalidArgumentError(`an array was expected, got "${object}"`);
        }
        const codecs = this.subCodecs;
        const codecsLen = codecs.length;
        if (object.length !== codecsLen) {
          throw new errors_1.InvalidArgumentError(`expected ${codecsLen} tuple item${codecsLen === 1 ? "" : "s"}, got ${object.length}`);
        }
        if (!codecsLen) {
          buf.writeBuffer(EmptyTupleCodec.BUFFER);
        }
        const elemData = new buffer_1.WriteBuffer();
        for (let i6 = 0; i6 < codecsLen; i6++) {
          const elem = object[i6];
          elemData.writeInt32(0);
          if (elem == null) {
            throw new errors_1.MissingArgumentError(`element at index ${i6} in tuple cannot be 'null'`);
          } else {
            try {
              codecs[i6].encode(elemData, elem, ctx);
            } catch (e6) {
              if (e6 instanceof errors_1.QueryArgumentError) {
                throw new errors_1.InvalidArgumentError(`invalid element at index ${i6} in tuple: ${e6.message}`);
              } else {
                throw e6;
              }
            }
          }
        }
        const elemBuf = elemData.unwrap();
        buf.writeInt32(4 + elemBuf.length);
        buf.writeInt32(codecsLen);
        buf.writeBuffer(elemBuf);
      }
      decode(buf, ctx) {
        const els = buf.readUInt32();
        const subCodecs = this.subCodecs;
        if (els !== subCodecs.length) {
          throw new errors_1.ProtocolError(`cannot decode Tuple: expected ${subCodecs.length} elements, got ${els}`);
        }
        const elemBuf = buffer_1.ReadBuffer.alloc();
        const result = new Array(els);
        for (let i6 = 0; i6 < els; i6++) {
          buf.discard(4);
          const elemLen = buf.readInt32();
          if (elemLen === -1) {
            result[i6] = null;
          } else {
            buf.sliceInto(elemBuf, elemLen);
            result[i6] = subCodecs[i6].decode(elemBuf, ctx);
            elemBuf.finish();
          }
        }
        return result;
      }
      getSubcodecs() {
        return Array.from(this.subCodecs);
      }
      getKind() {
        return "tuple";
      }
    };
    exports2.TupleCodec = TupleCodec;
    var EmptyTupleCodec = class extends ifaces_1.Codec {
      encode(buf, object, _ctx) {
        if (!Array.isArray(object)) {
          throw new errors_1.InvalidArgumentError("cannot encode empty Tuple: expected an array");
        }
        if (object.length) {
          throw new errors_1.InvalidArgumentError(`cannot encode empty Tuple: expected 0 elements got ${object.length}`);
        }
        buf.writeInt32(4);
        buf.writeInt32(0);
      }
      decode(buf) {
        const els = buf.readInt32();
        if (els !== 0) {
          throw new errors_1.ProtocolError(`cannot decode empty Tuple: expected 0 elements, received ${els}`);
        }
        return [];
      }
      getSubcodecs() {
        return [];
      }
      getKind() {
        return "tuple";
      }
    };
    __publicField(EmptyTupleCodec, "BUFFER", new buffer_1.WriteBuffer().writeInt32(4).writeInt32(0).unwrap());
    exports2.EmptyTupleCodec = EmptyTupleCodec;
    exports2.EMPTY_TUPLE_CODEC_ID = consts_1.KNOWN_TYPENAMES.get("empty-tuple");
    exports2.EMPTY_TUPLE_CODEC = new EmptyTupleCodec(exports2.EMPTY_TUPLE_CODEC_ID);
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/range.js
var require_range2 = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/range.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MultiRange = exports2.Range = void 0;
    var Range = class _Range {
      constructor(_lower, _upper, _incLower = _lower != null, _incUpper = false) {
        __publicField(this, "_lower");
        __publicField(this, "_upper");
        __publicField(this, "_incLower");
        __publicField(this, "_incUpper");
        __publicField(this, "_isEmpty", false);
        this._lower = _lower;
        this._upper = _upper;
        this._incLower = _incLower;
        this._incUpper = _incUpper;
      }
      get lower() {
        return this._lower;
      }
      get upper() {
        return this._upper;
      }
      get incLower() {
        return this._incLower;
      }
      get incUpper() {
        return this._incUpper;
      }
      get isEmpty() {
        return this._isEmpty;
      }
      static empty() {
        const range = new _Range(null, null);
        range._isEmpty = true;
        return range;
      }
      toJSON() {
        return this.isEmpty ? { empty: true } : {
          lower: this._lower,
          upper: this._upper,
          inc_lower: this._incLower,
          inc_upper: this._incUpper
        };
      }
    };
    exports2.Range = Range;
    var MultiRange = class {
      constructor(ranges = []) {
        __publicField(this, "_ranges");
        this._ranges = [...ranges];
      }
      get length() {
        return this._ranges.length;
      }
      *[Symbol.iterator]() {
        for (const range of this._ranges) {
          yield range;
        }
      }
      toJSON() {
        return [...this._ranges];
      }
    };
    exports2.MultiRange = MultiRange;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/range.js
var require_range3 = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/range.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MultiRangeCodec = exports2.RangeCodec = void 0;
    var ifaces_1 = require_ifaces();
    var buffer_1 = require_buffer();
    var range_1 = require_range2();
    var errors_1 = require_errors();
    var RangeFlags;
    (function(RangeFlags2) {
      RangeFlags2[RangeFlags2["EMPTY"] = 1] = "EMPTY";
      RangeFlags2[RangeFlags2["INC_LOWER"] = 2] = "INC_LOWER";
      RangeFlags2[RangeFlags2["INC_UPPER"] = 4] = "INC_UPPER";
      RangeFlags2[RangeFlags2["EMPTY_LOWER"] = 8] = "EMPTY_LOWER";
      RangeFlags2[RangeFlags2["EMPTY_UPPER"] = 16] = "EMPTY_UPPER";
    })(RangeFlags || (RangeFlags = {}));
    var MAXINT32 = 2147483647;
    function encodeRange(buf, obj, subCodec, ctx) {
      if (!(obj instanceof range_1.Range)) {
        throw new errors_1.InvalidArgumentError("a Range was expected");
      }
      const elemData = new buffer_1.WriteBuffer();
      if (obj.lower !== null) {
        subCodec.encode(elemData, obj.lower, ctx);
      }
      if (obj.upper !== null) {
        subCodec.encode(elemData, obj.upper, ctx);
      }
      const elemBuf = elemData.unwrap();
      buf.writeInt32(1 + elemBuf.length);
      buf.writeUInt8(obj.isEmpty ? RangeFlags.EMPTY : (obj.incLower ? RangeFlags.INC_LOWER : 0) | (obj.incUpper ? RangeFlags.INC_UPPER : 0) | (obj.lower === null ? RangeFlags.EMPTY_LOWER : 0) | (obj.upper === null ? RangeFlags.EMPTY_UPPER : 0));
      buf.writeBuffer(elemBuf);
    }
    function decodeRange(buf, subCodec, ctx) {
      const flags = buf.readUInt8();
      if (flags & RangeFlags.EMPTY) {
        return range_1.Range.empty();
      }
      const elemBuf = buffer_1.ReadBuffer.alloc();
      let lower2 = null;
      let upper = null;
      if (!(flags & RangeFlags.EMPTY_LOWER)) {
        buf.sliceInto(elemBuf, buf.readInt32());
        lower2 = subCodec.decode(elemBuf, ctx);
        elemBuf.finish();
      }
      if (!(flags & RangeFlags.EMPTY_UPPER)) {
        buf.sliceInto(elemBuf, buf.readInt32());
        upper = subCodec.decode(elemBuf, ctx);
        elemBuf.finish();
      }
      return new range_1.Range(lower2, upper, !!(flags & RangeFlags.INC_LOWER), !!(flags & RangeFlags.INC_UPPER));
    }
    var RangeCodec = class extends ifaces_1.Codec {
      constructor(tid, typeName, subCodec) {
        super(tid);
        __publicField(this, "tsType", "Range");
        __publicField(this, "tsModule", "gel");
        __publicField(this, "subCodec");
        __publicField(this, "typeName");
        this.subCodec = subCodec;
        this.typeName = typeName;
      }
      encode(buf, obj, ctx) {
        return encodeRange(buf, obj, this.subCodec, ctx);
      }
      decode(buf, ctx) {
        return decodeRange(buf, this.subCodec, ctx);
      }
      getSubcodecs() {
        return [this.subCodec];
      }
      getKind() {
        return "range";
      }
    };
    exports2.RangeCodec = RangeCodec;
    var MultiRangeCodec = class extends ifaces_1.Codec {
      constructor(tid, typeName, subCodec) {
        super(tid);
        __publicField(this, "tsType", "MultiRange");
        __publicField(this, "tsModule", "gel");
        __publicField(this, "subCodec");
        __publicField(this, "typeName");
        this.subCodec = subCodec;
        this.typeName = typeName;
      }
      encode(buf, obj, ctx) {
        if (!(obj instanceof range_1.MultiRange)) {
          throw new TypeError(`a MultiRange expected (got type ${obj.constructor.name})`);
        }
        const objLen = obj.length;
        if (objLen > MAXINT32) {
          throw new errors_1.InvalidArgumentError("too many elements in array");
        }
        const elemData = new buffer_1.WriteBuffer();
        for (const item of obj) {
          try {
            encodeRange(elemData, item, this.subCodec, ctx);
          } catch (e6) {
            if (e6 instanceof errors_1.InvalidArgumentError) {
              throw new errors_1.InvalidArgumentError(`invalid multirange element: ${e6.message}`);
            } else {
              throw e6;
            }
          }
        }
        const elemBuf = elemData.unwrap();
        const elemDataLen = elemBuf.length;
        if (elemDataLen > MAXINT32 - 4) {
          throw new errors_1.InvalidArgumentError(`size of encoded multirange datum exceeds the maximum allowed ${MAXINT32 - 4} bytes`);
        }
        buf.writeInt32(4 + elemDataLen);
        buf.writeInt32(objLen);
        buf.writeBuffer(elemBuf);
      }
      decode(buf, ctx) {
        const elemCount = buf.readInt32();
        const result = new Array(elemCount);
        const elemBuf = buffer_1.ReadBuffer.alloc();
        const subCodec = this.subCodec;
        for (let i6 = 0; i6 < elemCount; i6++) {
          const elemLen = buf.readInt32();
          if (elemLen === -1) {
            throw new errors_1.ProtocolError("unexpected NULL element in multirange value");
          } else {
            buf.sliceInto(elemBuf, elemLen);
            const elem = decodeRange(elemBuf, subCodec, ctx);
            if (elemBuf.length) {
              throw new errors_1.ProtocolError(`unexpected trailing data in buffer after multirange element decoding: ${elemBuf.length}`);
            }
            result[i6] = elem;
            elemBuf.finish();
          }
        }
        return new range_1.MultiRange(result);
      }
      getSubcodecs() {
        return [this.subCodec];
      }
      getKind() {
        return "multirange";
      }
    };
    exports2.MultiRangeCodec = MultiRangeCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/namedtuple.js
var require_namedtuple = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/namedtuple.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NamedTupleCodec = void 0;
    var ifaces_1 = require_ifaces();
    var buffer_1 = require_buffer();
    var errors_1 = require_errors();
    var NamedTupleCodec = class extends ifaces_1.Codec {
      constructor(tid, typeName, codecs, names) {
        super(tid);
        __publicField(this, "subCodecs");
        __publicField(this, "names");
        __publicField(this, "typeName");
        this.subCodecs = codecs;
        this.names = names;
        this.typeName = typeName;
      }
      encode(buf, object, ctx) {
        if (typeof object !== "object" || Array.isArray(object)) {
          throw new errors_1.InvalidArgumentError(`an object was expected, got "${object}"`);
        }
        const codecsLen = this.subCodecs.length;
        if (Object.keys(object).length !== codecsLen) {
          throw new errors_1.QueryArgumentError(`expected ${codecsLen} element${codecsLen === 1 ? "" : "s"} in named tuple, got ${Object.keys(object).length}`);
        }
        const elemData = new buffer_1.WriteBuffer();
        for (let i6 = 0; i6 < codecsLen; i6++) {
          const key = this.names[i6];
          const val2 = object[key];
          if (val2 == null) {
            throw new errors_1.MissingArgumentError(`element '${key}' in named tuple cannot be 'null'`);
          } else {
            elemData.writeInt32(0);
            try {
              this.subCodecs[i6].encode(elemData, val2, ctx);
            } catch (e6) {
              if (e6 instanceof errors_1.QueryArgumentError) {
                throw new errors_1.InvalidArgumentError(`invalid element '${key}' in named tuple: ${e6.message}`);
              } else {
                throw e6;
              }
            }
          }
        }
        const elemBuf = elemData.unwrap();
        buf.writeInt32(4 + elemBuf.length);
        buf.writeInt32(codecsLen);
        buf.writeBuffer(elemBuf);
      }
      decode(buf, ctx) {
        const els = buf.readUInt32();
        const subCodecs = this.subCodecs;
        if (els !== subCodecs.length) {
          throw new errors_1.ProtocolError(`cannot decode NamedTuple: expected ${subCodecs.length} elements, got ${els}`);
        }
        const elemBuf = buffer_1.ReadBuffer.alloc();
        const names = this.names;
        const result = {};
        for (let i6 = 0; i6 < els; i6++) {
          buf.discard(4);
          const elemLen = buf.readInt32();
          let val2 = null;
          if (elemLen !== -1) {
            buf.sliceInto(elemBuf, elemLen);
            val2 = subCodecs[i6].decode(elemBuf, ctx);
            elemBuf.finish();
          }
          result[names[i6]] = val2;
        }
        return result;
      }
      getSubcodecs() {
        return Array.from(this.subCodecs);
      }
      getNames() {
        return Array.from(this.names);
      }
      getKind() {
        return "namedtuple";
      }
    };
    exports2.NamedTupleCodec = NamedTupleCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/array.js
var require_array = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/array.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ArrayCodec = void 0;
    var ifaces_1 = require_ifaces();
    var buffer_1 = require_buffer();
    var tuple_1 = require_tuple();
    var range_1 = require_range3();
    var errors_1 = require_errors();
    var namedtuple_1 = require_namedtuple();
    var ArrayCodec = class extends ifaces_1.Codec {
      constructor(tid, typeName, subCodec, len) {
        super(tid);
        __publicField(this, "subCodec");
        __publicField(this, "len");
        __publicField(this, "typeName");
        this.subCodec = subCodec;
        this.len = len;
        this.typeName = typeName;
      }
      encode(buf, obj, ctx) {
        if (!(this.subCodec instanceof ifaces_1.ScalarCodec || this.subCodec instanceof tuple_1.TupleCodec || this.subCodec instanceof namedtuple_1.NamedTupleCodec || this.subCodec instanceof range_1.RangeCodec || this.subCodec instanceof range_1.MultiRangeCodec)) {
          throw new errors_1.InvalidArgumentError("only arrays of scalars or tuples are supported");
        }
        if (!Array.isArray(obj) && !isTypedArray(obj)) {
          throw new errors_1.InvalidArgumentError(`an array was expected (got type ${obj.constructor.name})`);
        }
        const subCodec = this.subCodec;
        const elemData = new buffer_1.WriteBuffer();
        const objLen = obj.length;
        if (objLen > 2147483647) {
          throw new errors_1.InvalidArgumentError("too many elements in array");
        }
        for (let i6 = 0; i6 < objLen; i6++) {
          const item = obj[i6];
          if (item == null) {
            elemData.writeInt32(-1);
          } else {
            subCodec.encode(elemData, item, ctx);
          }
        }
        const elemBuf = elemData.unwrap();
        buf.writeInt32(12 + 8 + elemBuf.length);
        buf.writeInt32(1);
        buf.writeInt32(0);
        buf.writeInt32(0);
        buf.writeInt32(objLen);
        buf.writeInt32(1);
        buf.writeBuffer(elemBuf);
      }
      decode(buf, ctx) {
        const ndims = buf.readInt32();
        buf.discard(4);
        buf.discard(4);
        if (ndims === 0) {
          return [];
        }
        if (ndims !== 1) {
          throw new errors_1.ProtocolError("only 1-dimensional arrays are supported");
        }
        const len = buf.readUInt32();
        if (this.len !== -1 && len !== this.len) {
          throw new errors_1.ProtocolError(`invalid array size: received ${len}, expected ${this.len}`);
        }
        buf.discard(4);
        const result = new Array(len);
        const elemBuf = buffer_1.ReadBuffer.alloc();
        const subCodec = this.subCodec;
        for (let i6 = 0; i6 < len; i6++) {
          const elemLen = buf.readInt32();
          if (elemLen === -1) {
            result[i6] = null;
          } else {
            buf.sliceInto(elemBuf, elemLen);
            result[i6] = subCodec.decode(elemBuf, ctx);
            elemBuf.finish();
          }
        }
        return result;
      }
      getSubcodecs() {
        return [this.subCodec];
      }
      getKind() {
        return "array";
      }
    };
    exports2.ArrayCodec = ArrayCodec;
    function isTypedArray(obj) {
      return !!(obj.buffer instanceof ArrayBuffer && obj.BYTES_PER_ELEMENT);
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/enum.js
var require_enum = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/enum.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.EnumCodec = void 0;
    var text_1 = require_text();
    var EnumCodec = class extends text_1.StrCodec {
      constructor(tid, typeName, values) {
        super(tid, typeName);
        __publicField(this, "values");
        this.values = values;
      }
    };
    exports2.EnumCodec = EnumCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/ifaces.js
var require_ifaces2 = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/ifaces.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      var desc = Object.getOwnPropertyDescriptor(m6, k5);
      if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m6[k5];
        } };
      }
      Object.defineProperty(o5, k22, desc);
    } : function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      o5[k22] = m6[k5];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v6) {
      Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
    } : function(o5, v6) {
      o5["default"] = v6;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Language = exports2.Cardinality = exports2.OutputFormat = void 0;
    var chars = __importStar(require_chars());
    var OutputFormat;
    (function(OutputFormat2) {
      OutputFormat2[OutputFormat2["BINARY"] = chars.$b] = "BINARY";
      OutputFormat2[OutputFormat2["JSON"] = chars.$j] = "JSON";
      OutputFormat2[OutputFormat2["NONE"] = chars.$n] = "NONE";
    })(OutputFormat || (exports2.OutputFormat = OutputFormat = {}));
    var Cardinality;
    (function(Cardinality2) {
      Cardinality2[Cardinality2["NO_RESULT"] = chars.$n] = "NO_RESULT";
      Cardinality2[Cardinality2["AT_MOST_ONE"] = chars.$o] = "AT_MOST_ONE";
      Cardinality2[Cardinality2["ONE"] = chars.$A] = "ONE";
      Cardinality2[Cardinality2["MANY"] = chars.$m] = "MANY";
      Cardinality2[Cardinality2["AT_LEAST_ONE"] = chars.$M] = "AT_LEAST_ONE";
    })(Cardinality || (exports2.Cardinality = Cardinality = {}));
    var Language;
    (function(Language2) {
      Language2[Language2["EDGEQL"] = chars.$E] = "EDGEQL";
      Language2[Language2["SQL"] = chars.$S] = "SQL";
    })(Language || (exports2.Language = Language = {}));
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/object.js
var require_object = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/object.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ObjectCodec = void 0;
    var ifaces_1 = require_ifaces2();
    var ifaces_2 = require_ifaces();
    var buffer_1 = require_buffer();
    var errors_1 = require_errors();
    var EDGE_POINTER_IS_IMPLICIT = 1 << 0;
    var EDGE_POINTER_IS_LINKPROP = 1 << 1;
    var ObjectCodec = class extends ifaces_2.Codec {
      constructor(tid, codecs, names, flags, cards) {
        super(tid);
        __publicField(this, "codecs");
        __publicField(this, "fields");
        __publicField(this, "namesSet");
        __publicField(this, "cardinalities");
        this.codecs = codecs;
        this.fields = new Array(names.length);
        this.namesSet = /* @__PURE__ */ new Set();
        this.cardinalities = cards;
        for (let i6 = 0; i6 < names.length; i6++) {
          const isLinkprop = !!(flags[i6] & EDGE_POINTER_IS_LINKPROP);
          const name = isLinkprop ? `@${names[i6]}` : names[i6];
          this.fields[i6] = {
            name,
            implicit: !!(flags[i6] & EDGE_POINTER_IS_IMPLICIT),
            linkprop: isLinkprop,
            cardinality: cards[i6]
          };
          this.namesSet.add(name);
        }
      }
      encode(_buf, _object) {
        throw new errors_1.InvalidArgumentError("Objects cannot be passed as arguments");
      }
      encodeArgs(args, ctx) {
        if (this.fields[0].name === "0" || this.fields[0].name === "1") {
          return this._encodePositionalArgs(args, ctx);
        }
        return this._encodeNamedArgs(args, ctx);
      }
      _encodePositionalArgs(args, ctx) {
        if (!Array.isArray(args)) {
          throw new errors_1.InvalidArgumentError("an array of arguments was expected");
        }
        const codecs = this.codecs;
        const codecsLen = codecs.length;
        if (args.length !== codecsLen) {
          throw new errors_1.QueryArgumentError(`expected ${codecsLen} argument${codecsLen === 1 ? "" : "s"}, got ${args.length}`);
        }
        const elemData = new buffer_1.WriteBuffer();
        for (let i6 = 0; i6 < codecsLen; i6++) {
          elemData.writeInt32(0);
          const arg = args[i6];
          if (arg == null) {
            const card = this.cardinalities[i6];
            if (card === ifaces_1.Cardinality.ONE || card === ifaces_1.Cardinality.AT_LEAST_ONE) {
              throw new errors_1.MissingArgumentError(`argument ${this.fields[i6].name} is required, but received ${arg}`);
            }
            elemData.writeInt32(-1);
          } else {
            const codec = codecs[i6];
            codec.encode(elemData, arg, ctx);
          }
        }
        const elemBuf = elemData.unwrap();
        const buf = new buffer_1.WriteBuffer();
        buf.writeInt32(4 + elemBuf.length);
        buf.writeInt32(codecsLen);
        buf.writeBuffer(elemBuf);
        return buf.unwrap();
      }
      _encodeNamedArgs(args, ctx) {
        if (args == null) {
          throw new errors_1.MissingArgumentError("One or more named arguments expected, received null");
        }
        const keys = Object.keys(args);
        const fields = this.fields;
        const namesSet = this.namesSet;
        const codecs = this.codecs;
        const codecsLen = codecs.length;
        if (keys.length > codecsLen) {
          const extraKeys = keys.filter((key) => !namesSet.has(key));
          throw new errors_1.UnknownArgumentError(`Unused named argument${extraKeys.length === 1 ? "" : "s"}: "${extraKeys.join('", "')}"`);
        }
        const elemData = new buffer_1.WriteBuffer();
        for (let i6 = 0; i6 < codecsLen; i6++) {
          const key = fields[i6].name;
          const val2 = args[key];
          elemData.writeInt32(0);
          if (val2 == null) {
            const card = this.cardinalities[i6];
            if (card === ifaces_1.Cardinality.ONE || card === ifaces_1.Cardinality.AT_LEAST_ONE) {
              throw new errors_1.MissingArgumentError(`argument ${this.fields[i6].name} is required, but received ${val2}`);
            }
            elemData.writeInt32(-1);
          } else {
            const codec = codecs[i6];
            codec.encode(elemData, val2, ctx);
          }
        }
        const elemBuf = elemData.unwrap();
        const buf = new buffer_1.WriteBuffer();
        buf.writeInt32(4 + elemBuf.length);
        buf.writeInt32(codecsLen);
        buf.writeBuffer(elemBuf);
        return buf.unwrap();
      }
      decode(buf, ctx) {
        const codecs = this.codecs;
        const fields = this.fields;
        const els = buf.readUInt32();
        if (els !== codecs.length) {
          throw new errors_1.ProtocolError(`cannot decode Object: expected ${codecs.length} elements, got ${els}`);
        }
        const elemBuf = buffer_1.ReadBuffer.alloc();
        const result = {};
        for (let i6 = 0; i6 < els; i6++) {
          buf.discard(4);
          const elemLen = buf.readInt32();
          const name = fields[i6].name;
          let val2 = null;
          if (elemLen !== -1) {
            buf.sliceInto(elemBuf, elemLen);
            val2 = codecs[i6].decode(elemBuf, ctx);
            elemBuf.finish();
          }
          result[name] = val2;
        }
        return result;
      }
      getSubcodecs() {
        return Array.from(this.codecs);
      }
      getFields() {
        return Array.from(this.fields);
      }
      getKind() {
        return "object";
      }
    };
    exports2.ObjectCodec = ObjectCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/set.js
var require_set = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/set.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SetCodec = void 0;
    var ifaces_1 = require_ifaces();
    var buffer_1 = require_buffer();
    var array_1 = require_array();
    var errors_1 = require_errors();
    var SetCodec = class extends ifaces_1.Codec {
      constructor(tid, subCodec) {
        super(tid);
        __publicField(this, "subCodec");
        this.subCodec = subCodec;
      }
      encode(_buf, _obj) {
        throw new errors_1.InvalidArgumentError("Sets cannot be passed in query arguments");
      }
      decode(buf, ctx) {
        if (this.subCodec instanceof array_1.ArrayCodec) {
          return this.decodeSetOfArrays(buf, ctx);
        } else {
          return this.decodeSet(buf, ctx);
        }
      }
      decodeSetOfArrays(buf, ctx) {
        const ndims = buf.readInt32();
        buf.discard(4);
        buf.discard(4);
        if (ndims === 0) {
          return [];
        }
        if (ndims !== 1) {
          throw new errors_1.ProtocolError(`expected 1-dimensional array of records of arrays`);
        }
        const len = buf.readUInt32();
        buf.discard(4);
        const result = new Array(len);
        const elemBuf = buffer_1.ReadBuffer.alloc();
        const subCodec = this.subCodec;
        for (let i6 = 0; i6 < len; i6++) {
          buf.discard(4);
          const recSize = buf.readUInt32();
          if (recSize !== 1) {
            throw new errors_1.ProtocolError("expected a record with a single element as an array set element envelope");
          }
          buf.discard(4);
          const elemLen = buf.readInt32();
          if (elemLen === -1) {
            throw new errors_1.ProtocolError("unexpected NULL value in array set element");
          }
          buf.sliceInto(elemBuf, elemLen);
          result[i6] = subCodec.decode(elemBuf, ctx);
          elemBuf.finish();
        }
        return result;
      }
      decodeSet(buf, ctx) {
        const ndims = buf.readInt32();
        buf.discard(4);
        buf.discard(4);
        if (ndims === 0) {
          return [];
        }
        if (ndims !== 1) {
          throw new errors_1.ProtocolError(`invalid set dimensinality: ${ndims}`);
        }
        const len = buf.readUInt32();
        buf.discard(4);
        const result = new Array(len);
        const elemBuf = buffer_1.ReadBuffer.alloc();
        const subCodec = this.subCodec;
        for (let i6 = 0; i6 < len; i6++) {
          const elemLen = buf.readInt32();
          if (elemLen === -1) {
            result[i6] = null;
          } else {
            buf.sliceInto(elemBuf, elemLen);
            result[i6] = subCodec.decode(elemBuf, ctx);
            elemBuf.finish();
          }
        }
        return result;
      }
      getSubcodecs() {
        return [this.subCodec];
      }
      getKind() {
        return "set";
      }
    };
    exports2.SetCodec = SetCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/record.js
var require_record = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/record.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RecordCodec = exports2.SQLRowModeObject = exports2.SQLRowModeArray = void 0;
    var ifaces_1 = require_ifaces();
    var buffer_1 = require_buffer();
    var errors_1 = require_errors();
    var SQLRowArrayCodec = {
      fromDatabase(values, _desc) {
        return values;
      },
      toDatabase() {
        throw new errors_1.InternalClientError("cannot encode SQL record as a query argument");
      }
    };
    var SQLRowObjectCodec = {
      fromDatabase(values, { names }) {
        return Object.fromEntries(names.map((key, index6) => [key, values[index6]]));
      },
      toDatabase() {
        throw new errors_1.InternalClientError("cannot encode SQL record as a query argument");
      }
    };
    exports2.SQLRowModeArray = {
      _private_sql_row: SQLRowArrayCodec
    };
    exports2.SQLRowModeObject = {
      _private_sql_row: SQLRowObjectCodec
    };
    var RecordCodec = class extends ifaces_1.Codec {
      constructor(tid, codecs, names) {
        super(tid);
        __publicField(this, "subCodecs");
        __publicField(this, "names");
        this.subCodecs = codecs;
        this.names = names;
      }
      encode(_buf, _object) {
        throw new errors_1.InvalidArgumentError("SQL records cannot be passed as arguments");
      }
      decode(buf, ctx) {
        const els = buf.readUInt32();
        const subCodecs = this.subCodecs;
        if (els !== subCodecs.length) {
          throw new errors_1.ProtocolError(`cannot decode Record: expected ${subCodecs.length} elements, got ${els}`);
        }
        const elemBuf = buffer_1.ReadBuffer.alloc();
        const overload = ctx.getContainerOverload("_private_sql_row");
        if (overload != null && overload !== SQLRowObjectCodec) {
          const result = new Array(els);
          for (let i6 = 0; i6 < els; i6++) {
            buf.discard(4);
            const elemLen = buf.readInt32();
            let val2 = null;
            if (elemLen !== -1) {
              buf.sliceInto(elemBuf, elemLen);
              val2 = subCodecs[i6].decode(elemBuf, ctx);
              elemBuf.finish();
            }
            result[i6] = val2;
          }
          if (overload !== SQLRowArrayCodec) {
            return overload.fromDatabase(result, { names: this.names });
          }
          return result;
        } else {
          const names = this.names;
          const result = {};
          for (let i6 = 0; i6 < els; i6++) {
            buf.discard(4);
            const elemLen = buf.readInt32();
            let val2 = null;
            if (elemLen !== -1) {
              buf.sliceInto(elemBuf, elemLen);
              val2 = subCodecs[i6].decode(elemBuf, ctx);
              elemBuf.finish();
            }
            result[names[i6]] = val2;
          }
          return result;
        }
      }
      getSubcodecs() {
        return Array.from(this.subCodecs);
      }
      getNames() {
        return Array.from(this.names);
      }
      getKind() {
        return "record";
      }
    };
    exports2.RecordCodec = RecordCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/sparseObject.js
var require_sparseObject = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/sparseObject.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SparseObjectCodec = void 0;
    var ifaces_1 = require_ifaces();
    var buffer_1 = require_buffer();
    var errors_1 = require_errors();
    var SparseObjectCodec = class extends ifaces_1.Codec {
      constructor(tid, codecs, names) {
        super(tid);
        __publicField(this, "codecs");
        __publicField(this, "names");
        this.codecs = codecs;
        this.names = names;
      }
      encode(buf, object, ctx) {
        const elemBuf = new buffer_1.WriteBuffer();
        let objLen = 0;
        for (const [key, val2] of Object.entries(object)) {
          if (val2 !== void 0) {
            const i6 = this.names.indexOf(key);
            if (i6 === -1) {
              throw new errors_1.UnknownArgumentError(this.names.length ? `invalid global '${key}', valid globals are ${this.names.map((n5) => `'${n5}'`).join(", ")}` : `invalid global '${key}', no valid globals exist`);
            }
            objLen += 1;
            elemBuf.writeInt32(i6);
            if (val2 === null) {
              elemBuf.writeInt32(-1);
            } else {
              this.codecs[i6].encode(elemBuf, val2, ctx);
            }
          }
        }
        const elemData = elemBuf.unwrap();
        buf.writeInt32(4 + elemData.length);
        buf.writeInt32(objLen);
        buf.writeBuffer(elemData);
      }
      decode(buf, ctx) {
        const codecs = this.codecs;
        const names = this.names;
        const els = buf.readUInt32();
        const elemBuf = buffer_1.ReadBuffer.alloc();
        const result = {};
        for (let _3 = 0; _3 < els; _3++) {
          const i6 = buf.readUInt32();
          const elemLen = buf.readInt32();
          const name = names[i6];
          let val2 = null;
          if (elemLen !== -1) {
            buf.sliceInto(elemBuf, elemLen);
            val2 = codecs[i6].decode(elemBuf, ctx);
            elemBuf.finish();
          }
          result[name] = val2;
        }
        return result;
      }
      getSubcodecs() {
        return Array.from(this.codecs);
      }
      getKind() {
        return "sparse_object";
      }
    };
    exports2.SparseObjectCodec = SparseObjectCodec;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/registry.js
var require_registry = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/registry.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.CodecsRegistry = void 0;
    var buffer_1 = require_buffer();
    var lru_1 = __importDefault(require_lru());
    var ifaces_1 = require_ifaces();
    var codecs_1 = require_codecs();
    var consts_1 = require_consts();
    var tuple_1 = require_tuple();
    var array_1 = require_array();
    var namedtuple_1 = require_namedtuple();
    var enum_1 = require_enum();
    var object_1 = require_object();
    var set_1 = require_set();
    var record_1 = require_record();
    var range_1 = require_range3();
    var utils_1 = require_utils2();
    var sparseObject_1 = require_sparseObject();
    var errors_1 = require_errors();
    var CODECS_CACHE_SIZE = 1e3;
    var CODECS_BUILD_CACHE_SIZE = 200;
    var CTYPE_SET = 0;
    var CTYPE_SHAPE = 1;
    var CTYPE_BASE_SCALAR = 2;
    var CTYPE_SCALAR = 3;
    var CTYPE_TUPLE = 4;
    var CTYPE_NAMEDTUPLE = 5;
    var CTYPE_ARRAY = 6;
    var CTYPE_ENUM = 7;
    var CTYPE_INPUT_SHAPE = 8;
    var CTYPE_RANGE = 9;
    var CTYPE_OBJECT = 10;
    var CTYPE_COMPOUND = 11;
    var CTYPE_MULTIRANGE = 12;
    var CTYPE_RECORD = 13;
    var CodecsRegistry = class {
      constructor() {
        __publicField(this, "codecsBuildCache");
        __publicField(this, "codecs");
        this.codecs = new lru_1.default({ capacity: CODECS_CACHE_SIZE });
        this.codecsBuildCache = new lru_1.default({ capacity: CODECS_BUILD_CACHE_SIZE });
      }
      hasCodec(typeId) {
        if (this.codecs.has(typeId)) {
          return true;
        }
        return typeId === consts_1.NULL_CODEC_ID || typeId === tuple_1.EMPTY_TUPLE_CODEC_ID;
      }
      getCodec(typeId) {
        const codec = this.codecs.get(typeId);
        if (codec != null) {
          return codec;
        }
        if (typeId === tuple_1.EMPTY_TUPLE_CODEC_ID) {
          return tuple_1.EMPTY_TUPLE_CODEC;
        }
        if (typeId === consts_1.NULL_CODEC_ID) {
          return codecs_1.NULL_CODEC;
        }
        return null;
      }
      buildCodec(spec, protocolVersion) {
        if (!(0, utils_1.versionGreaterThanOrEqual)(protocolVersion, [2, 0])) {
          throw new errors_1.UnsupportedProtocolVersionError("unsupported old protocol version v1; downgrade to the previous version of gel-js");
        }
        const frb = new buffer_1.ReadBuffer(spec);
        const codecsList = [];
        let codec = null;
        while (frb.length) {
          const descLen = frb.readInt32();
          const descBuf = buffer_1.ReadBuffer.alloc();
          frb.sliceInto(descBuf, descLen);
          codec = this._buildCodec(descBuf, codecsList);
          descBuf.finish("unexpected trailing data in type descriptor buffer");
          if (codec == null) {
            continue;
          }
          codecsList.push(codec);
          this.codecs.set(codec.tid, codec);
        }
        if (!codecsList.length) {
          throw new errors_1.InternalClientError("could not build a codec");
        }
        return codecsList[codecsList.length - 1];
      }
      _buildCodec(frb, cl) {
        const t6 = frb.readUInt8();
        const tid = frb.readUUID();
        let res = this.codecs.get(tid);
        if (res == null) {
          res = this.codecsBuildCache.get(tid);
        }
        if (res != null) {
          frb.discard(frb.length);
          return res;
        }
        switch (t6) {
          case CTYPE_BASE_SCALAR: {
            res = codecs_1.SCALAR_CODECS.get(tid);
            if (!res) {
              if (consts_1.KNOWN_TYPES.has(tid)) {
                throw new errors_1.InternalClientError(`no JS codec for ${consts_1.KNOWN_TYPES.get(tid)}`);
              }
              throw new errors_1.InternalClientError(`no JS codec for the type with ID ${tid}`);
            }
            if (!(res instanceof ifaces_1.ScalarCodec)) {
              throw new errors_1.ProtocolError("could not build scalar codec: base scalar is a non-scalar codec");
            }
            break;
          }
          case CTYPE_SHAPE:
          case CTYPE_INPUT_SHAPE: {
            if (t6 === CTYPE_SHAPE) {
              frb.readBoolean();
              frb.readUInt16();
            }
            const els = frb.readUInt16();
            const codecs = new Array(els);
            const names = new Array(els);
            const flags = new Array(els);
            const cards = new Array(els);
            for (let i6 = 0; i6 < els; i6++) {
              const flag = frb.readUInt32();
              const card = frb.readUInt8();
              const name = frb.readString();
              const pos = frb.readUInt16();
              const subCodec = cl[pos];
              if (subCodec == null) {
                throw new errors_1.ProtocolError("could not build object codec: missing subcodec");
              }
              codecs[i6] = subCodec;
              names[i6] = name;
              flags[i6] = flag;
              cards[i6] = card;
              if (t6 === CTYPE_SHAPE) {
                frb.readUInt16();
              }
            }
            res = t6 === CTYPE_INPUT_SHAPE ? new sparseObject_1.SparseObjectCodec(tid, codecs, names) : new object_1.ObjectCodec(tid, codecs, names, flags, cards);
            break;
          }
          case CTYPE_SET: {
            const pos = frb.readUInt16();
            const subCodec = cl[pos];
            if (subCodec == null) {
              throw new errors_1.ProtocolError("could not build set codec: missing subcodec");
            }
            res = new set_1.SetCodec(tid, subCodec);
            break;
          }
          case CTYPE_SCALAR: {
            const typeName = frb.readString();
            frb.readBoolean();
            const ancestorCount = frb.readUInt16();
            const ancestors = [];
            for (let i6 = 0; i6 < ancestorCount; i6++) {
              const ancestorPos = frb.readUInt16();
              const ancestorCodec = cl[ancestorPos];
              if (ancestorCodec == null) {
                throw new errors_1.ProtocolError("could not build scalar codec: missing a codec for base scalar");
              }
              if (!(ancestorCodec instanceof ifaces_1.ScalarCodec)) {
                throw new errors_1.ProtocolError(`a scalar codec expected for base scalar type, got ${ancestorCodec}`);
              }
              ancestors.push(ancestorCodec);
            }
            if (ancestorCount === 0) {
              res = codecs_1.SCALAR_CODECS.get(tid);
              if (res == null) {
                if (consts_1.KNOWN_TYPES.has(tid)) {
                  throw new errors_1.InternalClientError(`no JS codec for ${consts_1.KNOWN_TYPES.get(tid)}`);
                }
                throw new errors_1.InternalClientError(`no JS codec for the type with ID ${tid}`);
              }
            } else {
              const baseCodec = ancestors[ancestors.length - 1];
              res = baseCodec.derive(tid, typeName, ancestors);
            }
            break;
          }
          case CTYPE_ARRAY: {
            const typeName = frb.readString();
            frb.readBoolean();
            const ancestorCount = frb.readUInt16();
            for (let i6 = 0; i6 < ancestorCount; i6++) {
              frb.readUInt16();
            }
            const pos = frb.readUInt16();
            const els = frb.readUInt16();
            if (els !== 1) {
              throw new errors_1.ProtocolError("cannot handle arrays with more than one dimension");
            }
            const dimLen = frb.readInt32();
            const subCodec = cl[pos];
            if (subCodec == null) {
              throw new errors_1.ProtocolError("could not build array codec: missing subcodec");
            }
            res = new array_1.ArrayCodec(tid, typeName, subCodec, dimLen);
            break;
          }
          case CTYPE_TUPLE: {
            const typeName = frb.readString();
            frb.readBoolean();
            const ancestorCount = frb.readUInt16();
            for (let i6 = 0; i6 < ancestorCount; i6++) {
              frb.readUInt16();
            }
            const els = frb.readUInt16();
            if (els === 0) {
              res = tuple_1.EMPTY_TUPLE_CODEC;
            } else {
              const codecs = new Array(els);
              for (let i6 = 0; i6 < els; i6++) {
                const pos = frb.readUInt16();
                const subCodec = cl[pos];
                if (subCodec == null) {
                  throw new errors_1.ProtocolError("could not build tuple codec: missing subcodec");
                }
                codecs[i6] = subCodec;
              }
              res = new tuple_1.TupleCodec(tid, typeName, codecs);
            }
            break;
          }
          case CTYPE_NAMEDTUPLE: {
            const typeName = frb.readString();
            frb.readBoolean();
            const ancestorCount = frb.readUInt16();
            for (let i6 = 0; i6 < ancestorCount; i6++) {
              frb.readUInt16();
            }
            const els = frb.readUInt16();
            const codecs = new Array(els);
            const names = new Array(els);
            for (let i6 = 0; i6 < els; i6++) {
              names[i6] = frb.readString();
              const pos = frb.readUInt16();
              const subCodec = cl[pos];
              if (subCodec == null) {
                throw new errors_1.ProtocolError("could not build namedtuple codec: missing subcodec");
              }
              codecs[i6] = subCodec;
            }
            res = new namedtuple_1.NamedTupleCodec(tid, typeName, codecs, names);
            break;
          }
          case CTYPE_RECORD: {
            const els = frb.readUInt16();
            const codecs = new Array(els);
            const names = new Array(els);
            for (let i6 = 0; i6 < els; i6++) {
              names[i6] = frb.readString();
              const pos = frb.readUInt16();
              const subCodec = cl[pos];
              if (subCodec == null) {
                throw new errors_1.ProtocolError("could not build record codec: missing subcodec");
              }
              codecs[i6] = subCodec;
            }
            res = new record_1.RecordCodec(tid, codecs, names);
            break;
          }
          case CTYPE_ENUM: {
            const typeName = frb.readString();
            frb.readBoolean();
            const ancestorCount = frb.readUInt16();
            for (let i6 = 0; i6 < ancestorCount; i6++) {
              frb.readUInt16();
            }
            const els = frb.readUInt16();
            const values = [];
            for (let i6 = 0; i6 < els; i6++) {
              values.push(frb.readString());
            }
            res = new enum_1.EnumCodec(tid, typeName, values);
            break;
          }
          case CTYPE_RANGE: {
            const typeName = frb.readString();
            frb.readBoolean();
            const ancestorCount = frb.readUInt16();
            for (let i6 = 0; i6 < ancestorCount; i6++) {
              frb.readUInt16();
            }
            const pos = frb.readUInt16();
            const subCodec = cl[pos];
            if (subCodec == null) {
              throw new errors_1.ProtocolError("could not build range codec: missing subcodec");
            }
            res = new range_1.RangeCodec(tid, typeName, subCodec);
            break;
          }
          case CTYPE_OBJECT: {
            frb.discard(frb.length);
            res = codecs_1.NULL_CODEC;
            break;
          }
          case CTYPE_COMPOUND: {
            frb.discard(frb.length);
            res = codecs_1.NULL_CODEC;
            break;
          }
          case CTYPE_MULTIRANGE: {
            const typeName = frb.readString();
            frb.readBoolean();
            const ancestorCount = frb.readUInt16();
            for (let i6 = 0; i6 < ancestorCount; i6++) {
              frb.readUInt16();
            }
            const pos = frb.readUInt16();
            const subCodec = cl[pos];
            if (subCodec == null) {
              throw new errors_1.ProtocolError("could not build range codec: missing subcodec");
            }
            res = new range_1.MultiRangeCodec(tid, typeName, subCodec);
            break;
          }
        }
        if (res == null) {
          if (consts_1.KNOWN_TYPES.has(tid)) {
            throw new errors_1.InternalClientError(`could not build a codec for ${consts_1.KNOWN_TYPES.get(tid)} type`);
          } else {
            throw new errors_1.InternalClientError(`could not build a codec for ${tid} type`);
          }
        }
        this.codecsBuildCache.set(tid, res);
        return res;
      }
    };
    exports2.CodecsRegistry = CodecsRegistry;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/context.js
var require_context = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/context.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NOOP_CODEC_CONTEXT = exports2.CodecContext = void 0;
    var NOOP = {
      toDatabase(data) {
        return data;
      },
      fromDatabase(data) {
        return data;
      }
    };
    var CodecContext = class {
      constructor(spec) {
        __publicField(this, "spec");
        __publicField(this, "map");
        if (spec === null || spec.size === 0) {
          this.spec = null;
        } else {
          this.spec = spec;
        }
        this.map = /* @__PURE__ */ new Map();
      }
      initCodec(codec) {
        const specMap = this.spec;
        const targetTypeName = codec.typeName;
        const s6 = specMap.get(targetTypeName);
        if (s6 != null) {
          this.map.set(targetTypeName, s6);
          return s6;
        }
        const ancestors = codec.ancestors;
        if (ancestors == null) {
          this.map.set(targetTypeName, NOOP);
          return NOOP;
        }
        for (let i6 = 0; i6 < ancestors.length; i6++) {
          const parent = ancestors[i6];
          const s7 = specMap.get(parent.typeName);
          if (s7 != null) {
            this.map.set(targetTypeName, s7);
            return s7;
          }
        }
        this.map.set(targetTypeName, NOOP);
        return NOOP;
      }
      getContainerOverload(kind) {
        if (this.spec === null || !this.spec.size) {
          return;
        }
        return this.spec.get(kind);
      }
      hasOverload(codec) {
        if (this.spec === null || !this.spec.size) {
          return false;
        }
        const op = this.map.get(codec.typeName);
        if (op === NOOP) {
          return false;
        }
        if (op != null) {
          return true;
        }
        return this.initCodec(codec) !== NOOP;
      }
      postDecode(codec, value) {
        if (this.spec === null || !this.spec.size) {
          return value;
        }
        let op = this.map.get(codec.typeName);
        if (op === NOOP) {
          return value;
        }
        if (op == null) {
          op = this.initCodec(codec);
        }
        return op.fromDatabase(value);
      }
      preEncode(codec, value) {
        if (this.spec === null || !this.spec.size) {
          return value;
        }
        let op = this.map.get(codec.typeName);
        if (op === NOOP) {
          return value;
        }
        if (op == null) {
          op = this.initCodec(codec);
        }
        return op.toDatabase(value);
      }
    };
    exports2.CodecContext = CodecContext;
    exports2.NOOP_CODEC_CONTEXT = new CodecContext(null);
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/options.js
var require_options = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/options.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      var desc = Object.getOwnPropertyDescriptor(m6, k5);
      if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m6[k5];
        } };
      }
      Object.defineProperty(o5, k22, desc);
    } : function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      o5[k22] = m6[k5];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v6) {
      Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
    } : function(o5, v6) {
      o5["default"] = v6;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Options = exports2.TransactionOptions = exports2.RetryOptions = exports2.logWarnings = exports2.throwWarnings = exports2.RetryCondition = exports2.IsolationLevel = void 0;
    exports2.defaultBackoff = defaultBackoff;
    var errors = __importStar(require_errors());
    var buffer_1 = require_buffer();
    var record_1 = require_record();
    var context_1 = require_context();
    function defaultBackoff(attempt) {
      return 2 ** attempt * 100 + Math.random() * 100;
    }
    var IsolationLevel;
    (function(IsolationLevel2) {
      IsolationLevel2["Serializable"] = "Serializable";
      IsolationLevel2["RepeatableRead"] = "RepeatableRead";
      IsolationLevel2["PreferRepeatableRead"] = "PreferRepeatableRead";
    })(IsolationLevel || (exports2.IsolationLevel = IsolationLevel = {}));
    var RetryCondition;
    (function(RetryCondition2) {
      RetryCondition2[RetryCondition2["TransactionConflict"] = 0] = "TransactionConflict";
      RetryCondition2[RetryCondition2["NetworkError"] = 1] = "NetworkError";
    })(RetryCondition || (exports2.RetryCondition = RetryCondition = {}));
    var RetryRule = class {
      constructor(attempts, backoff) {
        __publicField(this, "attempts");
        __publicField(this, "backoff");
        this.attempts = attempts;
        this.backoff = backoff;
      }
    };
    var throwWarnings = (warnings) => {
      throw new AggregateError(warnings, formatWarnings(warnings));
    };
    exports2.throwWarnings = throwWarnings;
    var logWarnings = (warnings) => {
      const merged = new Error(formatWarnings(warnings));
      console.warn(Object.assign(merged, { name: "" }));
    };
    exports2.logWarnings = logWarnings;
    var formatWarnings = (warnings) => `warnings occurred while running query:
${warnings.map((warn) => warn.message).join("\n")}`;
    var RetryOptions = class _RetryOptions {
      constructor(attempts = 3, backoff = defaultBackoff) {
        __publicField(this, "default");
        __publicField(this, "overrides");
        this.default = new RetryRule(attempts, backoff);
        this.overrides = /* @__PURE__ */ new Map();
      }
      withRule(condition, attempts, backoff) {
        const def = this.default;
        const overrides = new Map(this.overrides);
        overrides.set(condition, new RetryRule(attempts ?? def.attempts, backoff ?? def.backoff));
        const result = Object.create(_RetryOptions.prototype);
        result.default = def;
        result.overrides = overrides;
        return result;
      }
      getRuleForException(err2) {
        let result;
        if (err2 instanceof errors.TransactionConflictError) {
          result = this.overrides.get(RetryCondition.TransactionConflict);
        } else if (err2 instanceof errors.ClientError) {
          result = this.overrides.get(RetryCondition.NetworkError);
        }
        return result ?? this.default;
      }
      static defaults() {
        return _retryOptionsDefault;
      }
    };
    exports2.RetryOptions = RetryOptions;
    var _retryOptionsDefault = new RetryOptions();
    var TransactionOptions = class {
      constructor({ isolation, readonly, deferrable } = {}) {
        __publicField(this, "isolation");
        __publicField(this, "readonly");
        __publicField(this, "deferrable");
        this.isolation = isolation;
        this.readonly = readonly;
        this.deferrable = deferrable;
      }
      isDefault() {
        return this.isolation === void 0 && this.readonly === void 0 && this.deferrable === void 0;
      }
      static defaults() {
        return _defaultTransactionOptions;
      }
    };
    exports2.TransactionOptions = TransactionOptions;
    var _defaultTransactionOptions = new TransactionOptions();
    var TAG_ANNOTATION_KEY = "tag";
    var _Options = class _Options {
      constructor({ retryOptions = RetryOptions.defaults(), transactionOptions = TransactionOptions.defaults(), warningHandler = exports2.logWarnings, module: module3 = "default", moduleAliases = {}, config = {}, globals = {}, codecs = {} } = {}) {
        __publicField(this, "module");
        __publicField(this, "moduleAliases");
        __publicField(this, "config");
        __publicField(this, "globals");
        __publicField(this, "retryOptions");
        __publicField(this, "transactionOptions");
        __publicField(this, "codecs");
        __publicField(this, "warningHandler");
        __publicField(this, "annotations", /* @__PURE__ */ new Map());
        __publicField(this, "cachedCodecContext", null);
        __publicField(this, "cachedCodecContextVer", -1);
        this.retryOptions = retryOptions;
        this.transactionOptions = transactionOptions;
        this.warningHandler = warningHandler;
        this.module = module3;
        this.moduleAliases = new Map(Object.entries(moduleAliases));
        this.config = new Map(Object.entries(config));
        this.globals = new Map(Object.entries(globals));
        this.codecs = new Map(Object.entries(codecs));
      }
      get tag() {
        return this.annotations.get(TAG_ANNOTATION_KEY) ?? null;
      }
      static signalSchemaChange() {
        this.schemaVersion += 1;
      }
      makeCodecContext() {
        if (this.codecs.size === 0) {
          return context_1.NOOP_CODEC_CONTEXT;
        }
        if (this.cachedCodecContextVer === _Options.schemaVersion) {
          return this.cachedCodecContext;
        }
        const ctx = new context_1.CodecContext(this.codecs);
        this.cachedCodecContext = ctx;
        this.cachedCodecContextVer = _Options.schemaVersion;
        return ctx;
      }
      _cloneWith(mergeOptions) {
        const clone2 = Object.create(_Options.prototype);
        clone2.annotations = this.annotations;
        clone2.retryOptions = mergeOptions.retryOptions ?? this.retryOptions;
        clone2.transactionOptions = mergeOptions.transactionOptions ?? this.transactionOptions;
        clone2.warningHandler = mergeOptions.warningHandler ?? this.warningHandler;
        if (mergeOptions.config != null) {
          clone2.config = new Map([
            ...this.config,
            ...Object.entries(mergeOptions.config)
          ]);
        } else {
          clone2.config = this.config;
        }
        if (mergeOptions.globals != null) {
          clone2.globals = new Map([
            ...this.globals,
            ...Object.entries(mergeOptions.globals)
          ]);
        } else {
          clone2.globals = this.globals;
        }
        if (mergeOptions.moduleAliases != null) {
          clone2.moduleAliases = new Map([
            ...this.moduleAliases,
            ...Object.entries(mergeOptions.moduleAliases)
          ]);
        } else {
          clone2.moduleAliases = this.moduleAliases;
        }
        if (mergeOptions.codecs != null) {
          clone2.codecs = new Map([
            ...this.codecs,
            ...Object.entries(mergeOptions.codecs)
          ]);
        } else {
          clone2.codecs = this.codecs;
          clone2.cachedCodecContext = this.cachedCodecContext;
          clone2.cachedCodecContextVer = this.cachedCodecContextVer;
        }
        if (mergeOptions._dropSQLRowCodec && clone2.codecs.has("_private_sql_row")) {
          if (clone2.codecs === this.codecs) {
            clone2.codecs = new Map(clone2.codecs);
            clone2.cachedCodecContext = null;
            clone2.cachedCodecContextVer = -1;
          }
          clone2.codecs.delete("_private_sql_row");
        }
        clone2.module = mergeOptions.module ?? this.module;
        return clone2;
      }
      _serialise() {
        const state2 = {};
        if (this.module !== "default") {
          state2.module = this.module;
        }
        if (this.moduleAliases.size) {
          state2.aliases = Array.from(this.moduleAliases.entries());
        }
        if (this.config.size) {
          state2.config = Object.fromEntries(this.config.entries());
        }
        if (this.globals.size) {
          const globs = {};
          for (const [key, val2] of this.globals.entries()) {
            globs[key.includes("::") ? key : `${this.module}::${key}`] = val2;
          }
          state2.globals = globs;
        }
        return state2;
      }
      withModuleAliases({ module: module3, ...aliases }) {
        return this._cloneWith({
          module: module3 ?? this.module,
          moduleAliases: aliases
        });
      }
      withConfig(config) {
        return this._cloneWith({ config });
      }
      withCodecs(codecs) {
        return this._cloneWith({ codecs });
      }
      withSQLRowMode(mode) {
        if (mode === "object") {
          return this._cloneWith({ _dropSQLRowCodec: true });
        } else if (mode === "array") {
          return this._cloneWith({ codecs: record_1.SQLRowModeArray });
        } else {
          throw new errors.InterfaceError(`invalid mode=${mode}`);
        }
      }
      withGlobals(globals) {
        return this._cloneWith({
          globals: { ...this.globals, ...globals }
        });
      }
      withQueryTag(tag) {
        const annos = new Map(this.annotations);
        if (tag != null) {
          if (tag.startsWith("edgedb/")) {
            throw new errors.InterfaceError("reserved tag: edgedb/*");
          }
          if (tag.startsWith("gel/")) {
            throw new errors.InterfaceError("reserved tag: gel/*");
          }
          if (buffer_1.utf8Encoder.encode(tag).length > 128) {
            throw new errors.InterfaceError("tag too long (> 128 bytes)");
          }
          annos.set(TAG_ANNOTATION_KEY, tag);
        } else {
          annos.delete(TAG_ANNOTATION_KEY);
        }
        const clone2 = this._cloneWith({});
        clone2.annotations = annos;
        return clone2;
      }
      withTransactionOptions(opt) {
        return this._cloneWith({
          transactionOptions: opt instanceof TransactionOptions ? opt : new TransactionOptions(opt)
        });
      }
      withRetryOptions(opt) {
        return this._cloneWith({
          retryOptions: opt instanceof RetryOptions ? opt : new RetryOptions(opt.attempts, opt.backoff)
        });
      }
      withWarningHandler(handler) {
        return this._cloneWith({ warningHandler: handler });
      }
      isDefaultSession() {
        return this.config.size === 0 && this.globals.size === 0 && this.moduleAliases.size === 0 && this.module === "default" && this.transactionOptions.isDefault();
      }
      static defaults() {
        return _defaultOptions;
      }
    };
    __publicField(_Options, "schemaVersion", 0);
    var Options = _Options;
    exports2.Options = Options;
    var _defaultOptions = new Options();
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/event.js
var require_event = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/event.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var errors_1 = require_errors();
    var Event = class {
      constructor() {
        __publicField(this, "_promise");
        __publicField(this, "_resolve");
        __publicField(this, "_reject");
        __publicField(this, "_done");
        this._done = false;
        let futReject = null;
        let futResolve = null;
        this._promise = new Promise((resolve, reject) => {
          futReject = (reason) => {
            this._done = true;
            reject(reason);
          };
          futResolve = (value) => {
            this._done = true;
            resolve(value);
          };
        });
        if (!futReject || !futResolve) {
          throw new errors_1.InternalClientError("Promise executor was not called synchronously");
        }
        this._reject = futReject;
        this._resolve = futResolve;
      }
      async wait() {
        await this._promise;
      }
      then(..._args) {
        throw new errors_1.InternalClientError("Event objects cannot be awaited on directly; use Event.wait()");
      }
      get done() {
        return this._done;
      }
      set() {
        if (this._done) {
          throw new errors_1.InternalClientError("emit(): the Event is already set");
        }
        this._resolve(true);
      }
      setError(reason) {
        if (this._done) {
          throw new errors_1.InternalClientError("emitError(): the Event is already set");
        }
        this._reject(reason);
      }
    };
    exports2.default = Event;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/queues.js
var require_queues = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/queues.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LifoQueue = void 0;
    var errors_1 = require_errors();
    var LifoQueue = class {
      constructor() {
        __publicField(this, "_promises");
        __publicField(this, "_resolvers");
        __publicField(this, "_rejecters");
        this._resolvers = [];
        this._rejecters = [];
        this._promises = [];
      }
      _add() {
        this._promises.push(new Promise((resolve, reject) => {
          this._resolvers.push(resolve);
          this._rejecters.push(reject);
        }));
      }
      push(item) {
        if (!this._resolvers.length) {
          this._add();
        }
        const resolve = this._resolvers.shift();
        this._rejecters.shift();
        if (!resolve) {
          throw new errors_1.InternalClientError("resolve function was null or undefined when attempting to push.");
        }
        resolve(item);
      }
      get() {
        if (!this._promises.length) {
          this._add();
        }
        const promise = this._promises.pop();
        if (!promise) {
          throw new errors_1.InternalClientError("promise was null or undefined when attempting to get.");
        }
        return promise;
      }
      cancelAllPending(err2) {
        const rejecters = this._rejecters;
        this._rejecters = [];
        this._resolvers = [];
        for (const reject of rejecters) {
          reject(err2);
        }
      }
      get length() {
        return this._promises.length - this._resolvers.length;
      }
      get pending() {
        return Math.max(0, this._resolvers.length - this._promises.length);
      }
    };
    exports2.LifoQueue = LifoQueue;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/retry.js
var require_retry = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/retry.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      var desc = Object.getOwnPropertyDescriptor(m6, k5);
      if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m6[k5];
        } };
      }
      Object.defineProperty(o5, k22, desc);
    } : function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      o5[k22] = m6[k5];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v6) {
      Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
    } : function(o5, v6) {
      o5["default"] = v6;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.retryingConnect = retryingConnect;
    var errors = __importStar(require_errors());
    var utils_1 = require_utils2();
    var lastLoggingAt = 0;
    async function retryingConnect(connectWithTimeout, config, registry) {
      const maxTime = config.connectionParams.waitUntilAvailable === 0 ? 0 : Date.now() + config.connectionParams.waitUntilAvailable;
      while (true) {
        try {
          return await connectWithTimeout(config, registry);
        } catch (e6) {
          if (e6 instanceof errors.ClientConnectionError) {
            if (e6.hasTag(errors.SHOULD_RECONNECT)) {
              const now = Date.now();
              if (now > maxTime) {
                throw e6;
              }
              if (config.logging && (!lastLoggingAt || now - lastLoggingAt > 5e3)) {
                lastLoggingAt = now;
                const logMsg = [
                  `A client connection error occurred; reconnecting because of "waitUntilAvailable=${config.connectionParams.waitUntilAvailable}".`,
                  e6
                ];
                if (!config.fromProject && !config.fromEnv && await config.inProject()) {
                  logMsg.push(`


Hint: it looks like the program is running from a directory initialized with "gel project init". Consider calling "gel.connect()" without arguments.
`);
                }
                console.warn(...logMsg);
              }
            } else {
              throw e6;
            }
          } else {
            console.error("Unexpected connection error:", e6);
            throw e6;
          }
        }
        await (0, utils_1.sleep)(Math.trunc(10 + Math.random() * 200));
      }
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/enums.js
var require_enums = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/enums.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OperatorKind = exports2.SelectModifierKind = exports2.ExpressionKind = exports2.TypeKind = exports2.Cardinality = void 0;
    var Cardinality;
    (function(Cardinality2) {
      Cardinality2["AtMostOne"] = "AtMostOne";
      Cardinality2["One"] = "One";
      Cardinality2["Many"] = "Many";
      Cardinality2["AtLeastOne"] = "AtLeastOne";
      Cardinality2["Empty"] = "Empty";
    })(Cardinality || (exports2.Cardinality = Cardinality = {}));
    var TypeKind;
    (function(TypeKind2) {
      TypeKind2["scalar"] = "scalar";
      TypeKind2["enum"] = "enum";
      TypeKind2["object"] = "object";
      TypeKind2["namedtuple"] = "namedtuple";
      TypeKind2["tuple"] = "tuple";
      TypeKind2["array"] = "array";
      TypeKind2["range"] = "range";
      TypeKind2["multirange"] = "multirange";
    })(TypeKind || (exports2.TypeKind = TypeKind = {}));
    var ExpressionKind;
    (function(ExpressionKind2) {
      ExpressionKind2["Set"] = "Set";
      ExpressionKind2["Array"] = "Array";
      ExpressionKind2["Tuple"] = "Tuple";
      ExpressionKind2["NamedTuple"] = "NamedTuple";
      ExpressionKind2["TuplePath"] = "TuplePath";
      ExpressionKind2["PathNode"] = "PathNode";
      ExpressionKind2["PathLeaf"] = "PathLeaf";
      ExpressionKind2["Literal"] = "Literal";
      ExpressionKind2["Cast"] = "Cast";
      ExpressionKind2["Select"] = "Select";
      ExpressionKind2["Update"] = "Update";
      ExpressionKind2["Delete"] = "Delete";
      ExpressionKind2["Insert"] = "Insert";
      ExpressionKind2["InsertUnlessConflict"] = "InsertUnlessConflict";
      ExpressionKind2["Function"] = "Function";
      ExpressionKind2["Operator"] = "Operator";
      ExpressionKind2["For"] = "For";
      ExpressionKind2["ForVar"] = "ForVar";
      ExpressionKind2["TypeIntersection"] = "TypeIntersection";
      ExpressionKind2["Alias"] = "Alias";
      ExpressionKind2["With"] = "With";
      ExpressionKind2["WithParams"] = "WithParams";
      ExpressionKind2["Param"] = "Param";
      ExpressionKind2["OptionalParam"] = "OptionalParam";
      ExpressionKind2["Detached"] = "Detached";
      ExpressionKind2["Global"] = "Global";
      ExpressionKind2["PolyShapeElement"] = "PolyShapeElement";
      ExpressionKind2["Group"] = "Group";
    })(ExpressionKind || (exports2.ExpressionKind = ExpressionKind = {}));
    var SelectModifierKind;
    (function(SelectModifierKind2) {
      SelectModifierKind2["filter"] = "filter";
      SelectModifierKind2["order_by"] = "order_by";
      SelectModifierKind2["offset"] = "offset";
      SelectModifierKind2["limit"] = "limit";
    })(SelectModifierKind || (exports2.SelectModifierKind = SelectModifierKind = {}));
    var OperatorKind;
    (function(OperatorKind2) {
      OperatorKind2["Infix"] = "Infix";
      OperatorKind2["Postfix"] = "Postfix";
      OperatorKind2["Prefix"] = "Prefix";
      OperatorKind2["Ternary"] = "Ternary";
    })(OperatorKind || (exports2.OperatorKind = OperatorKind = {}));
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/util.js
var require_util3 = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/util.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.util = void 0;
    var ifaces_1 = require_ifaces2();
    var enums_1 = require_enums();
    var util2;
    (function(util3) {
      function assertNever(arg, error2) {
        throw error2 ?? new Error(`${arg} is supposed to be of "never" type`);
      }
      util3.assertNever = assertNever;
      function splitName(name) {
        if (!name.includes("::"))
          throw new Error(`Invalid FQN ${name}`);
        const parts = name.split("::");
        return {
          mod: parts.slice(0, -1).join("::"),
          name: parts[parts.length - 1]
        };
      }
      util3.splitName = splitName;
      function toIdent(name) {
        if (name.includes("::")) {
          throw new Error(`toIdent: invalid name ${name}`);
        }
        return name.replace(/([^a-zA-Z0-9_]+)/g, "_");
      }
      util3.toIdent = toIdent;
      util3.deduplicate = (args) => [...new Set(args)];
      util3.getFromArrayMap = (map2, id) => {
        return map2[id] || [];
      };
      util3.defineProperty = (obj, name, def) => {
        return Object.defineProperty(obj, name, def);
      };
      util3.defineGetter = (obj, name, getter) => {
        return Object.defineProperty(obj, name, {
          get: getter,
          enumerable: true
        });
      };
      util3.defineMethod = (obj, name, method) => {
        obj[name] = method.bind(obj);
        return obj;
      };
      function flatMap(array2, callbackfn) {
        return Array.prototype.concat(...array2.map(callbackfn));
      }
      util3.flatMap = flatMap;
      function omitDollarPrefixed(object) {
        const obj = {};
        for (const key of Object.keys(object)) {
          if (!key.startsWith("$")) {
            obj[key] = object[key];
          }
        }
        return obj;
      }
      util3.omitDollarPrefixed = omitDollarPrefixed;
      util3.parseCardinality = (cardinality) => {
        switch (cardinality) {
          case ifaces_1.Cardinality.MANY:
            return enums_1.Cardinality.Many;
          case ifaces_1.Cardinality.ONE:
            return enums_1.Cardinality.One;
          case ifaces_1.Cardinality.AT_MOST_ONE:
            return enums_1.Cardinality.AtMostOne;
          case ifaces_1.Cardinality.AT_LEAST_ONE:
            return enums_1.Cardinality.AtLeastOne;
          case ifaces_1.Cardinality.NO_RESULT:
            return enums_1.Cardinality.Empty;
        }
        throw new Error(`Unexpected cardinality: ${cardinality}`);
      };
    })(util2 || (exports2.util = util2 = {}));
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/transaction.js
var require_transaction = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/transaction.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      var desc = Object.getOwnPropertyDescriptor(m6, k5);
      if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m6[k5];
        } };
      }
      Object.defineProperty(o5, k22, desc);
    } : function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      o5[k22] = m6[k5];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v6) {
      Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
    } : function(o5, v6) {
      o5["default"] = v6;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Transaction = exports2.TransactionImpl = exports2.TransactionState = void 0;
    var errors = __importStar(require_errors());
    var ifaces_1 = require_ifaces2();
    var options_1 = require_options();
    var TransactionState;
    (function(TransactionState2) {
      TransactionState2[TransactionState2["ACTIVE"] = 0] = "ACTIVE";
      TransactionState2[TransactionState2["COMMITTED"] = 1] = "COMMITTED";
      TransactionState2[TransactionState2["ROLLEDBACK"] = 2] = "ROLLEDBACK";
      TransactionState2[TransactionState2["FAILED"] = 3] = "FAILED";
    })(TransactionState || (exports2.TransactionState = TransactionState = {}));
    var TransactionImpl = class _TransactionImpl {
      constructor(holder, rawConn) {
        __publicField(this, "_holder");
        __publicField(this, "_rawConn");
        __publicField(this, "_state");
        __publicField(this, "_opInProgress");
        this._holder = holder;
        this._rawConn = rawConn;
        this._state = TransactionState.ACTIVE;
        this._opInProgress = false;
      }
      static async _startTransaction(holder, optimisticRepeatableRead) {
        const rawConn = await holder._getConnection();
        await rawConn.resetState();
        const options = holder.options.transactionOptions;
        const txOptions = [];
        if (options.isolation === options_1.IsolationLevel.RepeatableRead) {
          txOptions.push(`ISOLATION REPEATABLE READ`);
        } else if (options.isolation === options_1.IsolationLevel.Serializable) {
          txOptions.push(`ISOLATION SERIALIZABLE`);
        } else if (options.isolation === options_1.IsolationLevel.PreferRepeatableRead) {
          if (optimisticRepeatableRead) {
            txOptions.push(`ISOLATION REPEATABLE READ`);
          } else {
            txOptions.push(`ISOLATION SERIALIZABLE`);
          }
        } else if (options.isolation != null) {
          throw new errors.InterfaceError(`Invalid isolation level: ${options.isolation}`);
        }
        if (options.readonly !== void 0) {
          txOptions.push(options.readonly ? "READ ONLY" : "READ WRITE");
        }
        if (options.deferrable !== void 0) {
          txOptions.push(options.deferrable ? "DEFERRABLE" : "NOT DEFERRABLE");
        }
        await rawConn.fetch(`START TRANSACTION ${txOptions.join(", ")};`, void 0, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, holder.options, true);
        return new _TransactionImpl(holder, rawConn);
      }
      async _waitForConnAbort() {
        await this._rawConn.connAbortWaiter.wait();
        const abortError = this._rawConn.getConnAbortError();
        if (abortError instanceof errors.GelError && abortError.cause instanceof errors.TransactionTimeoutError) {
          throw abortError.cause;
        } else {
          throw abortError;
        }
      }
      async _runOp(opname, op, errMessage) {
        if (this._opInProgress) {
          throw new errors.InterfaceError(errMessage ?? "Another query is in progress. Use the query methods on 'Client' to run queries concurrently.");
        }
        if (this._state !== TransactionState.ACTIVE) {
          throw new errors.InterfaceError(`cannot ${opname}; the transaction is ${this._state === TransactionState.COMMITTED ? "already committed" : this._state === TransactionState.ROLLEDBACK ? "already rolled back" : "in error state"}`);
        }
        this._opInProgress = true;
        try {
          return await op();
        } finally {
          this._opInProgress = false;
        }
      }
      async _runFetchOp(opName, ...args) {
        const { result, warnings } = await this._runOp(opName, () => this._rawConn.fetch(...args));
        if (warnings.length) {
          this._holder.options.warningHandler(warnings);
        }
        return result;
      }
      async _commit() {
        await this._runOp("commit", async () => {
          await this._rawConn.fetch("COMMIT", void 0, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, this._holder.options, true);
          this._state = TransactionState.COMMITTED;
        }, "A query is still in progress after transaction block has returned.");
      }
      async _rollback() {
        await this._runOp("rollback", async () => {
          await this._rawConn.fetch("ROLLBACK", void 0, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, this._holder.options, true);
          this._state = TransactionState.ROLLEDBACK;
        }, "A query is still in progress after transaction block has returned.");
      }
    };
    exports2.TransactionImpl = TransactionImpl;
    var Transaction = class _Transaction {
      constructor(impl, options) {
        __publicField(this, "impl");
        __publicField(this, "options");
        this.impl = impl;
        this.options = options;
      }
      withSQLRowMode(mode) {
        return new _Transaction(this.impl, this.options.withSQLRowMode(mode));
      }
      async execute(query, args) {
        await this.impl._runFetchOp("execute", query, args, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, this.options);
      }
      async executeSQL(query, args) {
        await this.impl._runFetchOp("execute", query, args, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, this.options, false, ifaces_1.Language.SQL);
      }
      async query(query, args) {
        return this.impl._runFetchOp("query", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, this.options);
      }
      async querySQL(query, args) {
        return this.impl._runFetchOp("query", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, this.options, false, ifaces_1.Language.SQL);
      }
      async queryJSON(query, args) {
        return this.impl._runFetchOp("queryJSON", query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.MANY, this.options);
      }
      async querySingle(query, args) {
        return this.impl._runFetchOp("querySingle", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.AT_MOST_ONE, this.options);
      }
      async querySingleJSON(query, args) {
        return this.impl._runFetchOp("querySingleJSON", query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.AT_MOST_ONE, this.options);
      }
      async queryRequired(query, args) {
        return this.impl._runFetchOp("queryRequired", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.AT_LEAST_ONE, this.options);
      }
      async queryRequiredJSON(query, args) {
        return this.impl._runFetchOp("queryRequiredJSON", query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.AT_LEAST_ONE, this.options);
      }
      async queryRequiredSingle(query, args) {
        return this.impl._runFetchOp("queryRequiredSingle", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.ONE, this.options);
      }
      async queryRequiredSingleJSON(query, args) {
        return this.impl._runFetchOp("queryRequiredSingleJSON", query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.ONE, this.options);
      }
    };
    exports2.Transaction = Transaction;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/baseClient.js
var require_baseClient = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/baseClient.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      var desc = Object.getOwnPropertyDescriptor(m6, k5);
      if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m6[k5];
        } };
      }
      Object.defineProperty(o5, k22, desc);
    } : function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      o5[k22] = m6[k5];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v6) {
      Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
    } : function(o5, v6) {
      o5["default"] = v6;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
      }
      __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.Client = exports2.BaseClientPool = exports2.ClientConnectionHolder = void 0;
    var registry_1 = require_registry();
    var errors = __importStar(require_errors());
    var ifaces_1 = require_ifaces2();
    var options_1 = require_options();
    var event_1 = __importDefault(require_event());
    var queues_1 = require_queues();
    var retry_1 = require_retry();
    var util_1 = require_util3();
    var transaction_1 = require_transaction();
    var utils_1 = require_utils2();
    var ClientConnectionHolder = class {
      constructor(pool) {
        __publicField(this, "_pool");
        __publicField(this, "_connection");
        __publicField(this, "_options");
        __publicField(this, "_inUse");
        this._pool = pool;
        this._connection = null;
        this._options = null;
        this._inUse = null;
      }
      get options() {
        return this._options ?? options_1.Options.defaults();
      }
      async _getConnection() {
        if (!this._connection || this._connection.isClosed()) {
          this._connection = await this._pool.getNewConnection();
        }
        return this._connection;
      }
      get connectionOpen() {
        return this._connection !== null && !this._connection.isClosed();
      }
      async acquire(options) {
        if (this._inUse) {
          throw new errors.InternalClientError("ClientConnectionHolder cannot be acquired, already in use");
        }
        this._options = options;
        this._inUse = new event_1.default();
        return this;
      }
      async release() {
        if (this._inUse === null) {
          throw new errors.ClientError("ClientConnectionHolder.release() called on a free connection holder");
        }
        this._options = null;
        await this._connection?.resetState();
        if (!this._inUse.done) {
          this._inUse.set();
        }
        this._inUse = null;
        this._pool.enqueue(this);
      }
      async _waitUntilReleasedAndClose() {
        if (this._inUse) {
          await this._inUse.wait();
        }
        await this._connection?.close();
      }
      terminate() {
        this._connection?.close();
      }
      async transaction(action) {
        let result;
        let optimisticRepeatableRead = true;
        for (let iteration = 0; ; ++iteration) {
          const transaction = await transaction_1.TransactionImpl._startTransaction(this, optimisticRepeatableRead);
          const clientTx = new transaction_1.Transaction(transaction, this.options);
          let commitFailed = false;
          try {
            result = await Promise.race([
              action(clientTx),
              transaction._waitForConnAbort()
            ]);
            try {
              await transaction._commit();
            } catch (err2) {
              commitFailed = true;
              throw err2;
            }
          } catch (err2) {
            try {
              if (!commitFailed) {
                await transaction._rollback();
              }
            } catch (rollback_err) {
              if (!(rollback_err instanceof errors.GelError)) {
                throw rollback_err;
              }
            }
            if (err2 instanceof errors.CapabilityError && err2.message && err2.message.includes("REPEATABLE READ") && optimisticRepeatableRead) {
              optimisticRepeatableRead = false;
              iteration--;
              continue;
            }
            if (err2 instanceof errors.GelError && err2.hasTag(errors.SHOULD_RETRY) && !(commitFailed && err2 instanceof errors.ClientConnectionError)) {
              const rule = this.options.retryOptions.getRuleForException(err2);
              if (iteration + 1 >= rule.attempts) {
                throw err2;
              }
              await (0, utils_1.sleep)(rule.backoff(iteration + 1));
              continue;
            }
            throw err2;
          }
          return result;
        }
      }
      async retryingFetch(query, args, outputFormat, expectedCardinality, language = ifaces_1.Language.EDGEQL) {
        for (let iteration = 0; ; ++iteration) {
          const conn = await this._getConnection();
          try {
            const { result, warnings } = await conn.fetch(query, args, outputFormat, expectedCardinality, this.options, false, language);
            if (warnings.length) {
              this.options.warningHandler(warnings);
            }
            return result;
          } catch (err2) {
            if (err2 instanceof errors.GelError && err2.hasTag(errors.SHOULD_RETRY) && (conn.getQueryCapabilities(query, outputFormat, expectedCardinality) === 0 || err2 instanceof errors.TransactionConflictError)) {
              const rule = this.options.retryOptions.getRuleForException(err2);
              if (iteration + 1 >= rule.attempts) {
                throw err2;
              }
              await (0, utils_1.sleep)(rule.backoff(iteration + 1));
              continue;
            }
            throw err2;
          }
        }
      }
      async execute(query, args) {
        await this.retryingFetch(query, args, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT);
      }
      async executeSQL(query, args) {
        await this.retryingFetch(query, args, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, ifaces_1.Language.SQL);
      }
      async query(query, args) {
        return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY);
      }
      async querySQL(query, args) {
        return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, ifaces_1.Language.SQL);
      }
      async queryJSON(query, args) {
        return this.retryingFetch(query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.MANY);
      }
      async querySingle(query, args) {
        return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.AT_MOST_ONE);
      }
      async querySingleJSON(query, args) {
        return this.retryingFetch(query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.AT_MOST_ONE);
      }
      async queryRequired(query, args) {
        return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.AT_LEAST_ONE);
      }
      async queryRequiredJSON(query, args) {
        return this.retryingFetch(query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.AT_LEAST_ONE);
      }
      async queryRequiredSingle(query, args) {
        return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.ONE);
      }
      async queryRequiredSingleJSON(query, args) {
        return this.retryingFetch(query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.ONE);
      }
    };
    exports2.ClientConnectionHolder = ClientConnectionHolder;
    var BaseClientPool = class {
      constructor(_parseConnectArguments, options) {
        __publicField(this, "_parseConnectArguments");
        __publicField(this, "_closing");
        __publicField(this, "_queue");
        __publicField(this, "_holders");
        __publicField(this, "_userConcurrency");
        __publicField(this, "_suggestedConcurrency");
        __publicField(this, "_connectConfig");
        __publicField(this, "_codecsRegistry");
        __publicField(this, "__normalizedConnectConfig", null);
        this._parseConnectArguments = _parseConnectArguments;
        this.validateClientOptions(options);
        this._codecsRegistry = new registry_1.CodecsRegistry();
        this._queue = new queues_1.LifoQueue();
        this._holders = [];
        this._userConcurrency = options.concurrency ?? null;
        this._suggestedConcurrency = null;
        this._closing = null;
        this._connectConfig = { ...options };
        this._resizeHolderPool();
      }
      validateClientOptions(opts) {
        if (opts.concurrency != null && (typeof opts.concurrency !== "number" || !Number.isInteger(opts.concurrency) || opts.concurrency < 0)) {
          throw new errors.InterfaceError(`invalid 'concurrency' value: expected integer greater than 0 (got ${JSON.stringify(opts.concurrency)})`);
        }
      }
      _getStats() {
        return {
          queueLength: this._queue.pending,
          openConnections: this._holders.filter((holder) => holder.connectionOpen).length
        };
      }
      async ensureConnected() {
        if (this._closing) {
          throw new errors.InterfaceError(this._closing.done ? "The client is closed" : "The client is closing");
        }
        if (this._getStats().openConnections > 0) {
          return;
        }
        const connHolder = await this._queue.get();
        try {
          await connHolder._getConnection();
        } finally {
          this._queue.push(connHolder);
        }
      }
      get _concurrency() {
        return this._userConcurrency ?? this._suggestedConcurrency ?? 1;
      }
      _resizeHolderPool() {
        const holdersDiff = this._concurrency - this._holders.length;
        if (holdersDiff > 0) {
          for (let i6 = 0; i6 < holdersDiff; i6++) {
            const connectionHolder = new ClientConnectionHolder(this);
            this._holders.push(connectionHolder);
            this._queue.push(connectionHolder);
          }
        } else if (holdersDiff < 0) {
        }
      }
      _getNormalizedConnectConfig() {
        return this.__normalizedConnectConfig ?? (this.__normalizedConnectConfig = this._parseConnectArguments(this._connectConfig));
      }
      async resolveConnectionParams() {
        const config = await this._getNormalizedConnectConfig();
        return config.connectionParams;
      }
      async getNewConnection() {
        if (this._closing?.done) {
          throw new errors.InterfaceError("The client is closed");
        }
        const config = await this._getNormalizedConnectConfig();
        const connection = await (0, retry_1.retryingConnect)(this._connectWithTimeout, config, this._codecsRegistry);
        const suggestedConcurrency = connection.serverSettings.suggested_pool_concurrency;
        if (suggestedConcurrency && suggestedConcurrency !== this._suggestedConcurrency) {
          this._suggestedConcurrency = suggestedConcurrency;
          this._resizeHolderPool();
        }
        return connection;
      }
      async acquireHolder(options) {
        if (this._closing) {
          throw new errors.InterfaceError(this._closing.done ? "The client is closed" : "The client is closing");
        }
        const connectionHolder = await this._queue.get();
        try {
          return await connectionHolder.acquire(options);
        } catch (error2) {
          this._queue.push(connectionHolder);
          throw error2;
        }
      }
      enqueue(holder) {
        this._queue.push(holder);
      }
      async close() {
        if (this._closing) {
          return await this._closing.wait();
        }
        this._closing = new event_1.default();
        this._queue.cancelAllPending(new errors.InterfaceError(`The client is closing`));
        const warningTimeoutId = setTimeout(() => {
          console.warn("Client.close() is taking over 60 seconds to complete. Check if you have any unreleased connections left.");
        }, 6e4);
        try {
          await Promise.all(this._holders.map((connectionHolder) => connectionHolder._waitUntilReleasedAndClose()));
        } catch (err2) {
          this._terminate();
          this._closing.setError(err2);
          throw err2;
        } finally {
          clearTimeout(warningTimeoutId);
        }
        this._closing.set();
      }
      _terminate() {
        for (const connectionHolder of this._holders) {
          connectionHolder.terminate();
        }
      }
      terminate() {
        if (this._closing?.done) {
          return;
        }
        this._queue.cancelAllPending(new errors.InterfaceError(`The client is closed`));
        this._terminate();
        if (!this._closing) {
          this._closing = new event_1.default();
          this._closing.set();
        }
      }
      isClosed() {
        return !!this._closing;
      }
    };
    exports2.BaseClientPool = BaseClientPool;
    var Client2 = class _Client {
      constructor(pool, options) {
        __publicField(this, "pool");
        __publicField(this, "options");
        this.pool = pool;
        this.options = options;
      }
      withTransactionOptions(opts) {
        return new _Client(this.pool, this.options.withTransactionOptions(opts));
      }
      withRetryOptions(opts) {
        return new _Client(this.pool, this.options.withRetryOptions(opts));
      }
      withModuleAliases(aliases) {
        return new _Client(this.pool, this.options.withModuleAliases(aliases));
      }
      withConfig(config) {
        return new _Client(this.pool, this.options.withConfig(config));
      }
      withCodecs(codecs) {
        return new _Client(this.pool, this.options.withCodecs(codecs));
      }
      withSQLRowMode(mode) {
        return new _Client(this.pool, this.options.withSQLRowMode(mode));
      }
      withGlobals(globals) {
        return new _Client(this.pool, this.options.withGlobals(globals));
      }
      withQueryTag(tag) {
        return new _Client(this.pool, this.options.withQueryTag(tag));
      }
      withWarningHandler(handler) {
        return new _Client(this.pool, this.options.withWarningHandler(handler));
      }
      async ensureConnected() {
        await this.pool.ensureConnected();
        return this;
      }
      async resolveConnectionParams() {
        return this.pool.resolveConnectionParams();
      }
      isClosed() {
        return this.pool.isClosed();
      }
      async close() {
        await this.pool.close();
      }
      terminate() {
        this.pool.terminate();
      }
      async transaction(action) {
        if (this.pool.isStateless) {
          throw new errors.GelError(`cannot use 'transaction()' API on HTTP client`);
        }
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.transaction(action);
        } finally {
          await holder.release();
        }
      }
      async execute(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.execute(query, args);
        } finally {
          await holder.release();
        }
      }
      async executeSQL(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.executeSQL(query, args);
        } finally {
          await holder.release();
        }
      }
      async query(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.query(query, args);
        } finally {
          await holder.release();
        }
      }
      async querySQL(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.querySQL(query, args);
        } finally {
          await holder.release();
        }
      }
      async queryJSON(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.queryJSON(query, args);
        } finally {
          await holder.release();
        }
      }
      async querySingle(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.querySingle(query, args);
        } finally {
          await holder.release();
        }
      }
      async querySingleJSON(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.querySingleJSON(query, args);
        } finally {
          await holder.release();
        }
      }
      async queryRequired(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.queryRequired(query, args);
        } finally {
          await holder.release();
        }
      }
      async queryRequiredJSON(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.queryRequiredJSON(query, args);
        } finally {
          await holder.release();
        }
      }
      async queryRequiredSingle(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.queryRequiredSingle(query, args);
        } finally {
          await holder.release();
        }
      }
      async queryRequiredSingleJSON(query, args) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          return await holder.queryRequiredSingleJSON(query, args);
        } finally {
          await holder.release();
        }
      }
      async describe(query) {
        const holder = await this.pool.acquireHolder(this.options);
        try {
          const cxn = await holder._getConnection();
          const result = await cxn._parse(ifaces_1.Language.EDGEQL, query, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, this.options);
          const cardinality = util_1.util.parseCardinality(result[0]);
          return {
            in: result[1],
            out: result[2],
            cardinality,
            capabilities: result[3]
          };
        } finally {
          await holder.release();
        }
      }
      async parse(query) {
        return await this.describe(query);
      }
    };
    exports2.Client = Client2;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/systemUtils.js
var require_systemUtils = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/systemUtils.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      var desc = Object.getOwnPropertyDescriptor(m6, k5);
      if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m6[k5];
        } };
      }
      Object.defineProperty(o5, k22, desc);
    } : function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      o5[k22] = m6[k5];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v6) {
      Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
    } : function(o5, v6) {
      o5["default"] = v6;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
      }
      __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.readFileUtf8 = readFileUtf8;
    exports2.hasFSReadPermission = hasFSReadPermission;
    exports2.hashSHA1toHex = hashSHA1toHex;
    exports2.walk = walk;
    exports2.exists = exists;
    exports2.input = input;
    var crypto5 = __importStar(require("crypto"));
    var node_fs_1 = require("fs");
    var node_path_1 = __importDefault(require("path"));
    var node_process_1 = __importDefault(require("process"));
    var readline = __importStar(require("readline"));
    var node_stream_1 = require("stream");
    async function readFileUtf8(...pathParts) {
      return await node_fs_1.promises.readFile(node_path_1.default.join(...pathParts), { encoding: "utf8" });
    }
    function hasFSReadPermission() {
      if (typeof Deno !== "undefined") {
        return Deno.permissions.querySync({ name: "read" }).state === "granted";
      }
      return true;
    }
    function hashSHA1toHex(msg) {
      return crypto5.createHash("sha1").update(msg).digest("hex");
    }
    async function walk(dir, params) {
      const { match: match2, skip = [] } = params || {};
      try {
        await node_fs_1.promises.access(dir);
      } catch (_err) {
        return [];
      }
      const dirents = await node_fs_1.promises.readdir(dir, { withFileTypes: true });
      const files = await Promise.all(dirents.map((dirent) => {
        const fspath = node_path_1.default.resolve(dir, dirent.name);
        if (skip) {
          if (skip.some((re) => re.test(fspath))) {
            return [];
          }
        }
        if (dirent.isDirectory()) {
          return walk(fspath, params);
        }
        if (match2) {
          if (!match2.some((re) => re.test(fspath))) {
            return [];
          }
        }
        return [fspath];
      }));
      return Array.prototype.concat(...files);
    }
    async function exists(filepath) {
      try {
        await node_fs_1.promises.access(filepath);
        return true;
      } catch {
        return false;
      }
    }
    async function input(message, params) {
      let silent = false;
      const output = params?.silent ? new node_stream_1.Writable({
        write(chunk, encoding, callback) {
          if (!silent)
            node_process_1.default.stdout.write(chunk, encoding);
          callback();
        }
      }) : node_process_1.default.stdout;
      const rl = readline.createInterface({
        input: node_process_1.default.stdin,
        output
      });
      return new Promise((resolve) => {
        rl.question(message, (val2) => {
          rl.close();
          resolve(val2);
        });
        silent = true;
      });
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/platform.js
var require_platform = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/platform.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.isWindows = void 0;
    exports2.searchConfigDir = searchConfigDir;
    var node_path_1 = __importDefault(require("path"));
    var node_os_1 = __importDefault(require("os"));
    var systemUtils_1 = require_systemUtils();
    exports2.isWindows = process.platform === "win32";
    var homeDir = node_os_1.default.homedir;
    var _configDir;
    if (process.platform === "darwin") {
      _configDir = () => {
        return node_path_1.default.join(homeDir(), "Library", "Application Support", "edgedb");
      };
    } else if (process.platform === "win32") {
      _configDir = () => {
        const localAppDataDir = process.env.LOCALAPPDATA ?? node_path_1.default.join(homeDir(), "AppData", "Local");
        return node_path_1.default.join(localAppDataDir, "EdgeDB", "config");
      };
    } else {
      _configDir = () => {
        let xdgConfigDir = process.env.XDG_CONFIG_HOME;
        if (!xdgConfigDir || !node_path_1.default.isAbsolute(xdgConfigDir)) {
          xdgConfigDir = node_path_1.default.join(homeDir(), ".config");
        }
        return node_path_1.default.join(xdgConfigDir, "edgedb");
      };
    }
    async function searchConfigDir(...configPath) {
      const filePath = node_path_1.default.join(_configDir(), ...configPath);
      if (await (0, systemUtils_1.exists)(filePath)) {
        return filePath;
      }
      const fallbackPath = node_path_1.default.join(homeDir(), ".edgedb", ...configPath);
      if (await (0, systemUtils_1.exists)(fallbackPath)) {
        return fallbackPath;
      }
      return filePath;
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/credentials.js
var require_credentials = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/credentials.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getCredentialsPath = getCredentialsPath;
    exports2.readCredentialsFile = readCredentialsFile;
    exports2.validateCredentials = validateCredentials;
    var conUtils_1 = require_conUtils();
    var errors_1 = require_errors();
    async function getCredentialsPath(instanceName, serverUtils) {
      return serverUtils.searchConfigDir("credentials", instanceName + ".json");
    }
    async function readCredentialsFile(file, serverUtils) {
      try {
        const data = await serverUtils.readFileUtf8(file);
        return validateCredentials(JSON.parse(data));
      } catch (e6) {
        throw new errors_1.InterfaceError(`cannot read credentials file ${file}: ${e6}`);
      }
    }
    function validateCredentials(data) {
      const port = data.port;
      if (port != null && (typeof port !== "number" || port < 1 || port > 65535)) {
        throw new errors_1.InterfaceError("invalid `port` value");
      }
      const user = data.user;
      if (user == null) {
        throw new errors_1.InterfaceError("`user` key is required");
      }
      if (typeof user !== "string") {
        throw new errors_1.InterfaceError("`user` must be string");
      }
      const result = { user, port };
      const host = data.host;
      if (host != null) {
        if (typeof host !== "string") {
          throw new errors_1.InterfaceError("`host` must be string");
        }
        result.host = host;
      }
      const database = data.database;
      if (database != null) {
        if (typeof database !== "string") {
          throw new errors_1.InterfaceError("`database` must be string");
        }
        result.database = database;
      }
      const branch = data.branch;
      if (branch != null) {
        if (typeof branch !== "string") {
          throw new errors_1.InterfaceError("`branch` must be string");
        }
        if (database != null && branch !== database) {
          throw new errors_1.InterfaceError("`database` and `branch` cannot both be set");
        }
        result.branch = branch;
      }
      const password = data.password;
      if (password != null) {
        if (typeof password !== "string") {
          throw new errors_1.InterfaceError("`password` must be string");
        }
        result.password = password;
      }
      const caData = data.tls_ca;
      if (caData != null) {
        if (typeof caData !== "string") {
          throw new errors_1.InterfaceError("`tls_ca` must be string");
        }
        result.tlsCAData = caData;
      }
      const certData = data.tls_cert_data;
      if (certData != null) {
        if (typeof certData !== "string") {
          throw new errors_1.InterfaceError("`tls_cert_data` must be string");
        }
        if (caData != null && certData !== caData) {
          throw new errors_1.InterfaceError(`both 'tls_ca' and 'tls_cert_data' are defined, and are not in agreement`);
        }
        result.tlsCAData = certData;
      }
      let verifyHostname = data.tls_verify_hostname;
      const tlsSecurity = data.tls_security;
      if (verifyHostname != null) {
        if (typeof verifyHostname === "boolean") {
          verifyHostname = verifyHostname ? "strict" : "no_host_verification";
        } else {
          throw new errors_1.InterfaceError("`tls_verify_hostname` must be boolean");
        }
      }
      if (tlsSecurity != null && (typeof tlsSecurity !== "string" || !conUtils_1.validTlsSecurityValues.includes(tlsSecurity))) {
        throw new errors_1.InterfaceError(`\`tls_security\` must be one of ${conUtils_1.validTlsSecurityValues.map((val2) => `"${val2}"`).join(", ")}`);
      }
      if (verifyHostname && tlsSecurity && verifyHostname !== tlsSecurity && !(verifyHostname === "no_host_verification" && tlsSecurity === "insecure")) {
        throw new errors_1.InterfaceError(`both 'tls_security' and 'tls_verify_hostname' are defined, and are not in agreement`);
      }
      if (tlsSecurity || verifyHostname) {
        result.tlsSecurity = tlsSecurity ?? verifyHostname;
      }
      return result;
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/crcHqx.js
var require_crcHqx = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/crcHqx.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.crcHqx = crcHqx;
    var crctabHqx = new Uint16Array([
      0,
      4129,
      8258,
      12387,
      16516,
      20645,
      24774,
      28903,
      33032,
      37161,
      41290,
      45419,
      49548,
      53677,
      57806,
      61935,
      4657,
      528,
      12915,
      8786,
      21173,
      17044,
      29431,
      25302,
      37689,
      33560,
      45947,
      41818,
      54205,
      50076,
      62463,
      58334,
      9314,
      13379,
      1056,
      5121,
      25830,
      29895,
      17572,
      21637,
      42346,
      46411,
      34088,
      38153,
      58862,
      62927,
      50604,
      54669,
      13907,
      9842,
      5649,
      1584,
      30423,
      26358,
      22165,
      18100,
      46939,
      42874,
      38681,
      34616,
      63455,
      59390,
      55197,
      51132,
      18628,
      22757,
      26758,
      30887,
      2112,
      6241,
      10242,
      14371,
      51660,
      55789,
      59790,
      63919,
      35144,
      39273,
      43274,
      47403,
      23285,
      19156,
      31415,
      27286,
      6769,
      2640,
      14899,
      10770,
      56317,
      52188,
      64447,
      60318,
      39801,
      35672,
      47931,
      43802,
      27814,
      31879,
      19684,
      23749,
      11298,
      15363,
      3168,
      7233,
      60846,
      64911,
      52716,
      56781,
      44330,
      48395,
      36200,
      40265,
      32407,
      28342,
      24277,
      20212,
      15891,
      11826,
      7761,
      3696,
      65439,
      61374,
      57309,
      53244,
      48923,
      44858,
      40793,
      36728,
      37256,
      33193,
      45514,
      41451,
      53516,
      49453,
      61774,
      57711,
      4224,
      161,
      12482,
      8419,
      20484,
      16421,
      28742,
      24679,
      33721,
      37784,
      41979,
      46042,
      49981,
      54044,
      58239,
      62302,
      689,
      4752,
      8947,
      13010,
      16949,
      21012,
      25207,
      29270,
      46570,
      42443,
      38312,
      34185,
      62830,
      58703,
      54572,
      50445,
      13538,
      9411,
      5280,
      1153,
      29798,
      25671,
      21540,
      17413,
      42971,
      47098,
      34713,
      38840,
      59231,
      63358,
      50973,
      55100,
      9939,
      14066,
      1681,
      5808,
      26199,
      30326,
      17941,
      22068,
      55628,
      51565,
      63758,
      59695,
      39368,
      35305,
      47498,
      43435,
      22596,
      18533,
      30726,
      26663,
      6336,
      2273,
      14466,
      10403,
      52093,
      56156,
      60223,
      64286,
      35833,
      39896,
      43963,
      48026,
      19061,
      23124,
      27191,
      31254,
      2801,
      6864,
      10931,
      14994,
      64814,
      60687,
      56684,
      52557,
      48554,
      44427,
      40424,
      36297,
      31782,
      27655,
      23652,
      19525,
      15522,
      11395,
      7392,
      3265,
      61215,
      65342,
      53085,
      57212,
      44955,
      49082,
      36825,
      40952,
      28183,
      32310,
      20053,
      24180,
      11923,
      16050,
      3793,
      7920
    ]);
    function crcHqx(data, crc) {
      crc &= 65535;
      const len = data.length;
      let i6 = 0;
      while (i6 < len) {
        crc = crc << 8 & 65280 ^ crctabHqx[crc >> 8 ^ data[i6++]];
      }
      return crc;
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/conUtils.js
var require_conUtils = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/conUtils.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      var desc = Object.getOwnPropertyDescriptor(m6, k5);
      if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m6[k5];
        } };
      }
      Object.defineProperty(o5, k22, desc);
    } : function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      o5[k22] = m6[k5];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v6) {
      Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
    } : function(o5, v6) {
      o5["default"] = v6;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ResolvedConnectConfig = exports2.validTlsSecurityValues = void 0;
    exports2.isValidTlsSecurityValue = isValidTlsSecurityValue;
    exports2.getConnectArgumentsParser = getConnectArgumentsParser;
    exports2.parseDuration = parseDuration;
    var errors = __importStar(require_errors());
    var credentials_1 = require_credentials();
    var datetime_1 = require_datetime();
    var datetime_2 = require_datetime2();
    var errors_1 = require_errors();
    var buffer_1 = require_buffer();
    var crcHqx_1 = require_crcHqx();
    var DOMAIN_NAME_MAX_LEN = 63;
    exports2.validTlsSecurityValues = [
      "insecure",
      "no_host_verification",
      "strict",
      "default"
    ];
    function isValidTlsSecurityValue(candidate) {
      return typeof candidate === "string" && exports2.validTlsSecurityValues.includes(candidate);
    }
    function getConnectArgumentsParser(utils) {
      return async (opts) => {
        return {
          ...await parseConnectDsnAndArgs(opts, utils),
          connectTimeout: opts.timeout,
          logging: opts.logging ?? true
        };
      };
    }
    function getEnv(envName, _required = false) {
      const gelEnv = envName;
      const edgedbEnv = envName.replace(/^GEL_/, "EDGEDB_");
      const gelValue = process.env[gelEnv];
      const edgedbValue = process.env[edgedbEnv];
      if (gelValue !== void 0 && edgedbValue !== void 0) {
        console.warn(`Both GEL_w+ and EDGEDB_w+ are set; EDGEDB_w+ will be ignored`);
      }
      return gelValue ?? edgedbValue;
    }
    var ResolvedConnectConfig = class {
      constructor() {
        __publicField(this, "_host", null);
        __publicField(this, "_hostSource", null);
        __publicField(this, "_port", null);
        __publicField(this, "_portSource", null);
        __publicField(this, "_database", null);
        __publicField(this, "_databaseSource", null);
        __publicField(this, "_branch", null);
        __publicField(this, "_branchSource", null);
        __publicField(this, "_user", null);
        __publicField(this, "_userSource", null);
        __publicField(this, "_password", null);
        __publicField(this, "_passwordSource", null);
        __publicField(this, "_secretKey", null);
        __publicField(this, "_secretKeySource", null);
        __publicField(this, "_cloudProfile", null);
        __publicField(this, "_cloudProfileSource", null);
        __publicField(this, "_tlsCAData", null);
        __publicField(this, "_tlsCADataSource", null);
        __publicField(this, "_tlsSecurity", null);
        __publicField(this, "_tlsSecuritySource", null);
        __publicField(this, "_tlsServerName", null);
        __publicField(this, "_tlsServerNameSource", null);
        __publicField(this, "_waitUntilAvailable", null);
        __publicField(this, "_waitUntilAvailableSource", null);
        __publicField(this, "serverSettings", {});
        this.setHost = this.setHost.bind(this);
        this.setPort = this.setPort.bind(this);
        this.setDatabase = this.setDatabase.bind(this);
        this.setBranch = this.setBranch.bind(this);
        this.setUser = this.setUser.bind(this);
        this.setPassword = this.setPassword.bind(this);
        this.setSecretKey = this.setSecretKey.bind(this);
        this.setTlsCAData = this.setTlsCAData.bind(this);
        this.setTlsCAFile = this.setTlsCAFile.bind(this);
        this.setTlsServerName = this.setTlsServerName.bind(this);
        this.setTlsSecurity = this.setTlsSecurity.bind(this);
        this.setWaitUntilAvailable = this.setWaitUntilAvailable.bind(this);
      }
      _setParam(param, value, source, validator2) {
        if (this[`_${param}`] === null) {
          this[`_${param}Source`] = source;
          if (value !== null) {
            this[`_${param}`] = validator2 ? validator2(value) : value;
            return true;
          }
        }
        return false;
      }
      async _setParamAsync(param, value, source, validator2) {
        if (this[`_${param}`] === null) {
          this[`_${param}Source`] = source;
          if (value !== null) {
            this[`_${param}`] = validator2 ? await validator2(value) : value;
            return true;
          }
        }
        return false;
      }
      setHost(host, source) {
        return this._setParam("host", host, source, validateHost);
      }
      setPort(port, source) {
        return this._setParam("port", port, source, parseValidatePort);
      }
      setDatabase(database, source) {
        return this._setParam("database", database, source, (db) => {
          if (db === "") {
            throw new errors_1.InterfaceError(`invalid database name: '${db}'`);
          }
          return db;
        });
      }
      setBranch(branch, source) {
        return this._setParam("branch", branch, source, (branchName) => {
          if (branchName === "") {
            throw new errors_1.InterfaceError(`invalid branch name: '${branchName}'`);
          }
          return branchName;
        });
      }
      setUser(user, source) {
        return this._setParam("user", user, source, (_user) => {
          if (_user === "") {
            throw new errors_1.InterfaceError(`invalid user name: '${_user}'`);
          }
          return _user;
        });
      }
      setPassword(password, source) {
        return this._setParam("password", password, source);
      }
      setSecretKey(secretKey, source) {
        return this._setParam("secretKey", secretKey, source);
      }
      setCloudProfile(cloudProfile, source) {
        return this._setParam("cloudProfile", cloudProfile, source);
      }
      setTlsCAData(caData, source) {
        return this._setParam("tlsCAData", caData, source);
      }
      setTlsCAFile(caFile, source, readFile4) {
        return this._setParamAsync("tlsCAData", caFile, source, (caFilePath) => readFile4(caFilePath));
      }
      setTlsServerName(serverName, source) {
        return this._setParam("tlsServerName", serverName, source, validateHost);
      }
      setTlsSecurity(tlsSecurity, source) {
        return this._setParam("tlsSecurity", tlsSecurity, source, (_tlsSecurity) => {
          if (!exports2.validTlsSecurityValues.includes(_tlsSecurity)) {
            throw new errors_1.InterfaceError(`invalid 'tlsSecurity' value: '${_tlsSecurity}', must be one of ${exports2.validTlsSecurityValues.map((val2) => `'${val2}'`).join(", ")}`);
          }
          const clientSecurity = getEnv("GEL_CLIENT_SECURITY");
          if (clientSecurity !== void 0) {
            if (!["default", "insecure_dev_mode", "strict"].includes(clientSecurity)) {
              throw new errors_1.InterfaceError(`invalid GEL_CLIENT_SECURITY value: '${clientSecurity}', must be one of 'default', 'insecure_dev_mode' or 'strict'`);
            }
            if (clientSecurity === "insecure_dev_mode") {
              if (_tlsSecurity === "default") {
                _tlsSecurity = "insecure";
              }
            } else if (clientSecurity === "strict") {
              if (_tlsSecurity === "insecure" || _tlsSecurity === "no_host_verification") {
                throw new errors_1.InterfaceError(`'tlsSecurity' value (${_tlsSecurity}) conflicts with GEL_CLIENT_SECURITY value (${clientSecurity}), 'tlsSecurity' value cannot be lower than security level set by GEL_CLIENT_SECURITY`);
              }
              _tlsSecurity = "strict";
            }
          }
          return _tlsSecurity;
        });
      }
      setWaitUntilAvailable(duration, source) {
        return this._setParam("waitUntilAvailable", duration, source, parseDuration);
      }
      addServerSettings(settings) {
        this.serverSettings = {
          ...settings,
          ...this.serverSettings
        };
      }
      get address() {
        return [this._host ?? "localhost", this._port ?? 5656];
      }
      get database() {
        return this._database ?? this._branch ?? "edgedb";
      }
      get branch() {
        return this._branch ?? this._database ?? "__default__";
      }
      get user() {
        return this._user ?? "edgedb";
      }
      get password() {
        return this._password ?? void 0;
      }
      get secretKey() {
        return this._secretKey ?? void 0;
      }
      get cloudProfile() {
        return this._cloudProfile ?? "default";
      }
      get tlsServerName() {
        return this._tlsServerName ?? void 0;
      }
      get tlsSecurity() {
        return this._tlsSecurity && this._tlsSecurity !== "default" ? this._tlsSecurity : this._tlsCAData !== null ? "no_host_verification" : "strict";
      }
      get waitUntilAvailable() {
        return this._waitUntilAvailable ?? 3e4;
      }
      explainConfig() {
        const output = [
          `Parameter          Value                                    Source`,
          `---------          -----                                    ------`
        ];
        const outputLine = (param, val2, rawVal, source) => {
          const isDefault = rawVal === null;
          const maxValLength = 40 - (isDefault ? 10 : 0);
          let value = String(val2);
          if (value.length > maxValLength) {
            value = value.slice(0, maxValLength - 3) + "...";
          }
          output.push(param.padEnd(19, " ") + (value + (isDefault ? " (default)" : "")).padEnd(42, " ") + (source ?? "default"));
        };
        outputLine("host", this.address[0], this._host, this._hostSource);
        outputLine("port", this.address[1], this._port, this._portSource);
        outputLine("database", this.database, this._database, this._databaseSource);
        outputLine("branch", this.branch, this._branch, this._branchSource);
        outputLine("user", this.user, this._user, this._userSource);
        outputLine("password", this.password && this.password.slice(0, 3).padEnd(this.password.length, "*"), this._password, this._passwordSource);
        outputLine("tlsCAData", this._tlsCAData && this._tlsCAData.replace(/\r\n?|\n/, ""), this._tlsCAData, this._tlsCADataSource);
        outputLine("tlsSecurity", this.tlsSecurity, this._tlsSecurity, this._tlsSecuritySource);
        outputLine("tlsServerName", this.tlsServerName, this._tlsServerName, this._tlsServerNameSource);
        outputLine("waitUntilAvailable", this.waitUntilAvailable, this._waitUntilAvailable, this._waitUntilAvailableSource);
        return output.join("\n");
      }
    };
    exports2.ResolvedConnectConfig = ResolvedConnectConfig;
    function parseValidatePort(port) {
      let parsedPort;
      if (typeof port === "string") {
        if (!/^\d*$/.test(port)) {
          throw new errors_1.InterfaceError(`invalid port: ${port}`);
        }
        parsedPort = parseInt(port, 10);
        if (Number.isNaN(parsedPort)) {
          throw new errors_1.InterfaceError(`invalid port: ${port}`);
        }
      } else {
        parsedPort = port;
      }
      if (!Number.isInteger(parsedPort) || parsedPort < 1 || parsedPort > 65535) {
        throw new errors_1.InterfaceError(`invalid port: ${port}`);
      }
      return parsedPort;
    }
    function validateHost(host) {
      if (host.includes("/")) {
        throw new errors_1.InterfaceError(`unix socket paths not supported`);
      }
      if (!host.length || host.includes(",")) {
        throw new errors_1.InterfaceError(`invalid host: '${host}'`);
      }
      return host;
    }
    function parseDuration(duration) {
      if (typeof duration === "number") {
        if (duration < 0) {
          throw new errors_1.InterfaceError("invalid waitUntilAvailable duration, must be >= 0");
        }
        return duration;
      }
      if (typeof duration === "string") {
        if (duration.startsWith("P")) {
          duration = datetime_1.Duration.from(duration);
        } else {
          return (0, datetime_1.parseHumanDurationString)(duration);
        }
      }
      if (duration instanceof datetime_1.Duration) {
        const invalidField = (0, datetime_2.checkValidGelDuration)(duration);
        if (invalidField) {
          throw new errors_1.InterfaceError(`invalid waitUntilAvailable duration, cannot have a '${invalidField}' value`);
        }
        if (duration.sign < 0) {
          throw new errors_1.InterfaceError("invalid waitUntilAvailable duration, must be >= 0");
        }
        return duration.milliseconds + duration.seconds * 1e3 + duration.minutes * 6e4 + duration.hours * 36e5;
      }
      throw new errors_1.InterfaceError(`invalid duration`);
    }
    async function parseConnectDsnAndArgs(config, serverUtils) {
      const resolvedConfig = new ResolvedConnectConfig();
      let fromEnv3 = false;
      let fromProject = false;
      const [dsn, instanceName] = config.instanceName == null && config.dsn != null && !/^[a-z]+:\/\//i.test(config.dsn) ? [void 0, config.dsn] : [config.dsn, config.instanceName];
      let { hasCompoundOptions } = await resolveConfigOptions(resolvedConfig, {
        dsn,
        instanceName,
        credentials: config.credentials,
        credentialsFile: config.credentialsFile,
        host: config.host,
        port: config.port,
        database: config.database,
        branch: config.branch,
        user: config.user,
        password: config.password,
        secretKey: config.secretKey,
        cloudProfile: getEnv("GEL_CLOUD_PROFILE"),
        tlsCA: config.tlsCA,
        tlsCAFile: config.tlsCAFile,
        tlsServerName: config.tlsServerName,
        tlsSecurity: config.tlsSecurity,
        serverSettings: config.serverSettings,
        waitUntilAvailable: config.waitUntilAvailable
      }, {
        dsn: `'dsnOrInstanceName' option (parsed as dsn)`,
        instanceName: config.instanceName != null ? `'instanceName' option` : `'dsnOrInstanceName' option (parsed as instance name)`,
        credentials: `'credentials' option`,
        credentialsFile: `'credentialsFile' option`,
        host: `'host' option`,
        port: `'port' option`,
        database: `'database' option`,
        branch: `'branch' option`,
        user: `'user' option`,
        password: `'password' option`,
        secretKey: `'secretKey' option`,
        cloudProfile: `'GEL_CLOUD_PROFILE' environment variable`,
        tlsCA: `'tlsCA' option`,
        tlsCAFile: `'tlsCAFile' option`,
        tlsSecurity: `'tlsSecurity' option`,
        tlsServerName: `'tlsServerName' option`,
        serverSettings: `'serverSettings' option`,
        waitUntilAvailable: `'waitUntilAvailable' option`
      }, `Cannot have more than one of the following connection options: 'dsn', 'instanceName', 'credentials', 'credentialsFile' or 'host'/'port'`, serverUtils);
      if (!hasCompoundOptions) {
        let port = getEnv("GEL_PORT");
        if (resolvedConfig._port === null && port?.startsWith("tcp://")) {
          console.warn(`GEL_PORT in 'tcp://host:port' format, so will be ignored`);
          port = void 0;
        }
        ({ hasCompoundOptions, anyOptionsUsed: fromEnv3 } = await resolveConfigOptions(resolvedConfig, {
          dsn: getEnv("GEL_DSN"),
          instanceName: getEnv("GEL_INSTANCE"),
          credentials: getEnv("GEL_CREDENTIALS"),
          credentialsFile: getEnv("GEL_CREDENTIALS_FILE"),
          host: getEnv("GEL_HOST"),
          port,
          database: getEnv("GEL_DATABASE"),
          branch: getEnv("GEL_BRANCH"),
          user: getEnv("GEL_USER"),
          password: getEnv("GEL_PASSWORD"),
          secretKey: getEnv("GEL_SECRET_KEY"),
          tlsCA: getEnv("GEL_TLS_CA"),
          tlsCAFile: getEnv("GEL_TLS_CA_FILE"),
          tlsServerName: getEnv("GEL_TLS_SERVER_NAME"),
          tlsSecurity: getEnv("GEL_CLIENT_TLS_SECURITY"),
          waitUntilAvailable: getEnv("GEL_WAIT_UNTIL_AVAILABLE")
        }, {
          dsn: `'GEL_DSN' environment variable`,
          instanceName: `'GEL_INSTANCE' environment variable`,
          credentials: `'GEL_CREDENTIALS' environment variable`,
          credentialsFile: `'GEL_CREDENTIALS_FILE' environment variable`,
          host: `'GEL_HOST' environment variable`,
          port: `'GEL_PORT' environment variable`,
          database: `'GEL_DATABASE' environment variable`,
          branch: `'GEL_BRANCH' environment variable`,
          user: `'GEL_USER' environment variable`,
          password: `'GEL_PASSWORD' environment variable`,
          secretKey: `'GEL_SECRET_KEY' environment variable`,
          tlsCA: `'GEL_TLS_CA' environment variable`,
          tlsCAFile: `'GEL_TLS_CA_FILE' environment variable`,
          tlsServerName: `'GEL_TLS_SERVER_NAME' environment variable`,
          tlsSecurity: `'GEL_CLIENT_TLS_SECURITY' environment variable`,
          waitUntilAvailable: `'GEL_WAIT_UNTIL_AVAILABLE' environment variable`
        }, `Cannot have more than one of the following connection environment variables: 'GEL_DSN', 'GEL_INSTANCE', 'GEL_CREDENTIALS', 'GEL_CREDENTIALS_FILE' or 'GEL_HOST'`, serverUtils));
      }
      if (!hasCompoundOptions) {
        if (!serverUtils) {
          throw new errors.ClientConnectionError("no connection options specified either by arguments to `createClient` API or environment variables; also cannot resolve from project config file in browser (or edge runtime) environment");
        }
        const projectDir = await serverUtils?.findProjectDir();
        if (!projectDir) {
          throw new errors.ClientConnectionError("no project config file found and no connection options specified either via arguments to `createClient()` API or via environment variables GEL_HOST, GEL_INSTANCE, GEL_DSN, GEL_CREDENTIALS or GEL_CREDENTIALS_FILE");
        }
        const stashDir = await serverUtils.findStashPath(projectDir);
        const instName = await serverUtils.readFileUtf8(stashDir, "instance-name").then((name) => name.trim()).catch(() => null);
        if (instName !== null) {
          const [cloudProfile, _database, branch] = await Promise.all([
            serverUtils.readFileUtf8(stashDir, "cloud-profile").then((name) => name.trim()).catch(() => void 0),
            serverUtils.readFileUtf8(stashDir, "database").then((name) => name.trim()).catch(() => void 0),
            serverUtils.readFileUtf8(stashDir, "branch").then((name) => name.trim()).catch(() => void 0)
          ]);
          let database = _database;
          if (database !== void 0 && branch !== void 0) {
            if (database !== branch) {
              throw new errors_1.InterfaceError("Both database and branch exist in the config dir and don't match.");
            } else {
              database = void 0;
            }
          }
          await resolveConfigOptions(resolvedConfig, { instanceName: instName, cloudProfile, database, branch }, {
            instanceName: `project linked instance ('${instName}')`,
            cloudProfile: `project defined cloud instance ('${cloudProfile}')`,
            database: `project default database`,
            branch: `project default branch`
          }, "", serverUtils);
          fromProject = true;
        } else {
          throw new errors.ClientConnectionError("Found project config file but the project is not initialized. Run 'gel project init'.");
        }
      }
      resolvedConfig.setTlsSecurity("default", "default");
      return {
        connectionParams: resolvedConfig,
        inProject: async () => await serverUtils?.findProjectDir(false) != null,
        fromEnv: fromEnv3,
        fromProject
      };
    }
    async function resolveConfigOptions(resolvedConfig, config, sources, compoundParamsError, serverUtils) {
      let anyOptionsUsed = false;
      const readFile4 = serverUtils?.readFileUtf8 ?? ((fn) => {
        throw new errors_1.InterfaceError(`cannot read file "${fn}" in browser (or edge runtime) environment`);
      });
      if (config.tlsCA != null && config.tlsCAFile != null) {
        throw new errors_1.InterfaceError(`Cannot specify both ${sources.tlsCA} and ${sources.tlsCAFile}`);
      }
      if (config.database != null) {
        if (config.branch != null) {
          throw new errors_1.InterfaceError(`${sources.database} and ${sources.branch} are mutually exclusive`);
        }
        if (resolvedConfig._branch == null) {
          anyOptionsUsed = resolvedConfig.setDatabase(config.database ?? null, sources.database) || anyOptionsUsed;
        }
      }
      if (config.branch != null) {
        if (resolvedConfig._database == null) {
          anyOptionsUsed = resolvedConfig.setBranch(config.branch ?? null, sources.branch) || anyOptionsUsed;
        }
      }
      anyOptionsUsed = resolvedConfig.setUser(config.user ?? null, sources.user) || anyOptionsUsed;
      anyOptionsUsed = resolvedConfig.setPassword(config.password ?? null, sources.password) || anyOptionsUsed;
      anyOptionsUsed = resolvedConfig.setSecretKey(config.secretKey ?? null, sources.secretKey) || anyOptionsUsed;
      anyOptionsUsed = resolvedConfig.setCloudProfile(config.cloudProfile ?? null, sources.cloudProfile) || anyOptionsUsed;
      anyOptionsUsed = resolvedConfig.setTlsCAData(config.tlsCA ?? null, sources.tlsCA) || anyOptionsUsed;
      anyOptionsUsed = await resolvedConfig.setTlsCAFile(config.tlsCAFile ?? null, sources.tlsCAFile, readFile4) || anyOptionsUsed;
      anyOptionsUsed = resolvedConfig.setTlsServerName(config.tlsServerName ?? null, sources.tlsServerName) || anyOptionsUsed;
      anyOptionsUsed = resolvedConfig.setTlsSecurity(config.tlsSecurity ?? null, sources.tlsSecurity) || anyOptionsUsed;
      anyOptionsUsed = resolvedConfig.setWaitUntilAvailable(config.waitUntilAvailable ?? null, sources.waitUntilAvailable) || anyOptionsUsed;
      resolvedConfig.addServerSettings(config.serverSettings ?? {});
      const compoundParamsCount = [
        config.dsn,
        config.instanceName,
        config.credentials,
        config.credentialsFile,
        config.host ?? config.port
      ].filter((param) => param !== void 0).length;
      if (compoundParamsCount > 1) {
        throw new errors_1.InterfaceError(compoundParamsError);
      }
      if (compoundParamsCount === 1) {
        if (config.dsn !== void 0 || config.host !== void 0 || config.port !== void 0) {
          let dsn = config.dsn;
          if (dsn === void 0) {
            if (config.port !== void 0) {
              resolvedConfig.setPort(config.port, sources.port);
            }
            const host = config.host != null ? validateHost(config.host) : "";
            dsn = `edgedb://${host.includes(":") ? `[${encodeURI(host)}]` : host}`;
          }
          await parseDSNIntoConfig(dsn, resolvedConfig, config.dsn ? sources.dsn : config.host !== void 0 ? sources.host : sources.port, readFile4);
        } else {
          let creds;
          let source;
          if (config.credentials != null) {
            creds = (0, credentials_1.validateCredentials)(JSON.parse(config.credentials));
            source = sources.credentials;
          } else {
            if (!serverUtils && !config.instanceName?.includes("/")) {
              throw new errors_1.InterfaceError(`cannot ${config.credentialsFile ? `read credentials file "${config.credentialsFile}"` : `resolve instance name "${config.instanceName}"`} in browser (or edge runtime) environment`);
            }
            let credentialsFile = config.credentialsFile;
            if (credentialsFile === void 0) {
              if (/^\w(-?\w)*$/.test(config.instanceName)) {
                credentialsFile = await (0, credentials_1.getCredentialsPath)(config.instanceName, serverUtils);
                source = sources.instanceName;
              } else {
                if (!/^([A-Za-z0-9_-](-?[A-Za-z0-9_])*)\/([A-Za-z0-9](-?[A-Za-z0-9])*)$/.test(config.instanceName)) {
                  throw new errors_1.InterfaceError(`invalid DSN or instance name: '${config.instanceName}'`);
                }
                await parseCloudInstanceNameIntoConfig(resolvedConfig, config.instanceName, sources.instanceName, serverUtils);
                return { hasCompoundOptions: true, anyOptionsUsed: true };
              }
            } else {
              source = sources.credentialsFile;
            }
            creds = await (0, credentials_1.readCredentialsFile)(credentialsFile, serverUtils);
          }
          resolvedConfig.setHost(creds.host ?? null, source);
          resolvedConfig.setPort(creds.port ?? null, source);
          if (creds.database != null) {
            if (resolvedConfig._branch == null) {
              resolvedConfig.setDatabase(creds.database ?? null, source);
            }
          } else if (creds.branch != null) {
            if (resolvedConfig._database == null) {
              resolvedConfig.setBranch(creds.branch ?? null, source);
            }
          }
          resolvedConfig.setUser(creds.user ?? null, source);
          resolvedConfig.setPassword(creds.password ?? null, source);
          resolvedConfig.setTlsCAData(creds.tlsCAData ?? null, source);
          resolvedConfig.setTlsSecurity(creds.tlsSecurity ?? null, source);
        }
        return { hasCompoundOptions: true, anyOptionsUsed: true };
      }
      return { hasCompoundOptions: false, anyOptionsUsed };
    }
    async function parseDSNIntoConfig(_dsnString, config, source, readFile4) {
      let dsnString = _dsnString;
      let regexHostname = null;
      let zoneId = "";
      const regexResult = /\[(.*?)(%25.+?)\]/.exec(_dsnString);
      if (regexResult) {
        regexHostname = regexResult[1];
        zoneId = decodeURI(regexResult[2]);
        dsnString = dsnString.slice(0, regexResult.index + regexHostname.length + 1) + dsnString.slice(regexResult.index + regexHostname.length + regexResult[2].length + 1);
      }
      let parsed;
      try {
        parsed = new URL(dsnString);
        if (regexHostname !== null && parsed.hostname !== `[${regexHostname}]`) {
          throw new Error();
        }
      } catch (_3) {
        throw new errors_1.InterfaceError(`invalid DSN or instance name: '${_dsnString}'`);
      }
      if (parsed.protocol !== "edgedb:" && parsed.protocol !== "gel:") {
        throw new errors_1.InterfaceError(`invalid DSN: scheme is expected to be 'gel', got '${parsed.protocol.slice(0, -1)}'`);
      }
      const searchParams = /* @__PURE__ */ new Map();
      for (const [key, value] of parsed.searchParams) {
        if (searchParams.has(key)) {
          throw new errors_1.InterfaceError(`invalid DSN: duplicate query parameter '${key}'`);
        }
        searchParams.set(key, value);
      }
      async function handleDSNPart(paramName, value, currentValue, setter, formatter = (val2) => val2) {
        if ([
          value || null,
          searchParams.get(paramName),
          searchParams.get(`${paramName}_env`),
          searchParams.get(`${paramName}_file`)
        ].filter((param) => param != null).length > 1) {
          throw new errors_1.InterfaceError(`invalid DSN: more than one of ${value !== null ? `'${paramName}', ` : ""}'?${paramName}=', '?${paramName}_env=' or '?${paramName}_file=' was specified ${dsnString}`);
        }
        if (currentValue === null) {
          let param = value || (searchParams.get(paramName) ?? null);
          let paramSource = source;
          if (param === null) {
            const env4 = searchParams.get(`${paramName}_env`);
            if (env4 != null) {
              param = getEnv(env4, true) ?? null;
              if (param === null) {
                throw new errors_1.InterfaceError(`'${paramName}_env' environment variable '${env4}' doesn't exist`);
              }
              paramSource += ` (${paramName}_env: ${env4})`;
            }
          }
          if (param === null) {
            const file = searchParams.get(`${paramName}_file`);
            if (file != null) {
              param = await readFile4(file);
              paramSource += ` (${paramName}_file: ${file})`;
            }
          }
          param = param !== null ? formatter(param) : null;
          await setter(param, paramSource);
        }
        searchParams.delete(paramName);
        searchParams.delete(`${paramName}_env`);
        searchParams.delete(`${paramName}_file`);
      }
      const hostname = /^\[.*\]$/.test(parsed.hostname) ? parsed.hostname.slice(1, -1) + zoneId : parsed.hostname;
      await handleDSNPart("host", hostname, config._host, config.setHost);
      await handleDSNPart("port", parsed.port, config._port, config.setPort);
      const stripLeadingSlash = (str) => str.replace(/^\//, "");
      const searchParamsContainsDatabase = searchParams.has("database") || searchParams.has("database_env") || searchParams.has("database_file");
      const searchParamsContainsBranch = searchParams.has("branch") || searchParams.has("branch_env") || searchParams.has("branch_file");
      if (searchParamsContainsBranch) {
        if (searchParamsContainsDatabase) {
          throw new errors_1.InterfaceError(`invalid DSN: cannot specify both 'database' and 'branch'`);
        }
        if (config._database === null) {
          await handleDSNPart("branch", stripLeadingSlash(parsed.pathname), config._branch, config.setBranch, stripLeadingSlash);
        } else {
          searchParams.delete("branch");
          searchParams.delete("branch_env");
          searchParams.delete("branch_file");
        }
      } else {
        if (config._branch === null) {
          await handleDSNPart("database", stripLeadingSlash(parsed.pathname), config._database, config.setDatabase, stripLeadingSlash);
        } else {
          searchParams.delete("database");
          searchParams.delete("database_env");
          searchParams.delete("database_file");
        }
      }
      await handleDSNPart("user", parsed.username, config._user, config.setUser);
      await handleDSNPart("password", parsed.password, config._password, config.setPassword);
      await handleDSNPart("secret_key", null, config._secretKey, config.setSecretKey);
      await handleDSNPart("tls_ca", null, config._tlsCAData, config.setTlsCAData);
      await handleDSNPart("tls_ca_file", null, config._tlsCAData, (val2, _source) => config.setTlsCAFile(val2, _source, readFile4));
      await handleDSNPart("tls_server_name", null, config._tlsServerName, config.setTlsServerName);
      await handleDSNPart("tls_security", null, config._tlsSecurity, config.setTlsSecurity);
      await handleDSNPart("wait_until_available", null, config._waitUntilAvailable, config.setWaitUntilAvailable);
      const serverSettings = {};
      for (const [key, value] of searchParams) {
        serverSettings[key] = value;
      }
      config.addServerSettings(serverSettings);
    }
    async function parseCloudInstanceNameIntoConfig(config, cloudInstanceName, source, serverUtils) {
      const normInstanceName = cloudInstanceName.toLowerCase();
      const [org, instanceName] = normInstanceName.split("/");
      const domainName = `${instanceName}--${org}`;
      if (domainName.length > DOMAIN_NAME_MAX_LEN) {
        throw new errors_1.InterfaceError(`invalid instance name: cloud instance name length cannot exceed ${DOMAIN_NAME_MAX_LEN - 1} characters: ${cloudInstanceName}`);
      }
      let secretKey = config.secretKey;
      if (secretKey == null) {
        try {
          if (!serverUtils) {
            throw new errors_1.InterfaceError(`Cannot get secret key from cloud profile in browser (or edge runtime) environment`);
          }
          const profile = config.cloudProfile;
          const profilePath = await serverUtils.searchConfigDir("cloud-credentials", `${profile}.json`);
          const fileData = await serverUtils.readFileUtf8(profilePath);
          secretKey = JSON.parse(fileData)["secret_key"];
          if (!secretKey) {
            throw new errors_1.InterfaceError(`Cloud profile '${profile}' doesn't contain a secret key`);
          }
          config.setSecretKey(secretKey, `cloud-credentials/${profile}.json`);
        } catch (e6) {
          throw new errors_1.InterfaceError(`Cannot connect to cloud instances without a secret key: ${e6}`);
        }
      }
      try {
        const keyParts = secretKey.split(".");
        if (keyParts.length < 2) {
          throw new errors_1.InterfaceError("Invalid secret key: does not contain payload");
        }
        const dnsZone = _jwtBase64Decode(keyParts[1])["iss"];
        if (!dnsZone) {
          throw new errors_1.InterfaceError("Invalid secret key: payload does not contain 'iss' value");
        }
        const dnsBucket = ((0, crcHqx_1.crcHqx)(buffer_1.utf8Encoder.encode(normInstanceName), 0) % 100).toString(10).padStart(2, "0");
        const host = `${domainName}.c-${dnsBucket}.i.${dnsZone}`;
        config.setHost(host, `resolved from 'secretKey' and ${source}`);
      } catch (e6) {
        if (e6 instanceof errors.GelError) {
          throw e6;
        } else {
          throw new errors_1.InterfaceError(`Invalid secret key: ${e6}`);
        }
      }
    }
    function _jwtBase64Decode(payload) {
      return JSON.parse(buffer_1.utf8Decoder.decode((0, buffer_1.decodeB64)(payload.padEnd(Math.ceil(payload.length / 4) * 4, "="))));
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/conUtils.server.js
var require_conUtils_server = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/conUtils.server.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      var desc = Object.getOwnPropertyDescriptor(m6, k5);
      if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m6[k5];
        } };
      }
      Object.defineProperty(o5, k22, desc);
    } : function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      o5[k22] = m6[k5];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v6) {
      Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
    } : function(o5, v6) {
      o5["default"] = v6;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
      }
      __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.parseConnectArguments = exports2.serverUtils = void 0;
    exports2.findStashPath = findStashPath;
    var platform2 = __importStar(require_platform());
    var node_fs_1 = require("fs");
    var node_path_1 = __importDefault(require("path"));
    var systemUtils_1 = require_systemUtils();
    var conUtils_1 = require_conUtils();
    var projectDirCache = /* @__PURE__ */ new Map();
    async function findProjectDir(required = true) {
      if (!required && !(0, systemUtils_1.hasFSReadPermission)()) {
        return null;
      }
      const workingDir = process.cwd();
      if (projectDirCache.has(workingDir)) {
        return projectDirCache.get(workingDir);
      }
      let dir = workingDir;
      const cwdDev = (await node_fs_1.promises.stat(dir)).dev;
      while (true) {
        if (await (0, systemUtils_1.exists)(node_path_1.default.join(dir, "edgedb.toml")) || await (0, systemUtils_1.exists)(node_path_1.default.join(dir, "gel.toml"))) {
          projectDirCache.set(workingDir, dir);
          return dir;
        }
        const parentDir = node_path_1.default.join(dir, "..");
        if (parentDir === dir || (await node_fs_1.promises.stat(parentDir)).dev !== cwdDev) {
          projectDirCache.set(workingDir, null);
          return null;
        }
        dir = parentDir;
      }
    }
    async function findStashPath(projectDir) {
      let projectPath = await node_fs_1.promises.realpath(projectDir);
      if (platform2.isWindows && !projectPath.startsWith("\\\\")) {
        projectPath = "\\\\?\\" + projectPath;
      }
      const hash = (0, systemUtils_1.hashSHA1toHex)(projectPath);
      const baseName = node_path_1.default.basename(projectPath);
      const dirName = baseName + "-" + hash;
      return platform2.searchConfigDir("projects", dirName);
    }
    exports2.serverUtils = {
      findProjectDir,
      findStashPath,
      readFileUtf8: systemUtils_1.readFileUtf8,
      searchConfigDir: platform2.searchConfigDir
    };
    exports2.parseConnectArguments = (0, conUtils_1.getConnectArgumentsParser)(exports2.serverUtils);
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/map.js
var require_map = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/map.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      var desc = Object.getOwnPropertyDescriptor(m6, k5);
      if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m6[k5];
        } };
      }
      Object.defineProperty(o5, k22, desc);
    } : function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      o5[k22] = m6[k5];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v6) {
      Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
    } : function(o5, v6) {
      o5["default"] = v6;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.errorMapping = void 0;
    var errors = __importStar(require_errors());
    exports2.errorMapping = /* @__PURE__ */ new Map();
    exports2.errorMapping.set(16777216, errors.InternalServerError);
    exports2.errorMapping.set(33554432, errors.UnsupportedFeatureError);
    exports2.errorMapping.set(50331648, errors.ProtocolError);
    exports2.errorMapping.set(50397184, errors.BinaryProtocolError);
    exports2.errorMapping.set(50397185, errors.UnsupportedProtocolVersionError);
    exports2.errorMapping.set(50397186, errors.TypeSpecNotFoundError);
    exports2.errorMapping.set(50397187, errors.UnexpectedMessageError);
    exports2.errorMapping.set(50462720, errors.InputDataError);
    exports2.errorMapping.set(50462976, errors.ParameterTypeMismatchError);
    exports2.errorMapping.set(50463232, errors.StateMismatchError);
    exports2.errorMapping.set(50528256, errors.ResultCardinalityMismatchError);
    exports2.errorMapping.set(50593792, errors.CapabilityError);
    exports2.errorMapping.set(50594048, errors.UnsupportedCapabilityError);
    exports2.errorMapping.set(50594304, errors.DisabledCapabilityError);
    exports2.errorMapping.set(50594560, errors.UnsafeIsolationLevelError);
    exports2.errorMapping.set(67108864, errors.QueryError);
    exports2.errorMapping.set(67174400, errors.InvalidSyntaxError);
    exports2.errorMapping.set(67174656, errors.EdgeQLSyntaxError);
    exports2.errorMapping.set(67174912, errors.SchemaSyntaxError);
    exports2.errorMapping.set(67175168, errors.GraphQLSyntaxError);
    exports2.errorMapping.set(67239936, errors.InvalidTypeError);
    exports2.errorMapping.set(67240192, errors.InvalidTargetError);
    exports2.errorMapping.set(67240193, errors.InvalidLinkTargetError);
    exports2.errorMapping.set(67240194, errors.InvalidPropertyTargetError);
    exports2.errorMapping.set(67305472, errors.InvalidReferenceError);
    exports2.errorMapping.set(67305473, errors.UnknownModuleError);
    exports2.errorMapping.set(67305474, errors.UnknownLinkError);
    exports2.errorMapping.set(67305475, errors.UnknownPropertyError);
    exports2.errorMapping.set(67305476, errors.UnknownUserError);
    exports2.errorMapping.set(67305477, errors.UnknownDatabaseError);
    exports2.errorMapping.set(67305478, errors.UnknownParameterError);
    exports2.errorMapping.set(67305479, errors.DeprecatedScopingError);
    exports2.errorMapping.set(67371008, errors.SchemaError);
    exports2.errorMapping.set(67436544, errors.SchemaDefinitionError);
    exports2.errorMapping.set(67436800, errors.InvalidDefinitionError);
    exports2.errorMapping.set(67436801, errors.InvalidModuleDefinitionError);
    exports2.errorMapping.set(67436802, errors.InvalidLinkDefinitionError);
    exports2.errorMapping.set(67436803, errors.InvalidPropertyDefinitionError);
    exports2.errorMapping.set(67436804, errors.InvalidUserDefinitionError);
    exports2.errorMapping.set(67436805, errors.InvalidDatabaseDefinitionError);
    exports2.errorMapping.set(67436806, errors.InvalidOperatorDefinitionError);
    exports2.errorMapping.set(67436807, errors.InvalidAliasDefinitionError);
    exports2.errorMapping.set(67436808, errors.InvalidFunctionDefinitionError);
    exports2.errorMapping.set(67436809, errors.InvalidConstraintDefinitionError);
    exports2.errorMapping.set(67436810, errors.InvalidCastDefinitionError);
    exports2.errorMapping.set(67437056, errors.DuplicateDefinitionError);
    exports2.errorMapping.set(67437057, errors.DuplicateModuleDefinitionError);
    exports2.errorMapping.set(67437058, errors.DuplicateLinkDefinitionError);
    exports2.errorMapping.set(67437059, errors.DuplicatePropertyDefinitionError);
    exports2.errorMapping.set(67437060, errors.DuplicateUserDefinitionError);
    exports2.errorMapping.set(67437061, errors.DuplicateDatabaseDefinitionError);
    exports2.errorMapping.set(67437062, errors.DuplicateOperatorDefinitionError);
    exports2.errorMapping.set(67437063, errors.DuplicateViewDefinitionError);
    exports2.errorMapping.set(67437064, errors.DuplicateFunctionDefinitionError);
    exports2.errorMapping.set(67437065, errors.DuplicateConstraintDefinitionError);
    exports2.errorMapping.set(67437066, errors.DuplicateCastDefinitionError);
    exports2.errorMapping.set(67437067, errors.DuplicateMigrationError);
    exports2.errorMapping.set(67502080, errors.SessionTimeoutError);
    exports2.errorMapping.set(67502336, errors.IdleSessionTimeoutError);
    exports2.errorMapping.set(67502592, errors.QueryTimeoutError);
    exports2.errorMapping.set(67504640, errors.TransactionTimeoutError);
    exports2.errorMapping.set(67504641, errors.IdleTransactionTimeoutError);
    exports2.errorMapping.set(83886080, errors.ExecutionError);
    exports2.errorMapping.set(83951616, errors.InvalidValueError);
    exports2.errorMapping.set(83951617, errors.DivisionByZeroError);
    exports2.errorMapping.set(83951618, errors.NumericOutOfRangeError);
    exports2.errorMapping.set(83951619, errors.AccessPolicyError);
    exports2.errorMapping.set(83951620, errors.QueryAssertionError);
    exports2.errorMapping.set(84017152, errors.IntegrityError);
    exports2.errorMapping.set(84017153, errors.ConstraintViolationError);
    exports2.errorMapping.set(84017154, errors.CardinalityViolationError);
    exports2.errorMapping.set(84017155, errors.MissingRequiredError);
    exports2.errorMapping.set(84082688, errors.TransactionError);
    exports2.errorMapping.set(84082944, errors.TransactionConflictError);
    exports2.errorMapping.set(84082945, errors.TransactionSerializationError);
    exports2.errorMapping.set(84082946, errors.TransactionDeadlockError);
    exports2.errorMapping.set(84148224, errors.WatchError);
    exports2.errorMapping.set(100663296, errors.ConfigurationError);
    exports2.errorMapping.set(117440512, errors.AccessError);
    exports2.errorMapping.set(117506048, errors.AuthenticationError);
    exports2.errorMapping.set(134217728, errors.AvailabilityError);
    exports2.errorMapping.set(134217729, errors.BackendUnavailableError);
    exports2.errorMapping.set(134217730, errors.ServerOfflineError);
    exports2.errorMapping.set(134217731, errors.UnknownTenantError);
    exports2.errorMapping.set(134217732, errors.ServerBlockedError);
    exports2.errorMapping.set(150994944, errors.BackendError);
    exports2.errorMapping.set(150995200, errors.UnsupportedBackendFeatureError);
    exports2.errorMapping.set(4026531840, errors.LogMessage);
    exports2.errorMapping.set(4026597376, errors.WarningMessage);
    exports2.errorMapping.set(4026662912, errors.StatusMessage);
    exports2.errorMapping.set(4026662913, errors.MigrationStatusMessage);
    exports2.errorMapping.set(4278190080, errors.ClientError);
    exports2.errorMapping.set(4278255616, errors.ClientConnectionError);
    exports2.errorMapping.set(4278255872, errors.ClientConnectionFailedError);
    exports2.errorMapping.set(4278255873, errors.ClientConnectionFailedTemporarilyError);
    exports2.errorMapping.set(4278256128, errors.ClientConnectionTimeoutError);
    exports2.errorMapping.set(4278256384, errors.ClientConnectionClosedError);
    exports2.errorMapping.set(4278321152, errors.InterfaceError);
    exports2.errorMapping.set(4278321408, errors.QueryArgumentError);
    exports2.errorMapping.set(4278321409, errors.MissingArgumentError);
    exports2.errorMapping.set(4278321410, errors.UnknownArgumentError);
    exports2.errorMapping.set(4278321411, errors.InvalidArgumentError);
    exports2.errorMapping.set(4278386688, errors.NoDataError);
    exports2.errorMapping.set(4278452224, errors.InternalClientError);
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/resolve.js
var require_resolve = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/resolve.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      var desc = Object.getOwnPropertyDescriptor(m6, k5);
      if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m6[k5];
        } };
      }
      Object.defineProperty(o5, k22, desc);
    } : function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      o5[k22] = m6[k5];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v6) {
      Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
    } : function(o5, v6) {
      o5["default"] = v6;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.resolveErrorCode = resolveErrorCode;
    exports2.errorFromJSON = errorFromJSON;
    var errors = __importStar(require_errors());
    var base_1 = require_base();
    var map_1 = require_map();
    function resolveErrorCode(code) {
      let result;
      result = map_1.errorMapping.get(code);
      if (result) {
        return result;
      }
      code = code & 4294967040;
      result = map_1.errorMapping.get(code);
      if (result) {
        return result;
      }
      code = code & 4294901760;
      result = map_1.errorMapping.get(code);
      if (result) {
        return result;
      }
      code = code & 4278190080;
      result = map_1.errorMapping.get(code);
      if (result) {
        return result;
      }
      return errors.GelError;
    }
    var _JSON_FIELDS = {
      hint: base_1.ErrorAttr.hint,
      details: base_1.ErrorAttr.details,
      start: base_1.ErrorAttr.characterStart,
      end: base_1.ErrorAttr.characterEnd,
      line: base_1.ErrorAttr.lineStart,
      col: base_1.ErrorAttr.columnStart
    };
    function errorFromJSON(data) {
      const errType = resolveErrorCode(data.code);
      const err2 = new errType(data.message);
      const attrs = /* @__PURE__ */ new Map();
      for (const [name, field] of Object.entries(_JSON_FIELDS)) {
        if (data[name] != null) {
          attrs.set(field, data[name]);
        }
      }
      err2._attrs = attrs;
      return err2;
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/baseConn.js
var require_baseConn = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/baseConn.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      var desc = Object.getOwnPropertyDescriptor(m6, k5);
      if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m6[k5];
        } };
      }
      Object.defineProperty(o5, k22, desc);
    } : function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      o5[k22] = m6[k5];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v6) {
      Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
    } : function(o5, v6) {
      o5["default"] = v6;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
      }
      __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.BaseRawConnection = exports2.RESTRICTED_CAPABILITIES = exports2.Capabilities = exports2.PROTO_VER_MIN = exports2.PROTO_VER = void 0;
    var codecs_1 = require_codecs();
    var object_1 = require_object();
    var utils_1 = require_utils2();
    var errors = __importStar(require_errors());
    var resolve_1 = require_resolve();
    var context_1 = require_context();
    var ifaces_1 = require_ifaces2();
    var buffer_1 = require_buffer();
    var chars = __importStar(require_chars());
    var event_1 = __importDefault(require_event());
    var lru_1 = __importDefault(require_lru());
    var options_1 = require_options();
    exports2.PROTO_VER = [3, 0];
    exports2.PROTO_VER_MIN = [0, 9];
    var TransactionStatus;
    (function(TransactionStatus2) {
      TransactionStatus2[TransactionStatus2["TRANS_IDLE"] = 0] = "TRANS_IDLE";
      TransactionStatus2[TransactionStatus2["TRANS_ACTIVE"] = 1] = "TRANS_ACTIVE";
      TransactionStatus2[TransactionStatus2["TRANS_INTRANS"] = 2] = "TRANS_INTRANS";
      TransactionStatus2[TransactionStatus2["TRANS_INERROR"] = 3] = "TRANS_INERROR";
      TransactionStatus2[TransactionStatus2["TRANS_UNKNOWN"] = 4] = "TRANS_UNKNOWN";
    })(TransactionStatus || (TransactionStatus = {}));
    var Capabilities;
    (function(Capabilities2) {
      Capabilities2[Capabilities2["NONE"] = 0] = "NONE";
      Capabilities2[Capabilities2["MODIFICATONS"] = 1] = "MODIFICATONS";
      Capabilities2[Capabilities2["SESSION_CONFIG"] = 2] = "SESSION_CONFIG";
      Capabilities2[Capabilities2["TRANSACTION"] = 4] = "TRANSACTION";
      Capabilities2[Capabilities2["DDL"] = 8] = "DDL";
      Capabilities2[Capabilities2["PERSISTENT_CONFIG"] = 16] = "PERSISTENT_CONFIG";
      Capabilities2[Capabilities2["SET_GLOBAL"] = 32] = "SET_GLOBAL";
      Capabilities2[Capabilities2["ALL"] = 4294967295] = "ALL";
    })(Capabilities || (exports2.Capabilities = Capabilities = {}));
    var NO_TRANSACTION_CAPABILITIES = (Capabilities.ALL & ~Capabilities.TRANSACTION) >>> 0;
    var NO_TRANSACTION_CAPABILITIES_BYTES = new Uint8Array(Array(8).fill(255));
    new DataView(NO_TRANSACTION_CAPABILITIES_BYTES.buffer).setUint32(4, NO_TRANSACTION_CAPABILITIES);
    exports2.RESTRICTED_CAPABILITIES = (Capabilities.ALL & ~Capabilities.TRANSACTION & ~Capabilities.SESSION_CONFIG & ~Capabilities.SET_GLOBAL) >>> 0;
    var CompilationFlag;
    (function(CompilationFlag2) {
      CompilationFlag2[CompilationFlag2["INJECT_OUTPUT_TYPE_IDS"] = 1] = "INJECT_OUTPUT_TYPE_IDS";
      CompilationFlag2[CompilationFlag2["INJECT_OUTPUT_TYPE_NAMES"] = 2] = "INJECT_OUTPUT_TYPE_NAMES";
      CompilationFlag2[CompilationFlag2["INJECT_OUTPUT_OBJECT_IDS"] = 4] = "INJECT_OUTPUT_OBJECT_IDS";
    })(CompilationFlag || (CompilationFlag = {}));
    var OLD_ERROR_CODES = /* @__PURE__ */ new Map([
      [84082689, 84082945],
      [84082690, 84082946]
    ]);
    var BaseRawConnection = class {
      constructor(registry) {
        __publicField(this, "connected", false);
        __publicField(this, "lastStatus");
        __publicField(this, "codecsRegistry");
        __publicField(this, "queryCodecCache");
        __publicField(this, "serverSecret");
        __publicField(this, "serverSettings");
        __publicField(this, "serverXactStatus");
        __publicField(this, "buffer");
        __publicField(this, "messageWaiter");
        __publicField(this, "connWaiter");
        __publicField(this, "connAbortWaiter");
        __publicField(this, "_abortedWith", null);
        __publicField(this, "protocolVersion", exports2.PROTO_VER);
        __publicField(this, "stateCodec", codecs_1.INVALID_CODEC);
        __publicField(this, "stateCache", /* @__PURE__ */ new WeakMap());
        __publicField(this, "lastStateUpdate", null);
        __publicField(this, "adminUIMode", false);
        this.buffer = new buffer_1.ReadMessageBuffer();
        this.codecsRegistry = registry;
        this.queryCodecCache = new lru_1.default({ capacity: 1e3 });
        this.lastStatus = null;
        this.serverSecret = null;
        this.serverSettings = {};
        this.serverXactStatus = TransactionStatus.TRANS_UNKNOWN;
        this.messageWaiter = null;
        this.connWaiter = new event_1.default();
        this.connAbortWaiter = new event_1.default();
      }
      throwNotImplemented(method) {
        throw new errors.InternalClientError(`method ${method} is not implemented`);
      }
      async _waitForMessage() {
        this.throwNotImplemented("_waitForMessage");
      }
      _sendData(_data5) {
        this.throwNotImplemented("_sendData");
      }
      getConnAbortError() {
        return this._abortedWith ?? new errors.InterfaceError(`client has been closed`);
      }
      _checkState() {
        if (this.isClosed()) {
          throw this.getConnAbortError();
        }
      }
      _abortWithError(err2) {
        this._abortedWith = err2;
        this._abort();
      }
      _ignoreHeaders() {
        let numFields = this.buffer.readInt16();
        while (numFields) {
          this.buffer.readInt16();
          this.buffer.readLenPrefixedBuffer();
          numFields--;
        }
      }
      _readHeaders() {
        const numFields = this.buffer.readInt16();
        const headers = {};
        for (let i6 = 0; i6 < numFields; i6++) {
          const key = this.buffer.readString();
          const value = this.buffer.readString();
          headers[key] = value;
        }
        return headers;
      }
      _abortWaiters(err2) {
        if (!this.connWaiter.done) {
          this.connWaiter.setError(err2);
        }
        this.messageWaiter?.setError(err2);
        this.messageWaiter = null;
      }
      _parseHeaders() {
        const ret = /* @__PURE__ */ new Map();
        let numFields = this.buffer.readInt16();
        while (numFields) {
          const key = this.buffer.readInt16();
          const value = this.buffer.readLenPrefixedBuffer();
          ret.set(key, value);
          numFields--;
        }
        return ret;
      }
      _parseDescribeTypeMessage(query) {
        let capabilities = -1;
        let warnings = [];
        let unsafeIsolationDangers = [];
        const headers = this._readHeaders();
        if (headers.warnings != null) {
          warnings = JSON.parse(headers.warnings).map((warning3) => {
            const err2 = (0, resolve_1.errorFromJSON)(warning3);
            err2._query = query;
            return err2;
          });
        }
        if (headers.unsafe_isolation_dangers != null) {
          unsafeIsolationDangers = JSON.parse(headers.unsafe_isolation_dangers).map((danger) => {
            const err2 = (0, resolve_1.errorFromJSON)(danger);
            err2._query = query;
            return err2;
          });
        }
        capabilities = Number(this.buffer.readBigInt64());
        const cardinality = this.buffer.readChar();
        const inTypeId = this.buffer.readUUID();
        const inTypeData = this.buffer.readLenPrefixedBuffer();
        const outTypeId = this.buffer.readUUID();
        const outTypeData = this.buffer.readLenPrefixedBuffer();
        this.buffer.finishMessage();
        let inCodec = this.codecsRegistry.getCodec(inTypeId);
        if (inCodec == null) {
          inCodec = this.codecsRegistry.buildCodec(inTypeData, this.protocolVersion);
        }
        let outCodec = this.codecsRegistry.getCodec(outTypeId);
        if (outCodec == null) {
          outCodec = this.codecsRegistry.buildCodec(outTypeData, this.protocolVersion);
        }
        return [
          cardinality,
          inCodec,
          outCodec,
          capabilities,
          inTypeData,
          outTypeData,
          warnings,
          unsafeIsolationDangers
        ];
      }
      _parseCommandCompleteMessage() {
        this._ignoreHeaders();
        this.buffer.readBigInt64();
        const status = this.buffer.readString();
        const stateTypeId = this.buffer.readUUID();
        const stateData = this.buffer.readLenPrefixedBuffer();
        if (this.adminUIMode && stateTypeId === this.stateCodec.tid) {
          this.lastStateUpdate = this.stateCodec.decode(new buffer_1.ReadBuffer(stateData), context_1.NOOP_CODEC_CONTEXT);
        }
        this.buffer.finishMessage();
        return status;
      }
      _parseErrorMessage() {
        this.buffer.readChar();
        const code = this.buffer.readUInt32();
        const message = this.buffer.readString();
        const errorType = (0, resolve_1.resolveErrorCode)(OLD_ERROR_CODES.get(code) ?? code);
        const err2 = new errorType(message);
        err2._attrs = this._parseHeaders();
        this.buffer.finishMessage();
        if (err2 instanceof errors.AuthenticationError) {
          throw err2;
        }
        return err2;
      }
      _parseSyncMessage() {
        this._parseHeaders();
        const status = this.buffer.readChar();
        switch (status) {
          case chars.$I:
            this.serverXactStatus = TransactionStatus.TRANS_IDLE;
            break;
          case chars.$T:
            this.serverXactStatus = TransactionStatus.TRANS_INTRANS;
            break;
          case chars.$E:
            this.serverXactStatus = TransactionStatus.TRANS_INERROR;
            break;
          default:
            this.serverXactStatus = TransactionStatus.TRANS_UNKNOWN;
        }
        this.buffer.finishMessage();
      }
      _redirectDataMessages(result) {
        const $D = chars.$D;
        const buffer = this.buffer;
        while (buffer.takeMessageType($D)) {
          const msg = buffer.consumeMessage();
          result.writeChar($D);
          result.writeInt32(msg.length + 4);
          result.writeBuffer(msg);
        }
      }
      _parseDataMessages(codec, result, ctx) {
        const frb = buffer_1.ReadBuffer.alloc();
        const $D = chars.$D;
        const buffer = this.buffer;
        if (Array.isArray(result)) {
          while (buffer.takeMessageType($D)) {
            buffer.consumeMessageInto(frb);
            frb.discard(6);
            result.push(codec.decode(frb, ctx));
            frb.finish();
          }
        } else {
          this._redirectDataMessages(result);
        }
      }
      _parseServerSettings(name, value) {
        switch (name) {
          case "suggested_pool_concurrency": {
            this.serverSettings.suggested_pool_concurrency = parseInt(buffer_1.utf8Decoder.decode(value), 10);
            break;
          }
          case "system_config": {
            const buf = new buffer_1.ReadBuffer(value);
            const typedescLen = buf.readInt32() - 16;
            const typedescId = buf.readUUID();
            const typedesc = buf.readBuffer(typedescLen);
            let codec = this.codecsRegistry.getCodec(typedescId);
            if (codec === null) {
              codec = this.codecsRegistry.buildCodec(typedesc, this.protocolVersion);
            }
            buf.discard(4);
            const data = codec.decode(buf, context_1.NOOP_CODEC_CONTEXT);
            buf.finish();
            this.serverSettings.system_config = data;
            break;
          }
          default:
            this.serverSettings[name] = value;
            break;
        }
      }
      _parseDescribeStateMessage() {
        const typedescId = this.buffer.readUUID();
        const typedesc = this.buffer.readBuffer(this.buffer.readInt32());
        let codec = this.codecsRegistry.getCodec(typedescId);
        if (codec === null) {
          codec = this.codecsRegistry.buildCodec(typedesc, this.protocolVersion);
        }
        this.stateCodec = codec;
        this.stateCache = /* @__PURE__ */ new WeakMap();
        this.buffer.finishMessage();
      }
      _fallthrough() {
        const mtype = this.buffer.getMessageType();
        switch (mtype) {
          case chars.$S: {
            const name = this.buffer.readString();
            const value = this.buffer.readLenPrefixedBuffer();
            this._parseServerSettings(name, value);
            this.buffer.finishMessage();
            break;
          }
          case chars.$L: {
            const severity = this.buffer.readChar();
            const code = this.buffer.readUInt32();
            const message = this.buffer.readString();
            this._parseHeaders();
            this.buffer.finishMessage();
            console.info("SERVER MESSAGE", severity, code, message);
            break;
          }
          default:
            throw new errors.UnexpectedMessageError(`unexpected message type ${mtype} ("${chars.chr(mtype)}")`);
        }
      }
      _encodeArgs(args, inCodec, ctx) {
        if (inCodec === codecs_1.NULL_CODEC) {
          if (args != null) {
            throw new errors.QueryArgumentError(`This query does not contain any query parameters, but query arguments were provided to the 'query*()' method`);
          }
          return codecs_1.NullCodec.BUFFER;
        }
        if (inCodec instanceof object_1.ObjectCodec) {
          return inCodec.encodeArgs(args, ctx);
        }
        throw new errors.ProtocolError("invalid input codec");
      }
      _isInTransaction() {
        return this.serverXactStatus === TransactionStatus.TRANS_INTRANS || this.serverXactStatus === TransactionStatus.TRANS_ACTIVE;
      }
      _setStateCodec(state2) {
        let encodedState = this.stateCache.get(state2);
        if (encodedState) {
          return encodedState;
        }
        const buf = new buffer_1.WriteBuffer();
        this.stateCodec.encode(buf, state2._serialise(), context_1.NOOP_CODEC_CONTEXT);
        encodedState = buf.unwrap();
        this.stateCache.set(state2, encodedState);
        return encodedState;
      }
      _encodeParseParams(wb, query, outputFormat, expectedCardinality, state2, capabilitiesFlags, options, language, isExecute, unsafeIsolationDangers) {
        if ((0, utils_1.versionGreaterThanOrEqual)(this.protocolVersion, [3, 0])) {
          if (state2.annotations.size >= 1 << 16) {
            throw new errors.InternalClientError("too many annotations");
          }
          wb.writeUInt16(state2.annotations.size);
          for (const [name, value] of state2.annotations) {
            wb.writeString(name);
            wb.writeString(value);
          }
        } else {
          wb.writeUInt16(0);
        }
        wb.writeFlags(4294967295, capabilitiesFlags);
        wb.writeFlags(0, 0 | (options?.injectObjectids ? CompilationFlag.INJECT_OUTPUT_OBJECT_IDS : 0) | (options?.injectTypeids ? CompilationFlag.INJECT_OUTPUT_TYPE_IDS : 0) | (options?.injectTypenames ? CompilationFlag.INJECT_OUTPUT_TYPE_NAMES : 0));
        wb.writeBigInt64(options?.implicitLimit ?? BigInt(0));
        if ((0, utils_1.versionGreaterThanOrEqual)(this.protocolVersion, [3, 0])) {
          wb.writeChar(language);
        }
        wb.writeChar(outputFormat);
        wb.writeChar(expectedCardinality === ifaces_1.Cardinality.ONE || expectedCardinality === ifaces_1.Cardinality.AT_MOST_ONE ? ifaces_1.Cardinality.AT_MOST_ONE : ifaces_1.Cardinality.MANY);
        wb.writeString(query);
        if (!this.adminUIMode && state2.isDefaultSession()) {
          wb.writeBuffer(codecs_1.NULL_CODEC.tidBuffer);
          wb.writeInt32(0);
        } else {
          wb.writeBuffer(this.stateCodec.tidBuffer);
          if (this.stateCodec === codecs_1.INVALID_CODEC || this.stateCodec === codecs_1.NULL_CODEC) {
            wb.writeInt32(0);
          } else {
            if ((0, utils_1.versionGreaterThanOrEqual)(this.protocolVersion, [3, 0]) && isExecute && !this._isInTransaction()) {
              const isolation = state2.transactionOptions.isolation === options_1.IsolationLevel.PreferRepeatableRead ? unsafeIsolationDangers.length === 0 ? options_1.IsolationLevel.RepeatableRead : options_1.IsolationLevel.Serializable : state2.transactionOptions.isolation;
              if (isolation !== state2.config.get("default_transaction_isolation")) {
                state2 = state2.withConfig({
                  default_transaction_isolation: isolation
                }).withTransactionOptions({
                  isolation
                });
              }
              if (state2.transactionOptions.readonly !== state2.config.get("default_transaction_access_mode")) {
                state2 = state2.withConfig({
                  default_transaction_access_mode: state2.transactionOptions.readonly ? "ReadOnly" : "ReadWrite"
                });
              }
            }
            const encodedState = this._setStateCodec(state2);
            wb.writeBuffer(encodedState);
          }
        }
      }
      async _parse(language, query, outputFormat, expectedCardinality, state2, capabilitiesFlags = exports2.RESTRICTED_CAPABILITIES, options, unsafeIsolationDangers = []) {
        const wb = new buffer_1.WriteMessageBuffer();
        wb.beginMessage(chars.$P);
        this._encodeParseParams(wb, query, outputFormat, expectedCardinality, state2, capabilitiesFlags, options, language, false, unsafeIsolationDangers);
        wb.endMessage();
        wb.writeSync();
        this._sendData(wb.unwrap());
        let parsing = true;
        let error2 = null;
        let newCard = null;
        let capabilities = -1;
        let inCodec = null;
        let outCodec = null;
        let inCodecBuf = null;
        let outCodecBuf = null;
        let warnings = [];
        while (parsing) {
          if (!this.buffer.takeMessage()) {
            await this._waitForMessage();
          }
          const mtype = this.buffer.getMessageType();
          switch (mtype) {
            case chars.$T: {
              try {
                [
                  newCard,
                  inCodec,
                  outCodec,
                  capabilities,
                  inCodecBuf,
                  outCodecBuf,
                  warnings,
                  unsafeIsolationDangers
                ] = this._parseDescribeTypeMessage(query);
                const key = this._getQueryCacheKey(query, outputFormat, expectedCardinality);
                this.queryCodecCache.set(key, [
                  newCard,
                  inCodec,
                  outCodec,
                  capabilities,
                  unsafeIsolationDangers
                ]);
              } catch (e6) {
                error2 = e6;
              }
              break;
            }
            case chars.$E: {
              error2 = this._parseErrorMessage();
              error2._query = query;
              break;
            }
            case chars.$s: {
              options_1.Options.signalSchemaChange();
              this._parseDescribeStateMessage();
              break;
            }
            case chars.$Z: {
              this._parseSyncMessage();
              parsing = false;
              break;
            }
            default:
              this._fallthrough();
          }
        }
        if (error2 !== null) {
          if (error2 instanceof errors.StateMismatchError) {
            return this._parse(language, query, outputFormat, expectedCardinality, state2, capabilitiesFlags, options, unsafeIsolationDangers);
          }
          throw error2;
        }
        return [
          newCard,
          inCodec,
          outCodec,
          capabilities,
          inCodecBuf,
          outCodecBuf,
          warnings,
          unsafeIsolationDangers
        ];
      }
      async _executeFlow(language, query, args, outputFormat, expectedCardinality, state2, inCodec, outCodec, result, capabilitiesFlags = exports2.RESTRICTED_CAPABILITIES, options, unsafeIsolationDangers = []) {
        let currentUnsafeIsolationDangers = unsafeIsolationDangers;
        let ctx = state2.makeCodecContext();
        const wb = new buffer_1.WriteMessageBuffer();
        wb.beginMessage(chars.$O);
        this._encodeParseParams(wb, query, outputFormat, expectedCardinality, state2, capabilitiesFlags, options, language, true, currentUnsafeIsolationDangers);
        wb.writeBuffer(inCodec.tidBuffer);
        wb.writeBuffer(outCodec.tidBuffer);
        if (inCodec) {
          wb.writeBuffer(this._encodeArgs(args, inCodec, ctx));
        } else {
          wb.writeInt32(0);
        }
        wb.endMessage();
        wb.writeSync();
        this._sendData(wb.unwrap());
        let error2 = null;
        let parsing = true;
        let currentWarnings = [];
        while (parsing) {
          if (!this.buffer.takeMessage()) {
            await this._waitForMessage();
          }
          const mtype = this.buffer.getMessageType();
          switch (mtype) {
            case chars.$D: {
              if (error2 == null) {
                try {
                  this._parseDataMessages(outCodec, result, ctx);
                } catch (e6) {
                  error2 = e6;
                  this.buffer.finishMessage();
                }
              } else {
                this.buffer.discardMessage();
              }
              break;
            }
            case chars.$C: {
              this.lastStatus = this._parseCommandCompleteMessage();
              break;
            }
            case chars.$Z: {
              this._parseSyncMessage();
              parsing = false;
              break;
            }
            case chars.$T: {
              try {
                ctx = state2.makeCodecContext();
                const [newCard, newInCodec, newOutCodec, capabilities, _3, __, _warnings, _dangers] = this._parseDescribeTypeMessage(query);
                if (outCodec !== codecs_1.NULL_CODEC && outCodec.tid !== newOutCodec.tid || inCodec !== codecs_1.NULL_CODEC && inCodec.tid !== newInCodec.tid) {
                  options_1.Options.signalSchemaChange();
                  ctx = state2.makeCodecContext();
                }
                const key = this._getQueryCacheKey(query, outputFormat, expectedCardinality);
                this.queryCodecCache.set(key, [
                  newCard,
                  newInCodec,
                  newOutCodec,
                  capabilities,
                  _dangers
                ]);
                outCodec = newOutCodec;
                currentWarnings = _warnings;
                currentUnsafeIsolationDangers = _dangers;
              } catch (e6) {
                options_1.Options.signalSchemaChange();
                error2 = e6;
              }
              break;
            }
            case chars.$s: {
              options_1.Options.signalSchemaChange();
              this._parseDescribeStateMessage();
              break;
            }
            case chars.$E: {
              error2 = this._parseErrorMessage();
              error2._query = query;
              break;
            }
            default:
              this._fallthrough();
          }
        }
        if (error2 != null) {
          if (error2 instanceof errors.StateMismatchError) {
            return this._executeFlow(language, query, args, outputFormat, expectedCardinality, state2, inCodec, outCodec, result, capabilitiesFlags, options, currentUnsafeIsolationDangers);
          }
          throw error2;
        }
        return [currentWarnings, currentUnsafeIsolationDangers];
      }
      _getQueryCacheKey(query, outputFormat, expectedCardinality, language = ifaces_1.Language.EDGEQL) {
        const expectOne = expectedCardinality === ifaces_1.Cardinality.ONE || expectedCardinality === ifaces_1.Cardinality.AT_MOST_ONE;
        return [language, outputFormat, expectOne, query.length, query].join(";");
      }
      _validateFetchCardinality(card, outputFormat, expectedCardinality) {
        if (expectedCardinality === ifaces_1.Cardinality.ONE && card === ifaces_1.Cardinality.NO_RESULT) {
          throw new errors.NoDataError(`query executed via queryRequiredSingle${outputFormat === ifaces_1.OutputFormat.JSON ? "JSON" : ""}() returned no data`);
        }
      }
      async fetch(query, args = null, outputFormat, expectedCardinality, state2, privilegedMode = false, language = ifaces_1.Language.EDGEQL) {
        if (language !== ifaces_1.Language.EDGEQL && (0, utils_1.versionGreaterThan)([3, 0], this.protocolVersion)) {
          throw new errors.UnsupportedFeatureError(`the server does not support SQL queries, upgrade to 6.0 or newer`);
        }
        this._checkState();
        const requiredOne = expectedCardinality === ifaces_1.Cardinality.ONE;
        const expectOne = requiredOne || expectedCardinality === ifaces_1.Cardinality.AT_MOST_ONE;
        const asJson = outputFormat === ifaces_1.OutputFormat.JSON;
        const key = this._getQueryCacheKey(query, outputFormat, expectedCardinality, language);
        const ret = [];
        let warnings = [];
        let [card, inCodec, outCodec, , unsafeIsolationDangers] = this.queryCodecCache.get(key) ?? [];
        if (card) {
          this._validateFetchCardinality(card, outputFormat, expectedCardinality);
        }
        if (!inCodec && args !== null || this.stateCodec === codecs_1.INVALID_CODEC && !state2.isDefaultSession()) {
          [card, inCodec, outCodec, , , , warnings, unsafeIsolationDangers] = await this._parse(language, query, outputFormat, expectedCardinality, state2, privilegedMode ? Capabilities.ALL : void 0, void 0, unsafeIsolationDangers);
          this._validateFetchCardinality(card, outputFormat, expectedCardinality);
        }
        try {
          [warnings, unsafeIsolationDangers] = await this._executeFlow(language, query, args, outputFormat, expectedCardinality, state2, inCodec ?? codecs_1.NULL_CODEC, outCodec ?? codecs_1.NULL_CODEC, ret, privilegedMode ? Capabilities.ALL : void 0, void 0, unsafeIsolationDangers);
        } catch (e6) {
          if (e6 instanceof errors.ParameterTypeMismatchError) {
            [card, inCodec, outCodec, , unsafeIsolationDangers] = this.queryCodecCache.get(key);
            [warnings, unsafeIsolationDangers] = await this._executeFlow(language, query, args, outputFormat, expectedCardinality, state2, inCodec ?? codecs_1.NULL_CODEC, outCodec ?? codecs_1.NULL_CODEC, ret, privilegedMode ? Capabilities.ALL : void 0);
          } else {
            throw e6;
          }
        }
        if (outputFormat === ifaces_1.OutputFormat.NONE) {
          return { result: null, warnings, unsafeIsolationDangers };
        }
        if (expectOne) {
          if (requiredOne && !ret.length) {
            throw new errors.NoDataError("query returned no data");
          } else {
            return {
              result: ret[0] ?? (asJson ? "null" : null),
              warnings,
              unsafeIsolationDangers
            };
          }
        } else {
          if (ret && ret.length) {
            if (asJson) {
              return { result: ret[0], warnings, unsafeIsolationDangers };
            } else {
              return { result: ret, warnings, unsafeIsolationDangers };
            }
          } else {
            if (asJson) {
              return { result: "[]", warnings, unsafeIsolationDangers };
            } else {
              return { result: ret, warnings, unsafeIsolationDangers };
            }
          }
        }
      }
      getQueryCapabilities(query, outputFormat, expectedCardinality) {
        const key = this._getQueryCacheKey(query, outputFormat, expectedCardinality);
        return this.queryCodecCache.get(key)?.[3] ?? null;
      }
      async resetState() {
        if (this.connected && this.serverXactStatus !== TransactionStatus.TRANS_IDLE) {
          try {
            await this.fetch(`rollback`, void 0, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, options_1.Options.defaults(), true);
          } catch {
            this._abortWithError(new errors.ClientConnectionClosedError("failed to reset state"));
          }
        }
      }
      _abort() {
        this.connected = false;
        this._abortWaiters(this.getConnAbortError());
        if (!this.connAbortWaiter.done) {
          this.connAbortWaiter.set();
        }
      }
      isClosed() {
        return !this.connected;
      }
      async close() {
        this._abort();
      }
    };
    exports2.BaseRawConnection = BaseRawConnection;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/scram.js
var require_scram = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/scram.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.saslprep = saslprep;
    exports2.getSCRAM = getSCRAM;
    var buffer_1 = require_buffer();
    var errors_1 = require_errors();
    var RAW_NONCE_LENGTH = 18;
    function saslprep(str) {
      return str.normalize("NFKC");
    }
    function getSCRAM({ randomBytes, H: H2, HMAC, makeKey }) {
      function bufferEquals(a5, b5) {
        if (a5.length !== b5.length) {
          return false;
        }
        for (let i6 = 0, len = a5.length; i6 < len; i6++) {
          if (a5[i6] !== b5[i6]) {
            return false;
          }
        }
        return true;
      }
      function generateNonce(length = RAW_NONCE_LENGTH) {
        return randomBytes(length);
      }
      function buildClientFirstMessage(clientNonce, username) {
        const bare = `n=${saslprep(username)},r=${(0, buffer_1.encodeB64)(clientNonce)}`;
        return [`n,,${bare}`, bare];
      }
      function parseServerFirstMessage(msg) {
        const attrs = msg.split(",");
        if (attrs.length < 3) {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        const nonceAttr = attrs[0];
        if (!nonceAttr || nonceAttr[0] !== "r") {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        const nonceB64 = nonceAttr.split("=", 2)[1];
        if (!nonceB64) {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        const nonce = (0, buffer_1.decodeB64)(nonceB64);
        const saltAttr = attrs[1];
        if (!saltAttr || saltAttr[0] !== "s") {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        const saltB64 = saltAttr.split("=", 2)[1];
        if (!saltB64) {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        const salt = (0, buffer_1.decodeB64)(saltB64);
        const iterAttr = attrs[2];
        if (!iterAttr || iterAttr[0] !== "i") {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        const iter = iterAttr.split("=", 2)[1];
        if (!iter || !iter.match(/^[0-9]*$/)) {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        const iterCount = parseInt(iter, 10);
        if (iterCount <= 0) {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        return [nonce, salt, iterCount];
      }
      function parseServerFinalMessage(msg) {
        const attrs = msg.split(",");
        if (attrs.length < 1) {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        const nonceAttr = attrs[0];
        if (!nonceAttr || nonceAttr[0] !== "v") {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        const signatureB64 = nonceAttr.split("=", 2)[1];
        if (!signatureB64) {
          throw new errors_1.ProtocolError("malformed SCRAM message");
        }
        return (0, buffer_1.decodeB64)(signatureB64);
      }
      async function buildClientFinalMessage(password, salt, iterations, clientFirstBare, serverFirst, serverNonce) {
        const clientFinal = `c=biws,r=${(0, buffer_1.encodeB64)(serverNonce)}`;
        const authMessage = buffer_1.utf8Encoder.encode(`${clientFirstBare},${serverFirst},${clientFinal}`);
        const saltedPassword = await _getSaltedPassword(buffer_1.utf8Encoder.encode(saslprep(password)), salt, iterations);
        const clientKey = await _getClientKey(saltedPassword);
        const storedKey = await H2(clientKey);
        const clientSignature = await HMAC(storedKey, authMessage);
        const clientProof = _XOR(clientKey, clientSignature);
        const serverKey = await _getServerKey(saltedPassword);
        const serverProof = await HMAC(serverKey, authMessage);
        return [`${clientFinal},p=${(0, buffer_1.encodeB64)(clientProof)}`, serverProof];
      }
      async function _getSaltedPassword(password, salt, iterations) {
        const msg = new Uint8Array(salt.length + 4);
        msg.set(salt);
        msg.set([0, 0, 0, 1], salt.length);
        const keyFromPassword = await makeKey(password);
        let Hi = await HMAC(keyFromPassword, msg);
        let Ui = Hi;
        for (let _3 = 0; _3 < iterations - 1; _3++) {
          Ui = await HMAC(keyFromPassword, Ui);
          Hi = _XOR(Hi, Ui);
        }
        return Hi;
      }
      function _getClientKey(saltedPassword) {
        return HMAC(saltedPassword, buffer_1.utf8Encoder.encode("Client Key"));
      }
      function _getServerKey(saltedPassword) {
        return HMAC(saltedPassword, buffer_1.utf8Encoder.encode("Server Key"));
      }
      function _XOR(a5, b5) {
        const len = a5.length;
        if (len !== b5.length) {
          throw new errors_1.ProtocolError("scram.XOR: buffers are of different lengths");
        }
        const res = new Uint8Array(len);
        for (let i6 = 0; i6 < len; i6++) {
          res[i6] = a5[i6] ^ b5[i6];
        }
        return res;
      }
      return {
        bufferEquals,
        generateNonce,
        buildClientFirstMessage,
        parseServerFirstMessage,
        parseServerFinalMessage,
        buildClientFinalMessage,
        _getSaltedPassword,
        _getClientKey,
        _getServerKey,
        _XOR
      };
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/browserCrypto.js
var require_browserCrypto = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/browserCrypto.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.cryptoUtils = void 0;
    async function makeKey(key) {
      return await crypto.subtle.importKey("raw", key, {
        name: "HMAC",
        hash: { name: "SHA-256" }
      }, false, ["sign"]);
    }
    function randomBytes(size) {
      return crypto.getRandomValues(new Uint8Array(size));
    }
    async function H2(msg) {
      return new Uint8Array(await crypto.subtle.digest("SHA-256", msg));
    }
    async function HMAC(key, msg) {
      const cryptoKey = key instanceof Uint8Array ? await makeKey(key) : key;
      return new Uint8Array(await crypto.subtle.sign("HMAC", cryptoKey, msg));
    }
    exports2.cryptoUtils = {
      makeKey,
      randomBytes,
      H: H2,
      HMAC
    };
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/nodeCrypto.js
var require_nodeCrypto = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/nodeCrypto.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.cryptoUtils = void 0;
    var node_crypto_1 = __importDefault(require("crypto"));
    function makeKey(keyBytes) {
      return Promise.resolve(keyBytes);
    }
    function randomBytes(size) {
      return node_crypto_1.default.randomBytes(size);
    }
    async function H2(msg) {
      const sign = node_crypto_1.default.createHash("sha256");
      sign.update(msg);
      return sign.digest();
    }
    async function HMAC(key, msg) {
      const cryptoKey = key instanceof Uint8Array ? key : node_crypto_1.default.KeyObject.from(key);
      const hm = node_crypto_1.default.createHmac("sha256", cryptoKey);
      hm.update(msg);
      return hm.digest();
    }
    exports2.cryptoUtils = {
      makeKey,
      randomBytes,
      H: H2,
      HMAC
    };
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/cryptoUtils.js
var require_cryptoUtils = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/cryptoUtils.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var browserCrypto_1 = require_browserCrypto();
    var isNode = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
    var cryptoUtils;
    function loadCrypto() {
      if (isNode) {
        try {
          require("crypto");
          cryptoUtils = require_nodeCrypto().cryptoUtils;
        } catch (_3) {
          if (typeof globalThis.crypto !== "undefined") {
            cryptoUtils = browserCrypto_1.cryptoUtils;
          } else {
            throw new Error("No crypto implementation found");
          }
        }
      } else {
        cryptoUtils = browserCrypto_1.cryptoUtils;
      }
    }
    loadCrypto();
    exports2.default = cryptoUtils;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/rawConn.js
var require_rawConn = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/rawConn.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      var desc = Object.getOwnPropertyDescriptor(m6, k5);
      if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m6[k5];
        } };
      }
      Object.defineProperty(o5, k22, desc);
    } : function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      o5[k22] = m6[k5];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v6) {
      Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
    } : function(o5, v6) {
      o5["default"] = v6;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
      }
      __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.RawConnection = void 0;
    var node_net_1 = __importDefault(require("net"));
    var tls = __importStar(require("tls"));
    var baseConn_1 = require_baseConn();
    var utils_1 = require_utils2();
    var buffer_1 = require_buffer();
    var event_1 = __importDefault(require_event());
    var chars = __importStar(require_chars());
    var scram_1 = require_scram();
    var errors = __importStar(require_errors());
    var cryptoUtils_1 = __importDefault(require_cryptoUtils());
    var AuthenticationStatuses;
    (function(AuthenticationStatuses2) {
      AuthenticationStatuses2[AuthenticationStatuses2["AUTH_OK"] = 0] = "AUTH_OK";
      AuthenticationStatuses2[AuthenticationStatuses2["AUTH_SASL"] = 10] = "AUTH_SASL";
      AuthenticationStatuses2[AuthenticationStatuses2["AUTH_SASL_CONTINUE"] = 11] = "AUTH_SASL_CONTINUE";
      AuthenticationStatuses2[AuthenticationStatuses2["AUTH_SASL_FINAL"] = 12] = "AUTH_SASL_FINAL";
    })(AuthenticationStatuses || (AuthenticationStatuses = {}));
    var scram = (0, scram_1.getSCRAM)(cryptoUtils_1.default);
    var _tlsOptions = /* @__PURE__ */ new WeakMap();
    function getTlsOptions(config) {
      if (_tlsOptions.has(config)) {
        return _tlsOptions.get(config);
      }
      const tlsSecurity = config.tlsSecurity;
      const tlsOptions = {
        ALPNProtocols: ["edgedb-binary"],
        rejectUnauthorized: tlsSecurity !== "insecure"
      };
      const isIPAddress = node_net_1.default.isIP(config.address[0]) !== 0;
      if (!isIPAddress) {
        tlsOptions.servername = config.tlsServerName || config.address[0];
      }
      _tlsOptions.set(config, tlsOptions);
      if (config._tlsCAData !== null) {
        tlsOptions.ca = config._tlsCAData;
      }
      if (tlsSecurity === "no_host_verification") {
        tlsOptions.checkServerIdentity = (hostname, cert) => {
          const err2 = tls.checkServerIdentity(hostname, cert);
          if (err2 === void 0) {
            return void 0;
          }
          if (err2.message.startsWith("Hostname/IP does not match certificate")) {
            return void 0;
          }
          return err2;
        };
      }
      return tlsOptions;
    }
    var RawConnection = class extends baseConn_1.BaseRawConnection {
      constructor(sock, config, registry) {
        super(registry);
        __publicField(this, "config");
        __publicField(this, "sock");
        __publicField(this, "paused");
        this.config = config;
        this.paused = false;
        this.sock = sock;
        this.sock.setNoDelay();
        this.sock.on("error", this._onError.bind(this));
        this.sock.on("data", this._onData.bind(this));
        if (tls.TLSSocket && this.sock instanceof tls.TLSSocket) {
          this.sock.on("secureConnect", this._onConnect.bind(this));
        } else {
          this.sock.on("connect", this._onConnect.bind(this));
        }
        this.sock.on("close", this._onClose.bind(this));
      }
      _onConnect() {
        this.connWaiter.set();
      }
      _onClose() {
        if (!this.connected) {
          return;
        }
        const newErr = new errors.ClientConnectionClosedError(`the connection has been aborted`);
        if (!this.connWaiter.done || this.messageWaiter) {
          this._abortWaiters(newErr);
        }
        if (this.buffer.takeMessage() && this.buffer.getMessageType() === chars.$E) {
          Object.defineProperty(newErr, "cause", {
            enumerable: false,
            value: this._parseErrorMessage()
          });
        }
        this._abortWithError(newErr);
      }
      _onError(err2) {
        const newErr = new errors.ClientConnectionClosedError(`network error: ${err2}`, { cause: err2 });
        try {
          this._abortWaiters(newErr);
        } finally {
          this._abortWithError(newErr);
        }
      }
      _onData(data) {
        try {
          this.buffer.feed(data);
        } catch (e6) {
          if (this.messageWaiter) {
            this.messageWaiter.setError(e6);
            this.messageWaiter = null;
          }
          this._abortWithError(e6);
        }
        if (this.messageWaiter) {
          if (this.buffer.takeMessage()) {
            this.messageWaiter.set();
            this.messageWaiter = null;
          }
        }
      }
      async _waitForMessage() {
        if (this.buffer.takeMessage()) {
          return;
        }
        if (this.paused) {
          this.paused = false;
          this.sock.resume();
        }
        this.sock.ref();
        this.messageWaiter = new event_1.default();
        try {
          await this.messageWaiter.wait();
        } finally {
          this.sock.unref();
        }
      }
      _sendData(data) {
        this.sock.write(data);
      }
      static newSock(addr, options) {
        if (typeof addr === "string") {
          return node_net_1.default.createConnection(addr);
        }
        const [host, port] = addr;
        if (options == null) {
          return node_net_1.default.createConnection(port, host);
        }
        const opts = { ...options, host, port };
        return tls.connect(opts);
      }
      _abort() {
        if (this.sock && this.connected) {
          this.sock.destroy();
        }
        super._abort();
      }
      async close() {
        if (this.sock && this.connected) {
          this.sock.write(new buffer_1.WriteMessageBuffer().beginMessage(chars.$X).endMessage().unwrap());
        }
        return await super.close();
      }
      static async connectWithTimeout(config, registry, useTls = true) {
        const sock = this.newSock(config.connectionParams.address, useTls ? getTlsOptions(config.connectionParams) : void 0);
        const conn = new this(sock, config, registry);
        const connPromise = conn.connect();
        let timeoutCb = null;
        let timeoutHappened = false;
        if (config.connectTimeout) {
          timeoutCb = setTimeout(() => {
            if (!conn.connected) {
              timeoutHappened = true;
              conn.sock.destroy(new errors.ClientConnectionTimeoutError(`connection timed out (${config.connectTimeout}ms)`));
            }
          }, config.connectTimeout);
        }
        try {
          await connPromise;
        } catch (e6) {
          conn._abort();
          if (timeoutHappened && e6 instanceof errors.ClientConnectionClosedError) {
            throw new errors.ClientConnectionTimeoutError(`connection timed out (${config.connectTimeout}ms)`);
          }
          if (e6 instanceof errors.GelError) {
            throw e6;
          } else {
            let err2;
            switch (e6.code) {
              case "EPROTO":
                if (useTls === true) {
                  try {
                    return this.connectWithTimeout(config, registry, false);
                  } catch {
                  }
                }
                err2 = new errors.ClientConnectionFailedError(`${e6.message}
Attempted to connect using the following credentials:
${config.connectionParams.explainConfig()}
`, { cause: e6 });
                break;
              case "ECONNREFUSED":
              case "ECONNABORTED":
              case "ECONNRESET":
              case "ENOTFOUND":
              case "ENOENT":
                err2 = new errors.ClientConnectionFailedTemporarilyError(`${e6.message}
Attempted to connect using the following credentials:
${config.connectionParams.explainConfig()}
`, { cause: e6 });
                break;
              default:
                err2 = new errors.ClientConnectionFailedError(`${e6.message}
Attempted to connect using the following credentials:
${config.connectionParams.explainConfig()}
`, { cause: e6 });
                break;
            }
            throw err2;
          }
        } finally {
          if (timeoutCb != null) {
            clearTimeout(timeoutCb);
          }
        }
        return conn;
      }
      async connect() {
        await this.connWaiter.wait();
        if (this.sock instanceof tls.TLSSocket) {
          if (this.sock.alpnProtocol !== "edgedb-binary") {
            throw new errors.ClientConnectionFailedError("The server doesn't support the edgedb-binary protocol.");
          }
        }
        const handshake = new buffer_1.WriteMessageBuffer();
        handshake.beginMessage(chars.$V).writeInt16(this.protocolVersion[0]).writeInt16(this.protocolVersion[1]);
        const clientHandshakeOptions = {
          user: this.config.connectionParams.user,
          database: this.config.connectionParams.database
        };
        if (this.config.connectionParams.secretKey != null) {
          clientHandshakeOptions.secret_key = this.config.connectionParams.secretKey;
        }
        handshake.writeInt16(Object.keys(clientHandshakeOptions).length);
        for (const [key, value] of Object.entries(clientHandshakeOptions)) {
          handshake.writeString(key).writeString(value);
        }
        handshake.writeInt16(0);
        handshake.endMessage();
        this.sock.write(handshake.unwrap());
        while (true) {
          if (!this.buffer.takeMessage()) {
            await this._waitForMessage();
          }
          const mtype = this.buffer.getMessageType();
          switch (mtype) {
            case chars.$v: {
              const hi = this.buffer.readInt16();
              const lo = this.buffer.readInt16();
              this._parseHeaders();
              this.buffer.finishMessage();
              const proposed = [hi, lo];
              if ((0, utils_1.versionGreaterThan)(proposed, baseConn_1.PROTO_VER) || (0, utils_1.versionGreaterThan)(baseConn_1.PROTO_VER_MIN, proposed)) {
                throw new errors.UnsupportedProtocolVersionError(`the server requested an unsupported version of the protocol ${hi}.${lo}`);
              }
              this.protocolVersion = [hi, lo];
              break;
            }
            case chars.$R: {
              const status = this.buffer.readInt32();
              if (status === AuthenticationStatuses.AUTH_OK) {
                this.buffer.finishMessage();
              } else if (status === AuthenticationStatuses.AUTH_SASL) {
                await this._authSasl();
              } else {
                throw new errors.ProtocolError(`unsupported authentication method requested by the server: ${status}`);
              }
              break;
            }
            case chars.$K: {
              this.serverSecret = this.buffer.readBuffer(32);
              this.buffer.finishMessage();
              break;
            }
            case chars.$E: {
              throw this._parseErrorMessage();
            }
            case chars.$s: {
              this._parseDescribeStateMessage();
              break;
            }
            case chars.$Z: {
              this._parseSyncMessage();
              if (!(this.sock instanceof tls.TLSSocket) && typeof Deno === "undefined") {
                const [major, minor] = this.protocolVersion;
                throw new errors.ProtocolError(`the protocol version requires TLS: ${major}.${minor}`);
              }
              this.connected = true;
              return;
            }
            default:
              this._fallthrough();
          }
        }
      }
      async _authSasl() {
        const numMethods = this.buffer.readInt32();
        if (numMethods <= 0) {
          throw new errors.ProtocolError("the server requested SASL authentication but did not offer any methods");
        }
        const methods = [];
        let foundScram256 = false;
        for (let _3 = 0; _3 < numMethods; _3++) {
          const method = this.buffer.readString();
          if (method === "SCRAM-SHA-256") {
            foundScram256 = true;
          }
          methods.push(method);
        }
        this.buffer.finishMessage();
        if (!foundScram256) {
          throw new errors.ProtocolError(`the server offered the following SASL authentication methods: ${methods.join(", ")}, neither are supported.`);
        }
        const clientNonce = scram.generateNonce();
        const [clientFirst, clientFirstBare] = scram.buildClientFirstMessage(clientNonce, this.config.connectionParams.user);
        const wb = new buffer_1.WriteMessageBuffer();
        wb.beginMessage(chars.$p).writeString("SCRAM-SHA-256").writeString(clientFirst).endMessage();
        this.sock.write(wb.unwrap());
        await this._ensureMessage(chars.$R, "SASLContinue");
        let status = this.buffer.readInt32();
        if (status !== AuthenticationStatuses.AUTH_SASL_CONTINUE) {
          throw new errors.ProtocolError(`expected SASLContinue from the server, received ${status}`);
        }
        const serverFirst = this.buffer.readString();
        this.buffer.finishMessage();
        const [serverNonce, salt, itercount] = scram.parseServerFirstMessage(serverFirst);
        const [clientFinal, expectedServerSig] = await scram.buildClientFinalMessage(this.config.connectionParams.password || "", salt, itercount, clientFirstBare, serverFirst, serverNonce);
        wb.reset().beginMessage(chars.$r).writeString(clientFinal).endMessage();
        this.sock.write(wb.unwrap());
        await this._ensureMessage(chars.$R, "SASLFinal");
        status = this.buffer.readInt32();
        if (status !== AuthenticationStatuses.AUTH_SASL_FINAL) {
          throw new errors.ProtocolError(`expected SASLFinal from the server, received ${status}`);
        }
        const serverFinal = this.buffer.readString();
        this.buffer.finishMessage();
        const serverSig = scram.parseServerFinalMessage(serverFinal);
        if (!scram.bufferEquals(serverSig, expectedServerSig)) {
          throw new errors.ProtocolError("server SCRAM proof does not match");
        }
      }
      async _ensureMessage(expectedMtype, err2) {
        if (!this.buffer.takeMessage()) {
          await this._waitForMessage();
        }
        const mtype = this.buffer.getMessageType();
        switch (mtype) {
          case chars.$E: {
            throw this._parseErrorMessage();
          }
          case expectedMtype: {
            return;
          }
          default: {
            throw new errors.UnexpectedMessageError(`expected ${err2} from the server, received ${chars.chr(mtype)}`);
          }
        }
      }
    };
    exports2.RawConnection = RawConnection;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/fetchConn.js
var require_fetchConn = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/fetchConn.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      var desc = Object.getOwnPropertyDescriptor(m6, k5);
      if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m6[k5];
        } };
      }
      Object.defineProperty(o5, k22, desc);
    } : function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      o5[k22] = m6[k5];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v6) {
      Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
    } : function(o5, v6) {
      o5["default"] = v6;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
      }
      __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.FetchConnection = exports2.AdminUIFetchConnection = void 0;
    var baseConn_1 = require_baseConn();
    var codecs_1 = require_codecs();
    var errors_1 = require_errors();
    var ifaces_1 = require_ifaces2();
    var buffer_1 = require_buffer();
    var chars = __importStar(require_chars());
    var event_1 = __importDefault(require_event());
    var utils_1 = require_utils2();
    var PROTO_MIME = `application/x.edgedb.v_${baseConn_1.PROTO_VER[0]}_${baseConn_1.PROTO_VER[1]}.binary'`;
    var PROTO_MIME_RE = /application\/x\.edgedb\.v_(\d+)_(\d+)\.binary/;
    var STUDIO_CAPABILITIES = (baseConn_1.RESTRICTED_CAPABILITIES | baseConn_1.Capabilities.SESSION_CONFIG | baseConn_1.Capabilities.SET_GLOBAL) >>> 0;
    var BaseFetchConnection = class extends baseConn_1.BaseRawConnection {
      constructor(fetch3, registry) {
        super(registry);
        __publicField(this, "authenticatedFetch");
        __publicField(this, "abortSignal", null);
        this.authenticatedFetch = fetch3;
      }
      async _waitForMessage() {
        if (this.buffer.takeMessage()) {
          return;
        }
        if (this.messageWaiter == null || this.messageWaiter.done) {
          throw new errors_1.InternalClientError(`message waiter was not initialized before waiting for response`);
        }
        await this.messageWaiter.wait();
      }
      async __sendData(data) {
        if (this.buffer.takeMessage()) {
          const mtype = this.buffer.getMessageType();
          throw new errors_1.InternalClientError(`sending request before reading all data of the previous one: ${chars.chr(mtype)}`);
        }
        if (this.messageWaiter != null && !this.messageWaiter.done) {
          throw new errors_1.InternalClientError(`sending request before waiting for completion of the previous one`);
        }
        this.messageWaiter = new event_1.default();
        try {
          const resp = await this.authenticatedFetch("", {
            method: "post",
            body: data,
            headers: {
              "Content-Type": PROTO_MIME
            },
            signal: this.abortSignal
          });
          if (!resp.ok) {
            throw new errors_1.ProtocolError(`fetch failed with status code ${resp.status}: ${resp.statusText}`);
          }
          const contentType = resp.headers.get("content-type");
          const matchProtoVer = contentType?.match(PROTO_MIME_RE);
          if (matchProtoVer) {
            this.protocolVersion = [+matchProtoVer[1], +matchProtoVer[2]];
          }
          const respData = await resp.arrayBuffer();
          const buf = new Uint8Array(respData);
          try {
            this.buffer.feed(buf);
          } catch (e6) {
            this.messageWaiter.setError(e6);
          }
          if (!this.buffer.takeMessage()) {
            throw new errors_1.ProtocolError("no binary protocol messages in the response");
          }
          this.messageWaiter.set();
        } catch (e6) {
          this.messageWaiter.setError(e6);
        } finally {
          this.messageWaiter = null;
        }
      }
      _sendData(data) {
        this.__sendData(data);
      }
      async fetch(...args) {
        const protoVer = this.protocolVersion;
        try {
          return await super.fetch(...args);
        } catch (err2) {
          if (err2 instanceof errors_1.BinaryProtocolError && !(0, utils_1.versionEqual)(protoVer, this.protocolVersion)) {
            return await super.fetch(...args);
          }
          throw err2;
        }
      }
      static create(fetch3, registry) {
        const conn = new this(fetch3, registry);
        conn.connected = true;
        conn.connWaiter.set();
        return conn;
      }
    };
    var AdminUIFetchConnection = class extends BaseFetchConnection {
      constructor() {
        super(...arguments);
        __publicField(this, "adminUIMode", true);
      }
      static create(fetch3, registry, knownServerVersion) {
        const conn = super.create(fetch3, registry);
        if (knownServerVersion && knownServerVersion[0] < 6) {
          conn.protocolVersion = [2, 0];
        }
        return conn;
      }
      async rawParse(language, query, state2, options, abortSignal) {
        this.abortSignal = abortSignal ?? null;
        const result = await this._parse(language, query, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, state2, STUDIO_CAPABILITIES, options);
        return [this.protocolVersion, ...result];
      }
      async rawExecute(language, query, state2, outCodec, options, inCodec, args = null, abortSignal) {
        this.abortSignal = abortSignal ?? null;
        const result = new buffer_1.WriteBuffer();
        const [warnings] = await this._executeFlow(language, query, args, outCodec ? ifaces_1.OutputFormat.BINARY : ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.MANY, state2, inCodec ?? codecs_1.NULL_CODEC, outCodec ?? codecs_1.NULL_CODEC, result, STUDIO_CAPABILITIES, options);
        return [result.unwrap(), warnings];
      }
    };
    exports2.AdminUIFetchConnection = AdminUIFetchConnection;
    var FetchConnection = class _FetchConnection extends BaseFetchConnection {
      static createConnectWithTimeout(httpSCRAMAuth) {
        return async function connectWithTimeout(config, registry) {
          const fetch3 = await (0, utils_1.getAuthenticatedFetch)(config.connectionParams, httpSCRAMAuth);
          const conn = new _FetchConnection(fetch3, registry);
          conn.connected = true;
          conn.connWaiter.set();
          return conn;
        };
      }
    };
    exports2.FetchConnection = FetchConnection;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/httpScram.js
var require_httpScram = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/httpScram.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getHTTPSCRAMAuth = getHTTPSCRAMAuth;
    var errors_1 = require_errors();
    var buffer_1 = require_buffer();
    var scram_1 = require_scram();
    var AUTH_ENDPOINT = "/auth/token";
    function getHTTPSCRAMAuth(cryptoUtils) {
      const { bufferEquals, generateNonce, buildClientFirstMessage, buildClientFinalMessage, parseServerFirstMessage, parseServerFinalMessage } = (0, scram_1.getSCRAM)(cryptoUtils);
      return async function HTTPSCRAMAuth(baseUrl, username, password) {
        const authUrl = baseUrl + AUTH_ENDPOINT;
        const clientNonce = generateNonce();
        const [clientFirst, clientFirstBare] = buildClientFirstMessage(clientNonce, username);
        const serverFirstRes = await fetch(authUrl, {
          headers: {
            Authorization: `SCRAM-SHA-256 data=${utf8ToB64(clientFirst)}`
          }
        });
        const authenticateHeader = serverFirstRes.headers.get("WWW-Authenticate");
        if (serverFirstRes.status !== 401 || !authenticateHeader) {
          const body = await serverFirstRes.text();
          throw new errors_1.ProtocolError(`authentication failed: ${body}`);
        }
        if (!authenticateHeader.startsWith("SCRAM-SHA-256")) {
          throw new errors_1.ProtocolError(`unsupported authentication scheme: ${authenticateHeader}`);
        }
        const authParams = authenticateHeader.split(/ (.+)?/, 2)[1] ?? "";
        if (authParams.length === 0) {
          const body = await serverFirstRes.text();
          throw new errors_1.ProtocolError(`authentication failed: ${body}`);
        }
        const { sid, data: serverFirst } = parseScramAttrs(authParams);
        if (!sid || !serverFirst) {
          throw new errors_1.ProtocolError(`authentication challenge missing attributes: expected "sid" and "data", got '${authParams}'`);
        }
        const [serverNonce, salt, iterCount] = parseServerFirstMessage(serverFirst);
        const [clientFinal, expectedServerSig] = await buildClientFinalMessage(password, salt, iterCount, clientFirstBare, serverFirst, serverNonce);
        const serverFinalRes = await fetch(authUrl, {
          headers: {
            Authorization: `SCRAM-SHA-256 sid=${sid}, data=${utf8ToB64(clientFinal)}`
          }
        });
        const authInfoHeader = serverFinalRes.headers.get("Authentication-Info");
        if (!serverFinalRes.ok || !authInfoHeader) {
          const body = await serverFinalRes.text();
          throw new errors_1.ProtocolError(`authentication failed: ${body}`);
        }
        const { data: serverFinal, sid: sidFinal } = parseScramAttrs(authInfoHeader);
        if (!sidFinal || !serverFinal) {
          throw new errors_1.ProtocolError(`authentication info missing attributes: expected "sid" and "data", got '${authInfoHeader}'`);
        }
        if (sidFinal !== sid) {
          throw new errors_1.ProtocolError("SCRAM session id does not match");
        }
        const serverSig = parseServerFinalMessage(serverFinal);
        if (!bufferEquals(serverSig, expectedServerSig)) {
          throw new errors_1.ProtocolError("server SCRAM proof does not match");
        }
        const authToken = await serverFinalRes.text();
        return authToken;
      };
    }
    function utf8ToB64(str) {
      return (0, buffer_1.encodeB64)(buffer_1.utf8Encoder.encode(str));
    }
    function b64ToUtf8(str) {
      return buffer_1.utf8Decoder.decode((0, buffer_1.decodeB64)(str));
    }
    function parseScramAttrs(paramsStr) {
      const params = new Map(paramsStr.length > 0 ? paramsStr.split(",").map((attr) => attr.split(/=(.+)?/, 2)).map(([key, val2]) => [key.trim(), val2.trim()]) : []);
      const sid = params.get("sid") ?? null;
      const rawData = params.get("data");
      const data = rawData ? b64ToUtf8(rawData) : null;
      return { sid, data };
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/nodeClient.js
var require_nodeClient = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/nodeClient.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.createClient = createClient;
    exports2.createHttpClient = createHttpClient;
    var baseClient_1 = require_baseClient();
    var conUtils_server_1 = require_conUtils_server();
    var options_1 = require_options();
    var rawConn_1 = require_rawConn();
    var fetchConn_1 = require_fetchConn();
    var httpScram_1 = require_httpScram();
    var cryptoUtils_1 = __importDefault(require_cryptoUtils());
    var ClientPool = class extends baseClient_1.BaseClientPool {
      constructor() {
        super(...arguments);
        __publicField(this, "isStateless", false);
        __publicField(this, "_connectWithTimeout", rawConn_1.RawConnection.connectWithTimeout.bind(rawConn_1.RawConnection));
      }
    };
    function createClient(options) {
      return new baseClient_1.Client(new ClientPool(conUtils_server_1.parseConnectArguments, typeof options === "string" ? { dsn: options } : options ?? {}), options_1.Options.defaults());
    }
    var httpSCRAMAuth = (0, httpScram_1.getHTTPSCRAMAuth)(cryptoUtils_1.default);
    var FetchClientPool = class extends baseClient_1.BaseClientPool {
      constructor() {
        super(...arguments);
        __publicField(this, "isStateless", true);
        __publicField(this, "_connectWithTimeout", fetchConn_1.FetchConnection.createConnectWithTimeout(httpSCRAMAuth));
      }
    };
    function createHttpClient(options) {
      return new baseClient_1.Client(new FetchClientPool(conUtils_server_1.parseConnectArguments, typeof options === "string" ? { dsn: options } : options ?? {}), options_1.Options.defaults());
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/wkt.js
var require_wkt = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/wkt.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.parseWKT = parseWKT;
    var postgis_1 = require_postgis();
    var sridRegex = /\s*SRID=([0-9]+)\s*;/iy;
    var endRegex = /\s*$/y;
    var geomTypes = [
      "POINT",
      "LINESTRING",
      "POLYGON",
      "MULTIPOINT",
      "MULTILINESTRING",
      "MULTIPOLYGON",
      "GEOMETRYCOLLECTION",
      "POLYHEDRALSURFACE",
      "TRIANGLE",
      "TIN",
      "CIRCULARSTRING",
      "COMPOUNDCURVE",
      "CURVEPOLYGON",
      "MULTICURVE",
      "MULTISURFACE"
    ];
    var geomTypeRegex = new RegExp(`\\s*(${geomTypes.join("|")})`, "iy");
    var zmFlagsRegex = /\s+(ZM|Z|M)/iy;
    var emptyOrOpenRegex = /\s+(EMPTY)|\s*\(/iy;
    var openRegex = /\s*\(/y;
    var closeRegex = /\s*\)/y;
    var commaRegex = /\s*,/y;
    var _num = "-?[0-9]+(?:\\.[0-9]+)?";
    var pointRegex = new RegExp(`\\s*(${_num})\\s+(${_num})(?:\\s+(${_num}))?(?:\\s+(${_num}))?`, "y");
    function parseWKT(wkt) {
      let i6 = 0;
      let hasZ = null;
      let hasM = null;
      let srid = null;
      sridRegex.lastIndex = i6;
      const _srid = sridRegex.exec(wkt);
      if (_srid) {
        srid = parseInt(_srid[1], 10);
        i6 += _srid[0].length;
      }
      const geom = _parseGeom();
      endRegex.lastIndex = i6;
      if (endRegex.exec(wkt) === null) {
        throw createParseError(wkt, i6, "expected end of wkt");
      }
      return geom;
      function _parseGeom(unnamedGeom = null, allowedGeoms = null) {
        geomTypeRegex.lastIndex = i6;
        const _geomType = geomTypeRegex.exec(wkt);
        const type = _geomType?.[1].toUpperCase() ?? unnamedGeom;
        if (!type || allowedGeoms && !allowedGeoms.includes(type)) {
          throw createParseError(wkt, i6, `expected one of ${(allowedGeoms ? ["(", ...allowedGeoms] : geomTypes).join(", ")}`);
        }
        i6 += _geomType?.[0].length ?? 0;
        if (_geomType !== null) {
          zmFlagsRegex.lastIndex = i6;
          const _zmFlags = zmFlagsRegex.exec(wkt);
          if (_zmFlags !== null) {
            const zm = _zmFlags[1].toLowerCase();
            hasZ = zm === "zm" || zm === "z";
            hasM = zm === "zm" || zm === "m";
            i6 += _zmFlags[0].length;
          } else {
            hasZ = null;
            hasM = null;
          }
        }
        const open = _geomType === null ? openRegex : emptyOrOpenRegex;
        open.lastIndex = i6;
        const _emptyOrOpen = open.exec(wkt);
        if (_emptyOrOpen === null) {
          throw createParseError(wkt, i6, _geomType === null ? `expected (` : `expected EMPTY or (`);
        }
        i6 += _emptyOrOpen[0].length;
        const empty = _emptyOrOpen[1] != null;
        let geom2;
        switch (type) {
          case "POINT":
            geom2 = _parsePoint(empty);
            break;
          case "LINESTRING":
          case "CIRCULARSTRING":
            geom2 = _parseLineString(empty, type === "CIRCULARSTRING" ? postgis_1.CircularString : postgis_1.LineString);
            break;
          case "POLYGON":
          case "TRIANGLE":
            geom2 = _parsePolygon(empty, type === "TRIANGLE" ? postgis_1.Triangle : postgis_1.Polygon);
            break;
          case "MULTIPOINT":
            geom2 = new postgis_1.MultiPoint(empty ? [] : _parseCommaSep(() => _parseBracketedGeom(_parsePoint)), hasZ ?? false, hasM ?? false, srid);
            break;
          case "MULTILINESTRING":
            geom2 = new postgis_1.MultiLineString(empty ? [] : _parseCommaSep(() => _parseBracketedGeom(_parseLineString)), hasZ ?? false, hasM ?? false, srid);
            break;
          case "MULTIPOLYGON":
          case "POLYHEDRALSURFACE":
          case "TIN":
            {
              const Geom = type === "TIN" ? postgis_1.TriangulatedIrregularNetwork : type === "POLYHEDRALSURFACE" ? postgis_1.PolyhedralSurface : postgis_1.MultiPolygon;
              geom2 = new Geom(empty ? [] : _parseCommaSep(() => _parseBracketedGeom(() => _parsePolygon(false, type === "TIN" ? postgis_1.Triangle : postgis_1.Polygon))), hasZ ?? false, hasM ?? false, srid);
            }
            break;
          case "GEOMETRYCOLLECTION": {
            geom2 = new postgis_1.GeometryCollection(empty ? [] : _checkDimensions(() => _parseCommaSep(_parseGeom)), hasZ ?? false, hasM ?? false, srid);
            break;
          }
          case "COMPOUNDCURVE":
            {
              const segments = empty ? [] : _checkDimensions(() => _parseCommaSep(() => _parseGeom("LINESTRING", ["LINESTRING", "CIRCULARSTRING"])));
              geom2 = new postgis_1.CompoundCurve(segments, hasZ ?? false, hasM ?? false, srid);
            }
            break;
          case "CURVEPOLYGON":
          case "MULTICURVE":
            {
              const rings = empty ? [] : _checkDimensions(() => _parseCommaSep(() => _parseGeom("LINESTRING", [
                "LINESTRING",
                "CIRCULARSTRING",
                "COMPOUNDCURVE"
              ])));
              const Geom = type === "MULTICURVE" ? postgis_1.MultiCurve : postgis_1.CurvePolygon;
              geom2 = new Geom(rings, hasZ ?? false, hasM ?? false, srid);
            }
            break;
          case "MULTISURFACE":
            {
              const surfaces = empty ? [] : _checkDimensions(() => _parseCommaSep(() => _parseGeom("POLYGON", ["POLYGON", "CURVEPOLYGON"])));
              geom2 = new postgis_1.MultiSurface(surfaces, hasZ ?? false, hasM ?? false, srid);
            }
            break;
          default:
            assertNever(type, `unknown geometry type ${type}`);
        }
        if (!empty) {
          closeRegex.lastIndex = i6;
          const _close = closeRegex.exec(wkt);
          if (_close === null) {
            throw createParseError(wkt, i6, `expected )`);
          }
          i6 += _close[0].length;
        }
        return geom2;
      }
      function _parsePoint(empty = false) {
        if (empty) {
          return new postgis_1.Point(NaN, NaN, hasZ ? NaN : null, hasM ? NaN : null, srid);
        }
        pointRegex.lastIndex = i6;
        const coords = pointRegex.exec(wkt);
        if (coords === null) {
          throw createParseError(wkt, i6, `expected between 2 to 4 coordinates`);
        }
        const x5 = parseFloat(coords[1]);
        const y2 = parseFloat(coords[2]);
        const z2 = coords[3] ? parseFloat(coords[3]) : null;
        const m6 = coords[4] ? parseFloat(coords[4]) : null;
        if (hasZ === null) {
          hasZ = z2 !== null;
          hasM = m6 !== null;
        } else {
          if (m6 === null) {
            if (hasZ && hasM) {
              throw createParseError(wkt, i6, `expected M coordinate`);
            }
          } else {
            if (!hasM) {
              throw createParseError(wkt, i6, `unexpected M coordinate`);
            }
          }
          if (z2 === null) {
            if (hasZ || hasM) {
              throw createParseError(wkt, i6, `expected ${hasZ ? "Z" : "M"} coordinate`);
            }
          } else {
            if (!hasZ && (!hasM || m6 !== null)) {
              throw createParseError(wkt, i6, `unexpected Z coordinate`);
            }
          }
        }
        i6 += coords[0].length;
        return new postgis_1.Point(x5, y2, hasZ ? z2 : null, hasZ ? m6 : z2, srid);
      }
      function _parseLineString(empty = false, Geom = postgis_1.LineString) {
        return new Geom(empty ? [] : _parseCommaSep(_parsePoint), hasZ ?? false, hasM ?? false, srid);
      }
      function _parsePolygon(empty = false, Geom = postgis_1.Polygon) {
        return new Geom(empty ? [] : _parseCommaSep(() => _parseBracketedGeom(_parseLineString)), hasZ ?? false, hasM ?? false, srid);
      }
      function _parseCommaSep(parseGeom) {
        const geoms = [parseGeom()];
        while (true) {
          commaRegex.lastIndex = i6;
          const comma = commaRegex.exec(wkt);
          if (comma === null) {
            break;
          }
          i6 += comma[0].length;
          geoms.push(parseGeom());
        }
        return geoms;
      }
      function _parseBracketedGeom(parseGeom) {
        openRegex.lastIndex = i6;
        const open = openRegex.exec(wkt);
        if (open === null) {
          throw createParseError(wkt, i6, `expected (`);
        }
        i6 += open[0].length;
        const geom2 = parseGeom();
        closeRegex.lastIndex = i6;
        const close = closeRegex.exec(wkt);
        if (close === null) {
          throw createParseError(wkt, i6, `expected )`);
        }
        i6 += close[0].length;
        return geom2;
      }
      function _checkDimensions(parseChildren) {
        const parentZ = hasZ;
        const parentM = hasM;
        const geoms = parseChildren();
        hasZ = parentZ ?? geoms[0].hasZ ?? false;
        hasM = parentM ?? geoms[0].hasM ?? false;
        if (geoms.some((geom2) => geom2.hasZ !== hasZ || geom2.hasM !== hasM)) {
          throw createParseError(wkt, i6, `child geometries have mixed dimensions`);
        }
        return geoms;
      }
    }
    function createParseError(_wkt, index6, error2) {
      return new Error(`${error2} at position ${index6}`);
    }
    function assertNever(_type2, message) {
      throw new Error(message);
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/index.shared.js
var require_index_shared = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/index.shared.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      var desc = Object.getOwnPropertyDescriptor(m6, k5);
      if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m6[k5];
        } };
      }
      Object.defineProperty(o5, k22, desc);
    } : function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      o5[k22] = m6[k5];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v6) {
      Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
    } : function(o5, v6) {
      o5["default"] = v6;
    });
    var __exportStar = exports2 && exports2.__exportStar || function(m6, exports3) {
      for (var p5 in m6) if (p5 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p5)) __createBinding(exports3, m6, p5);
    };
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2._ReadBuffer = exports2._CodecsRegistry = exports2.throwWarnings = exports2.logWarnings = exports2.defaultBackoff = exports2.Options = exports2.RetryOptions = exports2.RetryCondition = exports2.IsolationLevel = exports2.parseWKT = exports2.Float16Array = exports2.SparseVector = exports2.MultiRange = exports2.Range = exports2.ConfigMemory = exports2.DateDuration = exports2.RelativeDuration = exports2.Duration = exports2.LocalTime = exports2.LocalDate = exports2.LocalDateTime = void 0;
    var datetime_1 = require_datetime();
    Object.defineProperty(exports2, "LocalDateTime", { enumerable: true, get: function() {
      return datetime_1.LocalDateTime;
    } });
    Object.defineProperty(exports2, "LocalDate", { enumerable: true, get: function() {
      return datetime_1.LocalDate;
    } });
    Object.defineProperty(exports2, "LocalTime", { enumerable: true, get: function() {
      return datetime_1.LocalTime;
    } });
    Object.defineProperty(exports2, "Duration", { enumerable: true, get: function() {
      return datetime_1.Duration;
    } });
    Object.defineProperty(exports2, "RelativeDuration", { enumerable: true, get: function() {
      return datetime_1.RelativeDuration;
    } });
    Object.defineProperty(exports2, "DateDuration", { enumerable: true, get: function() {
      return datetime_1.DateDuration;
    } });
    var memory_1 = require_memory();
    Object.defineProperty(exports2, "ConfigMemory", { enumerable: true, get: function() {
      return memory_1.ConfigMemory;
    } });
    var range_1 = require_range2();
    Object.defineProperty(exports2, "Range", { enumerable: true, get: function() {
      return range_1.Range;
    } });
    Object.defineProperty(exports2, "MultiRange", { enumerable: true, get: function() {
      return range_1.MultiRange;
    } });
    var pgvector_1 = require_pgvector();
    Object.defineProperty(exports2, "SparseVector", { enumerable: true, get: function() {
      return pgvector_1.SparseVector;
    } });
    var utils_1 = require_utils2();
    Object.defineProperty(exports2, "Float16Array", { enumerable: true, get: function() {
      return utils_1.Float16Array;
    } });
    __exportStar(require_postgis(), exports2);
    var wkt_1 = require_wkt();
    Object.defineProperty(exports2, "parseWKT", { enumerable: true, get: function() {
      return wkt_1.parseWKT;
    } });
    var options_1 = require_options();
    Object.defineProperty(exports2, "IsolationLevel", { enumerable: true, get: function() {
      return options_1.IsolationLevel;
    } });
    Object.defineProperty(exports2, "RetryCondition", { enumerable: true, get: function() {
      return options_1.RetryCondition;
    } });
    Object.defineProperty(exports2, "RetryOptions", { enumerable: true, get: function() {
      return options_1.RetryOptions;
    } });
    Object.defineProperty(exports2, "Options", { enumerable: true, get: function() {
      return options_1.Options;
    } });
    Object.defineProperty(exports2, "defaultBackoff", { enumerable: true, get: function() {
      return options_1.defaultBackoff;
    } });
    Object.defineProperty(exports2, "logWarnings", { enumerable: true, get: function() {
      return options_1.logWarnings;
    } });
    Object.defineProperty(exports2, "throwWarnings", { enumerable: true, get: function() {
      return options_1.throwWarnings;
    } });
    __exportStar(require_errors(), exports2);
    var reg = __importStar(require_registry());
    var buf = __importStar(require_buffer());
    exports2._CodecsRegistry = reg.CodecsRegistry;
    exports2._ReadBuffer = buf.ReadBuffer;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/typeutil.js
var require_typeutil = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/typeutil.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/strictMap.js
var require_strictMap = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/strictMap.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.StrictMapSet = exports2.StrictMap = void 0;
    var StrictMap = class extends Map {
      get(key) {
        if (!this.has(key)) {
          throw new Error(`key "${key}" is not found`);
        }
        return super.get(key);
      }
    };
    exports2.StrictMap = StrictMap;
    var StrictMapSet = class extends StrictMap {
      appendAt(key, value) {
        const set = this.has(key) ? this.get(key) : /* @__PURE__ */ new Set();
        set.add(value);
        this.set(key, set);
      }
    };
    exports2.StrictMapSet = StrictMapSet;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/reservedKeywords.js
var require_reservedKeywords = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/reservedKeywords.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.reservedKeywords = void 0;
    exports2.reservedKeywords = /* @__PURE__ */ new Set([
      "__edgedbsys__",
      "__edgedbtpl__",
      "__source__",
      "__std__",
      "__subject__",
      "__type__",
      "abort",
      "alter",
      "analyze",
      "and",
      "anyarray",
      "anytuple",
      "anytype",
      "anyobject",
      "begin",
      "case",
      "check",
      "commit",
      "configure",
      "create",
      "deallocate",
      "declare",
      "delete",
      "describe",
      "detached",
      "discard",
      "distinct",
      "do",
      "drop",
      "else",
      "empty",
      "end",
      "execute",
      "exists",
      "explain",
      "extending",
      "fetch",
      "filter",
      "for",
      "get",
      "global",
      "grant",
      "group",
      "if",
      "ilike",
      "import",
      "in",
      "insert",
      "introspect",
      "is",
      "like",
      "limit",
      "listen",
      "load",
      "lock",
      "match",
      "module",
      "move",
      "not",
      "notify",
      "offset",
      "optional",
      "or",
      "order",
      "over",
      "partition",
      "policy",
      "populate",
      "prepare",
      "raise",
      "refresh",
      "reindex",
      "release",
      "reset",
      "revoke",
      "rollback",
      "select",
      "set",
      "single",
      "start",
      "typeof",
      "union",
      "update",
      "variadic",
      "when",
      "window",
      "with"
    ]);
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/types.js
var require_types = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/types.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.typeMapping = void 0;
    exports2.getTypes = getTypes;
    exports2.types = getTypes;
    exports2.topoSort = topoSort;
    exports2.getTypes = getTypes;
    exports2.types = getTypes;
    var strictMap_1 = require_strictMap();
    var numberType2 = {
      id: "00000000-0000-0000-0000-0000000001ff",
      name: "std::number",
      is_abstract: false,
      is_seq: false,
      kind: "scalar",
      enum_values: null,
      material_id: null,
      bases: []
    };
    exports2.typeMapping = /* @__PURE__ */ new Map([
      [
        "00000000-0000-0000-0000-000000000103",
        numberType2
      ],
      [
        "00000000-0000-0000-0000-000000000104",
        numberType2
      ],
      [
        "00000000-0000-0000-0000-000000000105",
        numberType2
      ],
      [
        "00000000-0000-0000-0000-000000000106",
        numberType2
      ],
      [
        "00000000-0000-0000-0000-000000000107",
        numberType2
      ]
    ]);
    async function getTypes(cxn, params) {
      const debug = params?.debug === true;
      const version = await cxn.queryRequiredSingle(`select sys::get_version().major;`);
      const v2Plus = version >= 2;
      const v4Plus = version >= 4;
      const QUERY = `
    WITH
      MODULE schema,

      material_scalars := (
        SELECT ScalarType
        FILTER NOT .abstract
           AND NOT EXISTS .enum_values
           AND NOT EXISTS (SELECT .ancestors FILTER NOT .abstract)
      )

    SELECT Type {
      id,
      name :=
        array_join(array_agg([IS ObjectType].union_of.name), ' | ')
        IF EXISTS [IS ObjectType].union_of
        ELSE .name,
      is_abstract := .abstract,

      kind := 'object' IF Type IS ObjectType ELSE
              'scalar' IF Type IS ScalarType ELSE
              'array' IF Type IS Array ELSE
              'tuple' IF Type IS Tuple ELSE
              ${v2Plus ? `'range' IF Type IS Range ELSE` : ``}
              ${v4Plus ? `'multirange' IF Type IS MultiRange ELSE` : ``}
              'unknown',

      [IS ScalarType].enum_values,
      is_seq := 'std::sequence' in [IS ScalarType].ancestors.name,
      # for sequence (abstract type that has non-abstract ancestor)
      single material_id := (
        SELECT x := Type[IS ScalarType].ancestors
        FILTER x IN material_scalars
        LIMIT 1
      ).id,

      [IS InheritingObject].bases: {
        id
      } ORDER BY @index ASC,

      [IS ObjectType].union_of,
      [IS ObjectType].intersection_of,
      [IS ObjectType].pointers: {
        card := ("One" IF .required ELSE "AtMostOne") IF <str>.cardinality = "One" ELSE ("AtLeastOne" IF .required ELSE "Many"),
        name,
        target_id := .target.id,
        kind := 'link' IF .__type__.name = 'schema::Link' ELSE 'property',
        is_exclusive := exists (select .constraints filter .name = 'std::exclusive'),
        is_computed := len(.computed_fields) != 0,
        is_readonly := .readonly,
        has_default := EXISTS .default or ("std::sequence" in .target[IS ScalarType].ancestors.name),
        [IS Link].pointers: {
          card := ("One" IF .required ELSE "AtMostOne") IF <str>.cardinality = "One" ELSE ("AtLeastOne" IF .required ELSE "Many"),
          name := '@' ++ .name,
          target_id := .target.id,
          kind := 'link' IF .__type__.name = 'schema::Link' ELSE 'property',
          is_computed := len(.computed_fields) != 0,
          is_readonly := .readonly
        } filter .name != '@source' and .name != '@target',
      } FILTER any(@is_owned),
      exclusives := assert_distinct((
        [is schema::ObjectType].constraints
        union
        [is schema::ObjectType].pointers.constraints
      ) {
        target := (.subject[is schema::Property].name ?? .subject[is schema::Link].name ?? .subjectexpr)
      } filter .name = 'std::exclusive'),
      backlinks := (
         SELECT DETACHED Link
         FILTER .target = Type
           AND NOT EXISTS .source[IS ObjectType].union_of
        ) {
        card := "AtMostOne"
          IF
          EXISTS (select .constraints filter .name = 'std::exclusive')
          ELSE
          "Many",
        name := '<' ++ .name ++ '[is ' ++ assert_exists(.source.name) ++ ']',
        stub := .name,
        target_id := .source.id,
        kind := 'link',
        is_exclusive := (EXISTS (select .constraints filter .name = 'std::exclusive')) AND <str>.cardinality = "One",
      },
      backlink_stubs := array_agg((
        WITH
          stubs := DISTINCT (SELECT DETACHED Link FILTER .target = Type).name,
          baseObjectId := (SELECT DETACHED ObjectType FILTER .name = 'std::BaseObject' LIMIT 1).id
        FOR stub in { stubs }
        UNION (
          SELECT {
            card := "Many",
            name := '<' ++ stub,
            target_id := baseObjectId,
            kind := 'link',
            is_exclusive := false,
          }
        )
      )),
      array_element_id := [IS Array].element_type.id,

      tuple_elements := (SELECT [IS Tuple].element_types {
        target_id := .type.id,
        name
      } ORDER BY @index ASC),
      ${v2Plus ? `range_element_id := [IS Range].element_type.id,` : ``}
      ${v4Plus ? `multirange_element_id := [IS MultiRange].element_type.id,` : ``}
    }
    ORDER BY .name;
  `;
      const _types = JSON.parse(await cxn.queryJSON(QUERY));
      if (debug)
        console.log(JSON.stringify(_types, null, 2));
      for (const type of _types) {
        if (Array.isArray(type.backlinks)) {
          for (const backlink of type.backlinks) {
            const isName = backlink.name.match(/\[is (.+)\]/)[1];
            if (isName.split("::").length === 2 && isName.startsWith("default::")) {
              backlink.name = backlink.name.replace(/\[is (.+)\]/, `[is ${isName.slice(9)}]`);
            }
          }
        }
        switch (type.kind) {
          case "scalar":
            if (exports2.typeMapping.has(type.id)) {
              type.cast_type = exports2.typeMapping.get(type.id).id;
            }
            if (type.is_seq) {
              type.cast_type = numberType2.id;
            }
            if (type.name !== "std::sequence" && type.bases[0]?.id === type.material_id) {
              type.cast_type = exports2.typeMapping.get(type.material_id)?.id ?? type.material_id;
            }
            break;
          case "multirange":
            type.multirange_element_id = exports2.typeMapping.get(type.multirange_element_id)?.id ?? type.multirange_element_id;
            break;
          case "range":
            type.range_element_id = exports2.typeMapping.get(type.range_element_id)?.id ?? type.range_element_id;
            break;
          case "object": {
            const ptrs = {};
            for (const ptr of type.pointers) {
              ptrs[ptr.name] = ptr;
            }
            const rawExclusives = type.exclusives;
            const exclusives = [];
            for (const ex of rawExclusives) {
              const target = ex.target;
              if (target in ptrs) {
                exclusives.push({ [ex.target]: ptrs[ex.target] });
              }
              if (target[0] === "(" && target[target.length - 1] === ")") {
                const targets = target.slice(1, -1).split(" ").map((t6) => {
                  t6 = t6.trim();
                  if (t6[0] === ".")
                    t6 = t6.slice(1);
                  if (t6[t6.length - 1] === ",")
                    t6 = t6.slice(0, -1);
                  return t6;
                });
                const newEx = {};
                if (!targets.every((t6) => t6 in ptrs)) {
                  continue;
                }
                for (const t6 of targets) {
                  newEx[t6] = ptrs[t6];
                }
                exclusives.push(newEx);
              }
            }
            type.exclusives = exclusives;
            break;
          }
        }
      }
      _types.push(numberType2);
      const types3 = topoSort(_types);
      for (const [_3, type] of types3) {
        if (type.kind === "object" && type.union_of.length) {
          const unionTypes = type.union_of.map(({ id }) => {
            const t6 = types3.get(id);
            if (t6.kind !== "object") {
              throw new Error(`type '${t6.name}' of union '${type.name}' is not an object type`);
            }
            return t6;
          });
          const [first, ...rest] = unionTypes;
          const restPointerNames = rest.map((t6) => new Set(t6.pointers.map((p5) => p5.name)));
          for (const pointer of first.pointers) {
            if (restPointerNames.every((names) => names.has(pointer.name))) {
              type.pointers.push(pointer);
            }
          }
          type.backlinks = [];
          type.backlink_stubs = [];
        }
      }
      return types3;
    }
    function topoSort(types3) {
      const graph = new strictMap_1.StrictMap();
      const adj = new strictMap_1.StrictMap();
      for (const type of types3) {
        graph.set(type.id, type);
      }
      for (const type of types3) {
        if (type.kind !== "object" && type.kind !== "scalar") {
          continue;
        }
        for (const { id: base } of type.bases) {
          if (!graph.has(base)) {
            throw new Error(`reference to an unknown object type: ${base}`);
          }
          if (!adj.has(type.id)) {
            adj.set(type.id, /* @__PURE__ */ new Set());
          }
          adj.get(type.id).add(base);
        }
      }
      const visiting = /* @__PURE__ */ new Set();
      const visited = /* @__PURE__ */ new Set();
      const sorted = new strictMap_1.StrictMap();
      const visit = (type) => {
        if (visiting.has(type.name)) {
          const last = Array.from(visiting).slice(1, 2);
          throw new Error(`dependency cycle between ${type.name} and ${last}`);
        }
        if (!visited.has(type.id)) {
          visiting.add(type.name);
          if (adj.has(type.id)) {
            for (const adjId of adj.get(type.id).values()) {
              visit(graph.get(adjId));
            }
          }
          sorted.set(type.id, type);
          visited.add(type.id);
          visiting.delete(type.name);
        }
      };
      for (const type of types3) {
        visit(type);
      }
      return sorted;
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/casts.js
var require_casts = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/casts.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.casts = void 0;
    var types_1 = require_types();
    var reachableFrom = (source, adj, seen = /* @__PURE__ */ new Set()) => {
      const reachable = /* @__PURE__ */ new Set();
      if (seen.has(source))
        return [];
      seen.add(source);
      (adj[source] || []).map((cast) => {
        reachable.add(cast);
        for (const item of reachableFrom(cast, adj, seen)) {
          reachable.add(item);
        }
      });
      return [...reachable];
    };
    var casts = async (cxn, params) => {
      const allCastsRaw = await cxn.queryJSON(`WITH MODULE schema
        SELECT Cast {
            id,
            source := .from_type { id, name },
            target := .to_type { id, name },
            allow_assignment,
            allow_implicit,
        }
        FILTER .from_type IS ScalarType
        AND .to_type IS ScalarType
        # AND .from_type.is_abstract = false
        # AND .to_type.is_abstract = false
        `);
      const allCasts = JSON.parse(allCastsRaw);
      const types3 = /* @__PURE__ */ new Set();
      const typesById = {};
      const castsById = {};
      const castsBySource = {};
      const implicitCastsBySource = {};
      const implicitCastsByTarget = {};
      const assignmentCastsBySource = {};
      const assignmentCastsByTarget = {};
      for (const cast of allCasts) {
        if (types_1.typeMapping.has(cast.source.id) || types_1.typeMapping.has(cast.target.id)) {
          cast.allow_implicit = false;
          cast.allow_assignment = false;
        }
        typesById[cast.source.id] = cast.source;
        typesById[cast.target.id] = cast.target;
        types3.add(cast.source.id);
        types3.add(cast.target.id);
        castsById[cast.id] = cast;
        castsBySource[cast.source.id] = castsBySource[cast.source.id] || [];
        castsBySource[cast.source.id].push(cast.target.id);
        if (cast.allow_assignment || cast.allow_implicit) {
          assignmentCastsBySource[cast.source.id] ??= [];
          assignmentCastsBySource[cast.source.id].push(cast.target.id);
          assignmentCastsByTarget[cast.target.id] ??= [];
          assignmentCastsByTarget[cast.target.id].push(cast.source.id);
        }
        if (cast.allow_implicit) {
          implicitCastsBySource[cast.source.id] ??= [];
          implicitCastsBySource[cast.source.id].push(cast.target.id);
          implicitCastsByTarget[cast.target.id] ??= [];
          implicitCastsByTarget[cast.target.id].push(cast.source.id);
        }
      }
      const castMap = {};
      const implicitCastMap = {};
      const implicitCastFromMap = {};
      const assignmentCastMap = {};
      const assignableByMap = {};
      for (const type of [...types3]) {
        castMap[type] = castsBySource[type] || [];
        implicitCastMap[type] = reachableFrom(type, implicitCastsBySource);
        implicitCastFromMap[type] = reachableFrom(type, implicitCastsByTarget);
        assignmentCastMap[type] = reachableFrom(type, assignmentCastsBySource);
        assignableByMap[type] = reachableFrom(type, assignmentCastsByTarget);
      }
      if (params?.debug === true) {
        console.log(`
IMPLICIT`);
        for (const [fromId, castArr] of Object.entries(implicitCastMap)) {
          console.log(`${typesById[fromId].name} implicitly castable to: [${castArr.map((id) => typesById[id].name).join(", ")}]`);
        }
        console.log("");
        for (const [fromId, castArr] of Object.entries(implicitCastFromMap)) {
          console.log(`${typesById[fromId].name} implicitly castable from: [${castArr.map((id) => typesById[id].name).join(", ")}]`);
        }
        console.log(`
ASSIGNABLE TO`);
        for (const [fromId, castArr] of Object.entries(assignmentCastMap)) {
          console.log(`${typesById[fromId].name} assignable to: [${castArr.map((id) => typesById[id].name).join(", ")}]`);
        }
        console.log(`
ASSIGNABLE BY`);
        for (const [fromId, castArr] of Object.entries(assignableByMap)) {
          console.log(`${typesById[fromId].name} assignable by: [${castArr.map((id) => typesById[id].name).join(", ")}]`);
        }
        console.log(`
EXPLICIT`);
        for (const [fromId, castArr] of Object.entries(castMap)) {
          console.log(`${typesById[fromId].name} castable to: [${castArr.map((id) => {
            return typesById[id].name;
          }).join(", ")}]`);
        }
      }
      return {
        castsById,
        typesById,
        castMap,
        implicitCastMap,
        implicitCastFromMap,
        assignmentCastMap,
        assignableByMap
      };
    };
    exports2.casts = casts;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/functions.js
var require_functions = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/functions.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.functions = void 0;
    exports2.replaceNumberTypes = replaceNumberTypes;
    var strictMap_1 = require_strictMap();
    var types_1 = require_types();
    var functions = async (cxn) => {
      const functionsJson = await cxn.queryJSON(`
    with module schema
    select Function {
      id,
      name,
      annotations: {
        name,
        @value
      } filter .name = 'std::description',
      return_type: {id, name},
      return_typemod,
      params: {
        name,
        type: {id, name},
        kind,
        typemod,
        hasDefault := exists .default,
      } order by @index,
      preserves_optionality,
    } filter .internal = false
  `);
      const functionMap = new strictMap_1.StrictMap();
      const seenFuncDefHashes = /* @__PURE__ */ new Set();
      for (const func of JSON.parse(functionsJson)) {
        const { name } = func;
        const funcDef = {
          ...func,
          description: func.annotations[0]?.["@value"]
        };
        replaceNumberTypes(funcDef);
        const hash = hashFuncDef(funcDef);
        if (!seenFuncDefHashes.has(hash)) {
          if (!functionMap.has(name)) {
            functionMap.set(name, [funcDef]);
          } else {
            functionMap.get(name).push(funcDef);
          }
          seenFuncDefHashes.add(hash);
        }
      }
      return functionMap;
    };
    exports2.functions = functions;
    function replaceNumberTypes(def) {
      if (types_1.typeMapping.has(def.return_type.id)) {
        const type = types_1.typeMapping.get(def.return_type.id);
        def.return_type = {
          id: type.id,
          name: type.name
        };
      }
      for (const param of def.params) {
        if (types_1.typeMapping.has(param.type.id)) {
          const type = types_1.typeMapping.get(param.type.id);
          param.type = {
            id: type.id,
            name: type.name
          };
        }
      }
    }
    function hashFuncDef(def) {
      return JSON.stringify({
        name: def.name,
        return_type: def.return_type.id,
        return_typemod: def.return_typemod,
        params: def.params.map((param) => JSON.stringify({
          kind: param.kind,
          type: param.type.id,
          typemod: param.typemod,
          hasDefault: !!param.hasDefault
        })).sort(),
        preserves_optionality: def.preserves_optionality
      });
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/globals.js
var require_globals = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/globals.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.globals = globals;
    async function globals(cxn) {
      const globalsMap = /* @__PURE__ */ new Map();
      const version = await cxn.queryRequiredSingle(`select sys::get_version().major;`);
      if (version === 1) {
        return globalsMap;
      }
      const QUERY = `
    WITH
      MODULE schema
    SELECT schema::Global {
      id,
      name,
      target_id := .target.id,
      card := ("One" IF .required ELSE "One" IF EXISTS .default ELSE "AtMostOne")
        IF <str>.cardinality = "One" ELSE
        ("AtLeastOne" IF .required ELSE "Many"),
      has_default := exists .default,
    }
    ORDER BY .name;
  `;
      const allGlobals = JSON.parse(await cxn.queryJSON(QUERY));
      for (const g5 of allGlobals) {
        globalsMap.set(g5.id, g5);
      }
      return globalsMap;
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/operators.js
var require_operators = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/operators.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.operators = void 0;
    var strictMap_1 = require_strictMap();
    var functions_1 = require_functions();
    var util_1 = require_util3();
    var _operators = async (cxn) => {
      const operatorsJson = await cxn.queryJSON(`
    with module schema
    select Operator {
      id,
      name,
      annotations: {
        name,
        @value
      } filter .name in {'std::identifier', 'std::description'},
      operator_kind,
      return_type: {id, name},
      return_typemod,
      params: {
        name,
        type: {id, name},
        kind,
        typemod,
      } order by @index,
    } filter not .internal and not .abstract
  `);
      const operators = new strictMap_1.StrictMap();
      const seenOpDefHashes = /* @__PURE__ */ new Set();
      for (const op of JSON.parse(operatorsJson)) {
        const identifier = op.annotations.find((anno) => anno.name === "std::identifier")?.["@value"];
        if (!identifier) {
          continue;
        }
        const { mod } = util_1.util.splitName(op.name);
        const name = `${mod}::${identifier}`;
        const opDef = {
          ...op,
          name,
          kind: op.operator_kind,
          originalName: op.name,
          description: op.annotations.find((anno) => anno.name === "std::description")?.["@value"],
          annotations: void 0
        };
        (0, functions_1.replaceNumberTypes)(opDef);
        const hash = hashOpDef(opDef);
        if (!seenOpDefHashes.has(hash)) {
          if (!operators.has(name)) {
            operators.set(name, [opDef]);
          } else {
            operators.get(name).push(opDef);
          }
          seenOpDefHashes.add(hash);
        }
      }
      return operators;
    };
    exports2.operators = _operators;
    function hashOpDef(def) {
      return JSON.stringify({
        name: def.name,
        return_type: def.return_type.id,
        return_typemod: def.return_typemod,
        params: def.params.map((param) => JSON.stringify({
          kind: param.kind,
          type: param.type.id,
          typemod: param.typemod,
          hasDefault: !!param.hasDefault
        })).sort(),
        operator_kind: def.operator_kind
      });
    }
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/scalars.js
var require_scalars = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/scalars.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.scalars = void 0;
    var strictMap_1 = require_strictMap();
    var _scalars = async (cxn) => {
      const scalarArray = await cxn.queryJSON(`with module schema
select InheritingObject {
  id,
  name,
  is_abstract,
  bases: { id, name },
  ancestors: { id, name },
  children := .<bases[IS Type] { id, name },
  descendants := .<ancestors[IS Type] { id, name }
}
FILTER
  InheritingObject IS ScalarType OR
  InheritingObject IS ObjectType;
`);
      const scalars = new strictMap_1.StrictMap();
      for (const type of JSON.parse(scalarArray)) {
        scalars.set(type.id, type);
      }
      return scalars;
    };
    exports2.scalars = _scalars;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries.js
var require_queries = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      var desc = Object.getOwnPropertyDescriptor(m6, k5);
      if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m6[k5];
        } };
      }
      Object.defineProperty(o5, k22, desc);
    } : function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      o5[k22] = m6[k5];
    });
    var __exportStar = exports2 && exports2.__exportStar || function(m6, exports3) {
      for (var p5 in m6) if (p5 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p5)) __createBinding(exports3, m6, p5);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    __exportStar(require_casts(), exports2);
    __exportStar(require_functions(), exports2);
    __exportStar(require_globals(), exports2);
    __exportStar(require_operators(), exports2);
    __exportStar(require_scalars(), exports2);
    __exportStar(require_types(), exports2);
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/analyzeQuery.js
var require_analyzeQuery = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/analyzeQuery.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ImportMap = exports2.defaultApplyCardinalityToTsType = exports2.generateTsObjectField = exports2.generateTsObject = exports2.defaultCodecGenerators = exports2.defineCodecGeneratorTuple = exports2.generateTSTypeFromCodec = void 0;
    exports2.analyzeQuery = analyzeQuery;
    var array_1 = require_array();
    var enum_1 = require_enum();
    var ifaces_1 = require_ifaces();
    var namedtuple_1 = require_namedtuple();
    var object_1 = require_object();
    var range_1 = require_range3();
    var codecs_1 = require_codecs();
    var set_1 = require_set();
    var tuple_1 = require_tuple();
    var enums_1 = require_enums();
    var util_1 = require_util3();
    async function analyzeQuery(client, query) {
      const { cardinality, capabilities, in: inCodec, out: outCodec } = await client.describe(query);
      const args = (0, exports2.generateTSTypeFromCodec)(inCodec, enums_1.Cardinality.One, {
        optionalNulls: true,
        readonly: true
      });
      const result = (0, exports2.generateTSTypeFromCodec)(outCodec, cardinality);
      const imports = args.imports.merge(result.imports);
      return {
        result: result.type,
        args: args.type,
        cardinality,
        capabilities,
        query,
        importMap: imports,
        imports: imports.get("gel") ?? /* @__PURE__ */ new Set()
      };
    }
    var generateTSTypeFromCodec = (codec, cardinality = enums_1.Cardinality.One, options = {}) => {
      const optionsWithDefaults = {
        indent: "",
        optionalNulls: false,
        readonly: false,
        ...options
      };
      const context = {
        ...optionsWithDefaults,
        generators: exports2.defaultCodecGenerators,
        applyCardinality: (0, exports2.defaultApplyCardinalityToTsType)(optionsWithDefaults),
        ...options,
        imports: new ImportMap(),
        walk: (codec2, innerContext) => {
          innerContext ??= context;
          for (const [type2, generator] of innerContext.generators) {
            if (codec2 instanceof type2) {
              return generator(codec2, innerContext);
            }
          }
          throw new Error(`Unexpected codec kind: ${codec2.getKind()}`);
        }
      };
      const type = context.applyCardinality(context.walk(codec, context), cardinality);
      return {
        type,
        imports: context.imports
      };
    };
    exports2.generateTSTypeFromCodec = generateTSTypeFromCodec;
    var genDef = (codecType, generator) => [codecType, generator];
    exports2.defineCodecGeneratorTuple = genDef;
    exports2.defaultCodecGenerators = new Map([
      genDef(codecs_1.NullCodec, () => "null"),
      genDef(enum_1.EnumCodec, (codec) => {
        return `(${codec.values.map((val2) => JSON.stringify(val2)).join(" | ")})`;
      }),
      genDef(ifaces_1.ScalarCodec, (codec, ctx) => {
        if (codec.tsModule) {
          ctx.imports.add(codec.tsModule, codec.tsType);
        }
        return codec.tsType;
      }),
      genDef(object_1.ObjectCodec, (codec, ctx) => {
        const subCodecs = codec.getSubcodecs();
        const fields = codec.getFields().map((field, i6) => ({
          name: field.name,
          codec: subCodecs[i6],
          cardinality: util_1.util.parseCardinality(field.cardinality)
        }));
        return (0, exports2.generateTsObject)(fields, ctx);
      }),
      genDef(namedtuple_1.NamedTupleCodec, (codec, ctx) => {
        const subCodecs = codec.getSubcodecs();
        const fields = codec.getNames().map((name, i6) => ({
          name,
          codec: subCodecs[i6],
          cardinality: enums_1.Cardinality.One
        }));
        return (0, exports2.generateTsObject)(fields, ctx);
      }),
      genDef(tuple_1.TupleCodec, (codec, ctx) => {
        const subCodecs = codec.getSubcodecs().map((subCodec) => ctx.walk(subCodec));
        const tuple = `[${subCodecs.join(", ")}]`;
        return ctx.readonly ? `(readonly ${tuple})` : tuple;
      }),
      genDef(array_1.ArrayCodec, (codec, ctx) => ctx.applyCardinality(ctx.walk(codec.getSubcodecs()[0]), enums_1.Cardinality.Many)),
      genDef(range_1.RangeCodec, (codec, ctx) => {
        const subCodec = codec.getSubcodecs()[0];
        if (!(subCodec instanceof ifaces_1.ScalarCodec)) {
          throw Error("expected range subtype to be scalar type");
        }
        ctx.imports.add(codec.tsModule, codec.tsType);
        return `${codec.tsType}<${ctx.walk(subCodec)}>`;
      }),
      genDef(range_1.MultiRangeCodec, (codec, ctx) => {
        const subCodec = codec.getSubcodecs()[0];
        if (!(subCodec instanceof ifaces_1.ScalarCodec)) {
          throw Error("expected multirange subtype to be scalar type");
        }
        ctx.imports.add(codec.tsModule, codec.tsType);
        return `${codec.tsType}<${ctx.walk(subCodec)}>`;
      })
    ]);
    var generateTsObject = (fields, ctx) => {
      const properties = fields.map((field) => (0, exports2.generateTsObjectField)(field, ctx));
      return `{
${properties.join("\n")}
${ctx.indent}}`;
    };
    exports2.generateTsObject = generateTsObject;
    var generateTsObjectField = (field, ctx) => {
      const codec = unwrapSetCodec(field.codec, field.cardinality);
      const name = JSON.stringify(field.name);
      const value = ctx.applyCardinality(ctx.walk(codec, { ...ctx, indent: ctx.indent + "  " }), field.cardinality);
      const optional = ctx.optionalNulls && field.cardinality === enums_1.Cardinality.AtMostOne;
      const questionMark = optional ? "?" : "";
      const isReadonly = ctx.readonly ? "readonly " : "";
      return `${ctx.indent}  ${isReadonly}${name}${questionMark}: ${value};`;
    };
    exports2.generateTsObjectField = generateTsObjectField;
    function unwrapSetCodec(codec, cardinality) {
      if (!(codec instanceof set_1.SetCodec)) {
        return codec;
      }
      if (cardinality === enums_1.Cardinality.Many || cardinality === enums_1.Cardinality.AtLeastOne) {
        return codec.getSubcodecs()[0];
      }
      throw new Error("Sub-codec is SetCodec, but upper cardinality is one");
    }
    var defaultApplyCardinalityToTsType = (ctx) => (type, cardinality) => {
      switch (cardinality) {
        case enums_1.Cardinality.Many:
          return `${ctx.readonly ? "Readonly" : ""}Array<${type}>`;
        case enums_1.Cardinality.One:
          return type;
        case enums_1.Cardinality.AtMostOne:
          return `${type} | null`;
        case enums_1.Cardinality.AtLeastOne: {
          const tuple = `[(${type}), ...(${type})[]]`;
          return ctx.readonly ? `(readonly ${tuple})` : tuple;
        }
      }
      throw new Error(`Unexpected cardinality: ${cardinality}`);
    };
    exports2.defaultApplyCardinalityToTsType = defaultApplyCardinalityToTsType;
    var ImportMap = class _ImportMap extends Map {
      add(module3, specifier) {
        if (!this.has(module3)) {
          this.set(module3, /* @__PURE__ */ new Set());
        }
        this.get(module3).add(specifier);
        return this;
      }
      merge(map2) {
        const out = new _ImportMap();
        for (const [mod, specifiers] of [...this, ...map2]) {
          for (const specifier of specifiers) {
            out.add(mod, specifier);
          }
        }
        return out;
      }
    };
    exports2.ImportMap = ImportMap;
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/index.js
var require_reflection = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/index.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      var desc = Object.getOwnPropertyDescriptor(m6, k5);
      if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m6[k5];
        } };
      }
      Object.defineProperty(o5, k22, desc);
    } : function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      o5[k22] = m6[k5];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v6) {
      Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
    } : function(o5, v6) {
      o5["default"] = v6;
    });
    var __exportStar = exports2 && exports2.__exportStar || function(m6, exports3) {
      for (var p5 in m6) if (p5 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p5)) __createBinding(exports3, m6, p5);
    };
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Capabilities = exports2.introspect = void 0;
    __exportStar(require_enums(), exports2);
    __exportStar(require_util3(), exports2);
    __exportStar(require_typeutil(), exports2);
    __exportStar(require_util3(), exports2);
    __exportStar(require_strictMap(), exports2);
    __exportStar(require_reservedKeywords(), exports2);
    exports2.introspect = __importStar(require_queries());
    __exportStar(require_analyzeQuery(), exports2);
    var baseConn_1 = require_baseConn();
    Object.defineProperty(exports2, "Capabilities", { enumerable: true, get: function() {
      return baseConn_1.Capabilities;
    } });
  }
});

// ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/index.node.js
var require_index_node = __commonJS({
  "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/index.node.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      var desc = Object.getOwnPropertyDescriptor(m6, k5);
      if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m6[k5];
        } };
      }
      Object.defineProperty(o5, k22, desc);
    } : function(o5, m6, k5, k22) {
      if (k22 === void 0) k22 = k5;
      o5[k22] = m6[k5];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v6) {
      Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
    } : function(o5, v6) {
      o5["default"] = v6;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    var __exportStar = exports2 && exports2.__exportStar || function(m6, exports3) {
      for (var p5 in m6) if (p5 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p5)) __createBinding(exports3, m6, p5);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.$ = exports2.Client = exports2.ResolvedConnectConfig = exports2._RawConnection = exports2.systemUtils = exports2.createHttpClient = exports2.createClient = void 0;
    var nodeClient_1 = require_nodeClient();
    exports2.default = nodeClient_1.createClient;
    var nodeClient_2 = require_nodeClient();
    Object.defineProperty(exports2, "createClient", { enumerable: true, get: function() {
      return nodeClient_2.createClient;
    } });
    Object.defineProperty(exports2, "createHttpClient", { enumerable: true, get: function() {
      return nodeClient_2.createHttpClient;
    } });
    var systemUtils = __importStar(require_systemUtils());
    exports2.systemUtils = systemUtils;
    var rawConn_1 = require_rawConn();
    Object.defineProperty(exports2, "_RawConnection", { enumerable: true, get: function() {
      return rawConn_1.RawConnection;
    } });
    var conUtils_1 = require_conUtils();
    Object.defineProperty(exports2, "ResolvedConnectConfig", { enumerable: true, get: function() {
      return conUtils_1.ResolvedConnectConfig;
    } });
    var baseClient_1 = require_baseClient();
    Object.defineProperty(exports2, "Client", { enumerable: true, get: function() {
      return baseClient_1.Client;
    } });
    __exportStar(require_index_shared(), exports2);
    exports2.$ = __importStar(require_reflection());
  }
});

// src/cli/connections.ts
var connections_exports = {};
__export(connections_exports, {
  connectToLibSQL: () => connectToLibSQL,
  connectToMySQL: () => connectToMySQL,
  connectToSQLite: () => connectToSQLite,
  connectToSingleStore: () => connectToSingleStore,
  prepareGelDB: () => prepareGelDB,
  preparePostgresDB: () => preparePostgresDB
});
var preparePostgresDB, prepareGelDB, parseSingleStoreCredentials, connectToSingleStore, parseMysqlCredentials, connectToMySQL, prepareSqliteParams, preparePGliteParams, connectToSQLite, connectToLibSQL;
var init_connections = __esm({
  "src/cli/connections.ts"() {
    "use strict";
    init_src();
    init_wrapper();
    init_global();
    init_utils();
    init_utils4();
    init_outputs();
    preparePostgresDB = async (credentials2) => {
      if ("driver" in credentials2) {
        const { driver: driver2 } = credentials2;
        if (driver2 === "aws-data-api") {
          assertPackages("@aws-sdk/client-rds-data");
          const { RDSDataClient: RDSDataClient2, ExecuteStatementCommand: ExecuteStatementCommand2, TypeHint: TypeHint2 } = await Promise.resolve().then(() => (init_dist_es53(), dist_es_exports8));
          const { AwsDataApiSession, drizzle } = require("drizzle-orm/aws-data-api/pg");
          const { migrate } = require("drizzle-orm/aws-data-api/pg/migrator");
          const { PgDialect: PgDialect2 } = require("drizzle-orm/pg-core");
          const config = {
            database: credentials2.database,
            resourceArn: credentials2.resourceArn,
            secretArn: credentials2.secretArn
          };
          const rdsClient = new RDSDataClient2();
          const session = new AwsDataApiSession(
            rdsClient,
            new PgDialect2(),
            void 0,
            config,
            void 0
          );
          const db = drizzle(rdsClient, config);
          const migrateFn = async (config2) => {
            return migrate(db, config2);
          };
          const query = async (sql, params) => {
            const prepared = session.prepareQuery(
              { sql, params: params ?? [] },
              void 0,
              void 0,
              false
            );
            const result = await prepared.all();
            return result;
          };
          const proxy = async (params) => {
            const prepared = session.prepareQuery(
              {
                sql: params.sql,
                params: params.params ?? [],
                typings: params.typings
              },
              void 0,
              void 0,
              params.mode === "array"
            );
            if (params.mode === "array") {
              const result2 = await prepared.values();
              return result2.rows;
            }
            const result = await prepared.execute();
            return result.rows;
          };
          const transactionProxy = async (queries) => {
            throw new Error("Transaction not supported");
          };
          return {
            packageName: "@aws-sdk/client-rds-data",
            query,
            proxy,
            transactionProxy,
            migrate: migrateFn
          };
        }
        if (driver2 === "pglite") {
          assertPackages("@electric-sql/pglite");
          const { PGlite, types: types3 } = require("@electric-sql/pglite");
          const { drizzle } = require("drizzle-orm/pglite");
          const { migrate } = require("drizzle-orm/pglite/migrator");
          const pglite = "client" in credentials2 ? credentials2.client : new PGlite(normalisePGliteUrl(credentials2.url));
          await pglite.waitReady;
          const drzl = drizzle(pglite);
          const migrateFn = async (config) => {
            return migrate(drzl, config);
          };
          const parsers = {
            [types3.TIMESTAMP]: (value) => value,
            [types3.TIMESTAMPTZ]: (value) => value,
            [types3.INTERVAL]: (value) => value,
            [types3.DATE]: (value) => value
          };
          const query = async (sql, params = []) => {
            const result = await pglite.query(sql, params, {
              parsers
            });
            return result.rows;
          };
          const proxy = async (params) => {
            const preparedParams = preparePGliteParams(params.params || []);
            const result = await pglite.query(params.sql, preparedParams, {
              rowMode: params.mode,
              parsers
            });
            return result.rows;
          };
          const transactionProxy = async (queries) => {
            const results = [];
            try {
              await pglite.transaction(async (tx) => {
                for (const query2 of queries) {
                  const result = await tx.query(query2.sql, void 0, {
                    parsers
                  });
                  results.push(result.rows);
                }
              });
            } catch (error2) {
              results.push(error2);
            }
            return results;
          };
          return { packageName: "pglite", query, proxy, transactionProxy, migrate: migrateFn };
        }
        assertUnreachable(driver2);
      }
      if (await checkPackage("pg")) {
        console.log(withStyle.info(`Using 'pg' driver for database querying`));
        const { default: pg } = require("pg");
        const { drizzle } = require("drizzle-orm/node-postgres");
        const { migrate } = require("drizzle-orm/node-postgres/migrator");
        const ssl = "ssl" in credentials2 ? credentials2.ssl === "prefer" || credentials2.ssl === "require" || credentials2.ssl === "allow" ? { rejectUnauthorized: false } : credentials2.ssl === "verify-full" ? {} : credentials2.ssl : {};
        const types3 = {
          // @ts-ignore
          getTypeParser: (typeId, format) => {
            if (typeId === pg.types.builtins.TIMESTAMPTZ) {
              return (val2) => val2;
            }
            if (typeId === pg.types.builtins.TIMESTAMP) {
              return (val2) => val2;
            }
            if (typeId === pg.types.builtins.DATE) {
              return (val2) => val2;
            }
            if (typeId === pg.types.builtins.INTERVAL) {
              return (val2) => val2;
            }
            return pg.types.getTypeParser(typeId, format);
          }
        };
        const client = "url" in credentials2 ? new pg.Pool({ connectionString: credentials2.url, max: 1 }) : new pg.Pool({ ...credentials2, ssl, max: 1 });
        const db = drizzle(client);
        const migrateFn = async (config) => {
          return migrate(db, config);
        };
        const query = async (sql, params) => {
          const result = await client.query({
            text: sql,
            values: params ?? [],
            types: types3
          });
          return result.rows;
        };
        const proxy = async (params) => {
          const result = await client.query({
            text: params.sql,
            values: params.params,
            ...params.mode === "array" && { rowMode: "array" },
            types: types3
          });
          return result.rows;
        };
        const transactionProxy = async (queries) => {
          const results = [];
          const tx = await client.connect();
          try {
            await tx.query("BEGIN");
            for (const query2 of queries) {
              const result = await tx.query({
                text: query2.sql,
                types: types3
              });
              results.push(result.rows);
            }
            await tx.query("COMMIT");
          } catch (error2) {
            await tx.query("ROLLBACK");
            results.push(error2);
          } finally {
            tx.release();
          }
          return results;
        };
        return { packageName: "pg", query, proxy, transactionProxy, migrate: migrateFn };
      }
      if (await checkPackage("postgres")) {
        console.log(
          withStyle.info(`Using 'postgres' driver for database querying`)
        );
        const postgres = require("postgres");
        const { drizzle } = require("drizzle-orm/postgres-js");
        const { migrate } = require("drizzle-orm/postgres-js/migrator");
        const client = "url" in credentials2 ? postgres.default(credentials2.url, { max: 1 }) : postgres.default({ ...credentials2, max: 1 });
        const transparentParser = (val2) => val2;
        for (const type of ["1184", "1082", "1083", "1114"]) {
          client.options.parsers[type] = transparentParser;
          client.options.serializers[type] = transparentParser;
        }
        client.options.serializers["114"] = transparentParser;
        client.options.serializers["3802"] = transparentParser;
        const db = drizzle(client);
        const migrateFn = async (config) => {
          return migrate(db, config);
        };
        const query = async (sql, params) => {
          const result = await client.unsafe(sql, params ?? []);
          return result;
        };
        const proxy = async (params) => {
          if (params.mode === "array") {
            return await client.unsafe(params.sql, params.params).values();
          }
          return await client.unsafe(params.sql, params.params);
        };
        const transactionProxy = async (queries) => {
          const results = [];
          try {
            await client.begin(async (sql) => {
              for (const query2 of queries) {
                const result = await sql.unsafe(query2.sql);
                results.push(result);
              }
            });
          } catch (error2) {
            results.push(error2);
          }
          return results;
        };
        return { packageName: "postgres", query, proxy, transactionProxy, migrate: migrateFn };
      }
      if (await checkPackage("@vercel/postgres")) {
        console.log(
          withStyle.info(`Using '@vercel/postgres' driver for database querying`)
        );
        console.log(
          withStyle.fullWarning(
            "'@vercel/postgres' can only connect to remote Neon/Vercel Postgres/Supabase instances through a websocket"
          )
        );
        const { VercelPool, types: pgTypes } = require("@vercel/postgres");
        const { drizzle } = require("drizzle-orm/vercel-postgres");
        const { migrate } = require("drizzle-orm/vercel-postgres/migrator");
        const ssl = "ssl" in credentials2 ? credentials2.ssl === "prefer" || credentials2.ssl === "require" || credentials2.ssl === "allow" ? { rejectUnauthorized: false } : credentials2.ssl === "verify-full" ? {} : credentials2.ssl : {};
        const types3 = {
          // @ts-ignore
          getTypeParser: (typeId, format) => {
            if (typeId === pgTypes.builtins.TIMESTAMPTZ) {
              return (val2) => val2;
            }
            if (typeId === pgTypes.builtins.TIMESTAMP) {
              return (val2) => val2;
            }
            if (typeId === pgTypes.builtins.DATE) {
              return (val2) => val2;
            }
            if (typeId === pgTypes.builtins.INTERVAL) {
              return (val2) => val2;
            }
            return pgTypes.getTypeParser(typeId, format);
          }
        };
        const client = "url" in credentials2 ? new VercelPool({ connectionString: credentials2.url }) : new VercelPool({ ...credentials2, ssl });
        await client.connect();
        const db = drizzle(client);
        const migrateFn = async (config) => {
          return migrate(db, config);
        };
        const query = async (sql, params) => {
          const result = await client.query({
            text: sql,
            values: params ?? [],
            types: types3
          });
          return result.rows;
        };
        const proxy = async (params) => {
          const result = await client.query({
            text: params.sql,
            values: params.params,
            ...params.mode === "array" && { rowMode: "array" },
            types: types3
          });
          return result.rows;
        };
        const transactionProxy = async (queries) => {
          const results = [];
          const tx = await client.connect();
          try {
            await tx.query("BEGIN");
            for (const query2 of queries) {
              const result = await tx.query({
                text: query2.sql,
                types: types3
              });
              results.push(result.rows);
            }
            await tx.query("COMMIT");
          } catch (error2) {
            await tx.query("ROLLBACK");
            results.push(error2);
          } finally {
            tx.release();
          }
          return results;
        };
        return { packageName: "@vercel/postgres", query, proxy, transactionProxy, migrate: migrateFn };
      }
      if (await checkPackage("@neondatabase/serverless")) {
        console.log(
          withStyle.info(
            `Using '@neondatabase/serverless' driver for database querying`
          )
        );
        console.log(
          withStyle.fullWarning(
            "'@neondatabase/serverless' can only connect to remote Neon/Vercel Postgres/Supabase instances through a websocket"
          )
        );
        const { Pool, neonConfig, types: pgTypes } = require("@neondatabase/serverless");
        const { drizzle } = require("drizzle-orm/neon-serverless");
        const { migrate } = require("drizzle-orm/neon-serverless/migrator");
        const ssl = "ssl" in credentials2 ? credentials2.ssl === "prefer" || credentials2.ssl === "require" || credentials2.ssl === "allow" ? { rejectUnauthorized: false } : credentials2.ssl === "verify-full" ? {} : credentials2.ssl : {};
        const types3 = {
          // @ts-ignore
          getTypeParser: (typeId, format) => {
            if (typeId === pgTypes.builtins.TIMESTAMPTZ) {
              return (val2) => val2;
            }
            if (typeId === pgTypes.builtins.TIMESTAMP) {
              return (val2) => val2;
            }
            if (typeId === pgTypes.builtins.DATE) {
              return (val2) => val2;
            }
            if (typeId === pgTypes.builtins.INTERVAL) {
              return (val2) => val2;
            }
            return pgTypes.getTypeParser(typeId, format);
          }
        };
        const client = "url" in credentials2 ? new Pool({ connectionString: credentials2.url, max: 1 }) : new Pool({ ...credentials2, max: 1, ssl });
        neonConfig.webSocketConstructor = wrapper_default;
        const db = drizzle(client);
        const migrateFn = async (config) => {
          return migrate(db, config);
        };
        const query = async (sql, params) => {
          const result = await client.query({
            text: sql,
            values: params ?? [],
            types: types3
          });
          return result.rows;
        };
        const proxy = async (params) => {
          const result = await client.query({
            text: params.sql,
            values: params.params,
            ...params.mode === "array" && { rowMode: "array" },
            types: types3
          });
          return result.rows;
        };
        const transactionProxy = async (queries) => {
          const results = [];
          const tx = await client.connect();
          try {
            await tx.query("BEGIN");
            for (const query2 of queries) {
              const result = await tx.query({
                text: query2.sql,
                types: types3
              });
              results.push(result.rows);
            }
            await tx.query("COMMIT");
          } catch (error2) {
            await tx.query("ROLLBACK");
            results.push(error2);
          } finally {
            tx.release();
          }
          return results;
        };
        return { packageName: "@neondatabase/serverless", query, proxy, transactionProxy, migrate: migrateFn };
      }
      console.error(
        "To connect to Postgres database - please install either of 'pg', 'postgres', '@neondatabase/serverless' or '@vercel/postgres' drivers"
      );
      process.exit(1);
    };
    prepareGelDB = async (credentials2) => {
      if (await checkPackage("gel")) {
        const gel = await Promise.resolve().then(() => __toESM(require_index_node()));
        let client;
        if (!credentials2) {
          client = gel.createClient();
          try {
            await client.querySQL(`select 1;`);
          } catch (error2) {
            if (error2 instanceof gel.ClientConnectionError) {
              console.error(
                `It looks like you forgot to link the Gel project or provide the database credentials.
To link your project, please refer https://docs.geldata.com/reference/cli/gel_instance/gel_instance_link, or add the dbCredentials to your configuration file.`
              );
              process.exit(1);
            }
            throw error2;
          }
        } else if ("url" in credentials2) {
          "tlsSecurity" in credentials2 ? client = gel.createClient({ dsn: credentials2.url, tlsSecurity: credentials2.tlsSecurity, concurrency: 1 }) : client = gel.createClient({ dsn: credentials2.url, concurrency: 1 });
        } else {
          gel.createClient({ ...credentials2, concurrency: 1 });
        }
        const query = async (sql, params) => {
          const result = params?.length ? await client.querySQL(sql, params) : await client.querySQL(sql);
          return result;
        };
        const proxy = async (params) => {
          const { method, mode, params: sqlParams, sql, typings } = params;
          let result;
          switch (mode) {
            case "array":
              result = sqlParams?.length ? await client.withSQLRowMode("array").querySQL(sql, sqlParams) : await client.withSQLRowMode("array").querySQL(sql);
              break;
            case "object":
              result = sqlParams?.length ? await client.querySQL(sql, sqlParams) : await client.querySQL(sql);
              break;
          }
          return result;
        };
        const transactionProxy = async (queries) => {
          const result = [];
          try {
            await client.transaction(async (tx) => {
              for (const query2 of queries) {
                const res = await tx.querySQL(query2.sql);
                result.push(res);
              }
            });
          } catch (error2) {
            result.push(error2);
          }
          return result;
        };
        return { packageName: "gel", query, proxy, transactionProxy };
      }
      console.error(
        "To connect to gel database - please install 'edgedb' driver"
      );
      process.exit(1);
    };
    parseSingleStoreCredentials = (credentials2) => {
      if ("url" in credentials2) {
        const url = credentials2.url;
        const connectionUrl = new URL(url);
        const pathname = connectionUrl.pathname;
        const database = pathname.split("/")[pathname.split("/").length - 1];
        if (!database) {
          console.error(
            "You should specify a database name in connection string (singlestore://USER:PASSWORD@HOST:PORT/DATABASE)"
          );
          process.exit(1);
        }
        return { database, url };
      } else {
        return {
          database: credentials2.database,
          credentials: credentials2
        };
      }
    };
    connectToSingleStore = async (it) => {
      const result = parseSingleStoreCredentials(it);
      if (await checkPackage("mysql2")) {
        const { createConnection } = require("mysql2/promise");
        const { drizzle } = require("drizzle-orm/singlestore");
        const { migrate } = require("drizzle-orm/singlestore/migrator");
        const connection = result.url ? await createConnection(result.url) : await createConnection(result.credentials);
        const db = drizzle(connection);
        const migrateFn = async (config) => {
          return migrate(db, config);
        };
        await connection.connect();
        const query = async (sql, params) => {
          const res = await connection.execute(sql, params);
          return res[0];
        };
        const proxy = async (params) => {
          const result2 = await connection.query({
            sql: params.sql,
            values: params.params,
            rowsAsArray: params.mode === "array"
          });
          return result2[0];
        };
        const transactionProxy = async (queries) => {
          const results = [];
          try {
            await connection.beginTransaction();
            for (const query2 of queries) {
              const res = await connection.query(query2.sql);
              results.push(res[0]);
            }
            await connection.commit();
          } catch (error2) {
            await connection.rollback();
            results.push(error2);
          }
          return results;
        };
        return {
          db: { query },
          packageName: "mysql2",
          proxy,
          transactionProxy,
          database: result.database,
          migrate: migrateFn
        };
      }
      console.error(
        "To connect to SingleStore database - please install 'mysql2' driver"
      );
      process.exit(1);
    };
    parseMysqlCredentials = (credentials2) => {
      if ("url" in credentials2) {
        const url = credentials2.url;
        const connectionUrl = new URL(url);
        const pathname = connectionUrl.pathname;
        const database = pathname.split("/")[pathname.split("/").length - 1];
        if (!database) {
          console.error(
            "You should specify a database name in connection string (mysql://USER:PASSWORD@HOST:PORT/DATABASE)"
          );
          process.exit(1);
        }
        return { database, url };
      } else {
        return {
          database: credentials2.database,
          credentials: credentials2
        };
      }
    };
    connectToMySQL = async (it) => {
      const result = parseMysqlCredentials(it);
      if (await checkPackage("mysql2")) {
        const { createConnection } = require("mysql2/promise");
        const { drizzle } = require("drizzle-orm/mysql2");
        const { migrate } = require("drizzle-orm/mysql2/migrator");
        const connection = result.url ? await createConnection(result.url) : await createConnection(result.credentials);
        const db = drizzle(connection);
        const migrateFn = async (config) => {
          return migrate(db, config);
        };
        const typeCast = (field, next) => {
          if (field.type === "TIMESTAMP" || field.type === "DATETIME" || field.type === "DATE") {
            return field.string();
          }
          return next();
        };
        await connection.connect();
        const query = async (sql, params) => {
          const res = await connection.execute({
            sql,
            values: params,
            typeCast
          });
          return res[0];
        };
        const proxy = async (params) => {
          const result2 = await connection.query({
            sql: params.sql,
            values: params.params,
            rowsAsArray: params.mode === "array",
            typeCast
          });
          return result2[0];
        };
        const transactionProxy = async (queries) => {
          const results = [];
          try {
            await connection.beginTransaction();
            for (const query2 of queries) {
              const res = await connection.query(query2.sql);
              results.push(res[0]);
            }
            await connection.commit();
          } catch (error2) {
            await connection.rollback();
            results.push(error2);
          }
          return results;
        };
        return {
          db: { query },
          packageName: "mysql2",
          proxy,
          transactionProxy,
          database: result.database,
          migrate: migrateFn
        };
      }
      if (await checkPackage("@planetscale/database")) {
        const { Client: Client2 } = require("@planetscale/database");
        const { drizzle } = require("drizzle-orm/planetscale-serverless");
        const { migrate } = require("drizzle-orm/planetscale-serverless/migrator");
        const connection = new Client2(result);
        const db = drizzle(connection);
        const migrateFn = async (config) => {
          return migrate(db, config);
        };
        const query = async (sql, params) => {
          const res = await connection.execute(sql, params);
          return res.rows;
        };
        const proxy = async (params) => {
          const result2 = await connection.execute(
            params.sql,
            params.params,
            params.mode === "array" ? { as: "array" } : void 0
          );
          return result2.rows;
        };
        const transactionProxy = async (queries) => {
          const results = [];
          try {
            await connection.transaction(async (tx) => {
              for (const query2 of queries) {
                const res = await tx.execute(query2.sql);
                results.push(res.rows);
              }
            });
          } catch (error2) {
            results.push(error2);
          }
          return results;
        };
        return {
          db: { query },
          packageName: "@planetscale/database",
          proxy,
          transactionProxy,
          database: result.database,
          migrate: migrateFn
        };
      }
      console.error(
        "To connect to MySQL database - please install either of 'mysql2' or '@planetscale/database' drivers"
      );
      process.exit(1);
    };
    prepareSqliteParams = (params, driver2) => {
      return params.map((param) => {
        if (param && typeof param === "object" && "type" in param && "value" in param && param.type === "binary") {
          const value = typeof param.value === "object" ? JSON.stringify(param.value) : param.value;
          if (driver2 === "d1-http") {
            return value;
          }
          return Buffer.from(value);
        }
        return param;
      });
    };
    preparePGliteParams = (params) => {
      return params.map((param) => {
        if (param && typeof param === "object" && "type" in param && "value" in param && param.type === "binary") {
          const value = typeof param.value === "object" ? JSON.stringify(param.value) : param.value;
          return value;
        }
        return param;
      });
    };
    connectToSQLite = async (credentials2) => {
      if ("driver" in credentials2) {
        const { driver: driver2 } = credentials2;
        if (driver2 === "d1-http") {
          const { drizzle } = require("drizzle-orm/sqlite-proxy");
          const { migrate } = require("drizzle-orm/sqlite-proxy/migrator");
          const remoteCallback = async (sql, params, method) => {
            const res = await fetch2(
              `https://api.cloudflare.com/client/v4/accounts/${credentials2.accountId}/d1/database/${credentials2.databaseId}/${method === "values" ? "raw" : "query"}`,
              {
                method: "POST",
                body: JSON.stringify({ sql, params }),
                headers: {
                  "Content-Type": "application/json",
                  Authorization: `Bearer ${credentials2.token}`
                }
              }
            );
            const data = await res.json();
            if (!data.success) {
              throw new Error(
                data.errors.map((it) => `${it.code}: ${it.message}`).join("\n")
              );
            }
            const result = data.result[0].results;
            const rows = Array.isArray(result) ? result : result.rows;
            return {
              rows
            };
          };
          const remoteBatchCallback = async (queries) => {
            const sql = queries.map((q5) => q5.sql).join("; ");
            const res = await fetch2(
              `https://api.cloudflare.com/client/v4/accounts/${credentials2.accountId}/d1/database/${credentials2.databaseId}/query`,
              {
                method: "POST",
                body: JSON.stringify({ sql }),
                headers: {
                  "Content-Type": "application/json",
                  Authorization: `Bearer ${credentials2.token}`
                }
              }
            );
            const data = await res.json();
            if (!data.success) {
              throw new Error(
                data.errors.map((it) => `${it.code}: ${it.message}`).join("\n")
              );
            }
            const rows = data.result.map((result) => {
              const res2 = result.results;
              return Array.isArray(res2) ? res2 : res2.rows;
            });
            return {
              rows
            };
          };
          const drzl = drizzle(remoteCallback);
          const migrateFn = async (config) => {
            return migrate(
              drzl,
              async (queries) => {
                for (const query of queries) {
                  await remoteCallback(query, [], "run");
                }
              },
              config
            );
          };
          const db = {
            query: async (sql, params) => {
              const res = await remoteCallback(sql, params || [], "all");
              return res.rows;
            },
            run: async (query) => {
              await remoteCallback(query, [], "run");
            }
          };
          const proxy = async (params) => {
            const preparedParams = prepareSqliteParams(params.params || [], "d1-http");
            const result = await remoteCallback(
              params.sql,
              preparedParams,
              params.mode === "array" ? "values" : "all"
            );
            return result.rows;
          };
          const transactionProxy = async (queries) => {
            const result = await remoteBatchCallback(queries);
            return result.rows;
          };
          return { ...db, packageName: "d1-http", proxy, transactionProxy, migrate: migrateFn };
        } else {
          assertUnreachable(driver2);
        }
      }
      if (await checkPackage("@libsql/client")) {
        const { createClient } = require("@libsql/client");
        const { drizzle } = require("drizzle-orm/libsql");
        const { migrate } = require("drizzle-orm/libsql/migrator");
        const client = createClient({
          url: normaliseSQLiteUrl(credentials2.url, "libsql")
        });
        const drzl = drizzle(client);
        const migrateFn = async (config) => {
          return migrate(drzl, config);
        };
        const db = {
          query: async (sql, params) => {
            const res = await client.execute({ sql, args: params || [] });
            return res.rows;
          },
          run: async (query) => {
            await client.execute(query);
          }
        };
        const proxy = async (params) => {
          const preparedParams = prepareSqliteParams(params.params || []);
          const result = await client.execute({
            sql: params.sql,
            args: preparedParams
          });
          if (params.mode === "array") {
            return result.rows.map((row) => Object.values(row));
          } else {
            return result.rows;
          }
        };
        const transactionProxy = async (queries) => {
          const results = [];
          let transaction = null;
          try {
            transaction = await client.transaction();
            for (const query of queries) {
              const result = await transaction.execute(query.sql);
              results.push(result.rows);
            }
            await transaction.commit();
          } catch (error2) {
            results.push(error2);
            await transaction?.rollback();
          } finally {
            transaction?.close();
          }
          return results;
        };
        return { ...db, packageName: "@libsql/client", proxy, transactionProxy, migrate: migrateFn };
      }
      if (await checkPackage("better-sqlite3")) {
        const { default: Database } = require("better-sqlite3");
        const { drizzle } = require("drizzle-orm/better-sqlite3");
        const { migrate } = require("drizzle-orm/better-sqlite3/migrator");
        const sqlite = new Database(
          normaliseSQLiteUrl(credentials2.url, "better-sqlite")
        );
        const drzl = drizzle(sqlite);
        const migrateFn = async (config) => {
          return migrate(drzl, config);
        };
        const db = {
          query: async (sql, params = []) => {
            return sqlite.prepare(sql).bind(params).all();
          },
          run: async (query) => {
            sqlite.prepare(query).run();
          }
        };
        const proxy = async (params) => {
          const preparedParams = prepareSqliteParams(params.params || []);
          if (params.method === "values" || params.method === "get" || params.method === "all") {
            return sqlite.prepare(params.sql).raw(params.mode === "array").all(preparedParams);
          }
          sqlite.prepare(params.sql).run(preparedParams);
          return [];
        };
        const transactionProxy = async (queries) => {
          const results = [];
          const tx = sqlite.transaction((queries2) => {
            for (const query of queries2) {
              let result = [];
              if (query.method === "values" || query.method === "get" || query.method === "all") {
                result = sqlite.prepare(query.sql).all();
              } else {
                sqlite.prepare(query.sql).run();
              }
              results.push(result);
            }
          });
          try {
            tx(queries);
          } catch (error2) {
            results.push(error2);
          }
          return results;
        };
        return { ...db, packageName: "better-sqlite3", proxy, transactionProxy, migrate: migrateFn };
      }
      console.log(
        "Please install either 'better-sqlite3' or '@libsql/client' for Drizzle Kit to connect to SQLite databases"
      );
      process.exit(1);
    };
    connectToLibSQL = async (credentials2) => {
      if (await checkPackage("@libsql/client")) {
        const { createClient } = require("@libsql/client");
        const { drizzle } = require("drizzle-orm/libsql");
        const { migrate } = require("drizzle-orm/libsql/migrator");
        const client = createClient({
          url: normaliseSQLiteUrl(credentials2.url, "libsql"),
          authToken: credentials2.authToken
        });
        const drzl = drizzle(client);
        const migrateFn = async (config) => {
          return migrate(drzl, config);
        };
        const db = {
          query: async (sql, params) => {
            const res = await client.execute({ sql, args: params || [] });
            return res.rows;
          },
          run: async (query) => {
            await client.execute(query);
          },
          batchWithPragma: async (queries) => {
            await client.migrate(queries);
          }
        };
        const proxy = async (params) => {
          const preparedParams = prepareSqliteParams(params.params || []);
          const result = await client.execute({
            sql: params.sql,
            args: preparedParams
          });
          if (params.mode === "array") {
            return result.rows.map((row) => Object.values(row));
          } else {
            return result.rows;
          }
        };
        const transactionProxy = async (queries) => {
          const results = [];
          let transaction = null;
          try {
            transaction = await client.transaction();
            for (const query of queries) {
              const result = await transaction.execute(query.sql);
              results.push(result.rows);
            }
            await transaction.commit();
          } catch (error2) {
            results.push(error2);
            await transaction?.rollback();
          } finally {
            transaction?.close();
          }
          return results;
        };
        return { ...db, packageName: "@libsql/client", proxy, transactionProxy, migrate: migrateFn };
      }
      console.log(
        "Please install '@libsql/client' for Drizzle Kit to connect to LibSQL databases"
      );
      process.exit(1);
    };
  }
});

// src/serializer/studio.ts
var studio_exports = {};
__export(studio_exports, {
  drizzleForLibSQL: () => drizzleForLibSQL,
  drizzleForMySQL: () => drizzleForMySQL,
  drizzleForPostgres: () => drizzleForPostgres,
  drizzleForSQLite: () => drizzleForSQLite,
  drizzleForSingleStore: () => drizzleForSingleStore,
  extractRelations: () => extractRelations,
  prepareMySqlSchema: () => prepareMySqlSchema,
  preparePgSchema: () => preparePgSchema,
  prepareSQLiteSchema: () => prepareSQLiteSchema,
  prepareServer: () => prepareServer,
  prepareSingleStoreSchema: () => prepareSingleStoreSchema
});
var import_crypto7, import_drizzle_orm6, import_mysql_core2, import_pg_core3, import_relations2, import_singlestore_core2, import_sqlite_core2, import_fs8, import_node_https2, preparePgSchema, prepareMySqlSchema, prepareSQLiteSchema, prepareSingleStoreSchema, getCustomDefaults, drizzleForPostgres, drizzleForMySQL, drizzleForSQLite, drizzleForLibSQL, drizzleForSingleStore, extractRelations, init, proxySchema, transactionProxySchema, defaultsSchema, schema5, jsonStringify, prepareServer;
var init_studio2 = __esm({
  "src/serializer/studio.ts"() {
    "use strict";
    init_dist();
    init_esm2();
    import_crypto7 = require("crypto");
    import_drizzle_orm6 = require("drizzle-orm");
    import_mysql_core2 = require("drizzle-orm/mysql-core");
    import_pg_core3 = require("drizzle-orm/pg-core");
    import_relations2 = require("drizzle-orm/relations");
    import_singlestore_core2 = require("drizzle-orm/singlestore-core");
    import_sqlite_core2 = require("drizzle-orm/sqlite-core");
    import_fs8 = __toESM(require("fs"));
    init_dist2();
    init_compress2();
    init_cors();
    import_node_https2 = require("https");
    init_global();
    init_esm();
    init_utils3();
    init_serializer();
    init_utils2();
    preparePgSchema = async (path3) => {
      const imports = prepareFilenames(path3);
      const pgSchema2 = {};
      const relations = {};
      const files = imports.map((it, index6) => ({
        // get the file name from the path
        name: it.split("/").pop() || `schema${index6}.ts`,
        content: import_fs8.default.readFileSync(it, "utf-8")
      }));
      const { unregister } = await safeRegister();
      for (let i6 = 0; i6 < imports.length; i6++) {
        const it = imports[i6];
        const i0 = require(`${it}`);
        const i0values = Object.entries(i0);
        i0values.forEach(([k5, t6]) => {
          if ((0, import_drizzle_orm6.is)(t6, import_pg_core3.PgTable)) {
            const schema6 = (0, import_pg_core3.getTableConfig)(t6).schema || "public";
            pgSchema2[schema6] = pgSchema2[schema6] || {};
            pgSchema2[schema6][k5] = t6;
          }
          if ((0, import_drizzle_orm6.is)(t6, import_relations2.Relations)) {
            relations[k5] = t6;
          }
        });
      }
      unregister();
      return { schema: pgSchema2, relations, files };
    };
    prepareMySqlSchema = async (path3) => {
      const imports = prepareFilenames(path3);
      const mysqlSchema3 = {
        public: {}
      };
      const relations = {};
      const files = imports.map((it, index6) => ({
        // get the file name from the path
        name: it.split("/").pop() || `schema${index6}.ts`,
        content: import_fs8.default.readFileSync(it, "utf-8")
      }));
      const { unregister } = await safeRegister();
      for (let i6 = 0; i6 < imports.length; i6++) {
        const it = imports[i6];
        const i0 = require(`${it}`);
        const i0values = Object.entries(i0);
        i0values.forEach(([k5, t6]) => {
          if ((0, import_drizzle_orm6.is)(t6, import_mysql_core2.MySqlTable)) {
            const schema6 = (0, import_mysql_core2.getTableConfig)(t6).schema || "public";
            mysqlSchema3[schema6][k5] = t6;
          }
          if ((0, import_drizzle_orm6.is)(t6, import_relations2.Relations)) {
            relations[k5] = t6;
          }
        });
      }
      unregister();
      return { schema: mysqlSchema3, relations, files };
    };
    prepareSQLiteSchema = async (path3) => {
      const imports = prepareFilenames(path3);
      const sqliteSchema2 = {
        public: {}
      };
      const relations = {};
      const files = imports.map((it, index6) => ({
        // get the file name from the path
        name: it.split("/").pop() || `schema${index6}.ts`,
        content: import_fs8.default.readFileSync(it, "utf-8")
      }));
      const { unregister } = await safeRegister();
      for (let i6 = 0; i6 < imports.length; i6++) {
        const it = imports[i6];
        const i0 = require(`${it}`);
        const i0values = Object.entries(i0);
        i0values.forEach(([k5, t6]) => {
          if ((0, import_drizzle_orm6.is)(t6, import_sqlite_core2.SQLiteTable)) {
            const schema6 = "public";
            sqliteSchema2[schema6][k5] = t6;
          }
          if ((0, import_drizzle_orm6.is)(t6, import_relations2.Relations)) {
            relations[k5] = t6;
          }
        });
      }
      unregister();
      return { schema: sqliteSchema2, relations, files };
    };
    prepareSingleStoreSchema = async (path3) => {
      const imports = prepareFilenames(path3);
      const singlestoreSchema2 = {
        public: {}
      };
      const relations = {};
      const files = imports.map((it, index6) => ({
        // get the file name from the path
        name: it.split("/").pop() || `schema${index6}.ts`,
        content: import_fs8.default.readFileSync(it, "utf-8")
      }));
      const { unregister } = await safeRegister();
      for (let i6 = 0; i6 < imports.length; i6++) {
        const it = imports[i6];
        const i0 = require(`${it}`);
        const i0values = Object.entries(i0);
        i0values.forEach(([k5, t6]) => {
          if ((0, import_drizzle_orm6.is)(t6, import_singlestore_core2.SingleStoreTable)) {
            const schema6 = (0, import_singlestore_core2.getTableConfig)(t6).schema || "public";
            singlestoreSchema2[schema6][k5] = t6;
          }
          if ((0, import_drizzle_orm6.is)(t6, import_relations2.Relations)) {
            relations[k5] = t6;
          }
        });
      }
      unregister();
      return { schema: singlestoreSchema2, relations, files };
    };
    getCustomDefaults = (schema6, casing2) => {
      const customDefaults = [];
      Object.entries(schema6).map(([schema7, tables]) => {
        Object.entries(tables).map(([, table6]) => {
          let tableConfig;
          if ((0, import_drizzle_orm6.is)(table6, import_pg_core3.PgTable)) {
            tableConfig = (0, import_pg_core3.getTableConfig)(table6);
          } else if ((0, import_drizzle_orm6.is)(table6, import_mysql_core2.MySqlTable)) {
            tableConfig = (0, import_mysql_core2.getTableConfig)(table6);
          } else if ((0, import_drizzle_orm6.is)(table6, import_sqlite_core2.SQLiteTable)) {
            tableConfig = (0, import_sqlite_core2.getTableConfig)(table6);
          } else {
            tableConfig = (0, import_singlestore_core2.getTableConfig)(table6);
          }
          tableConfig.columns.map((column6) => {
            if (column6.defaultFn) {
              customDefaults.push({
                schema: schema7,
                table: tableConfig.name,
                column: getColumnCasing(column6, casing2),
                func: column6.defaultFn
              });
            }
          });
        });
      });
      return customDefaults;
    };
    drizzleForPostgres = async (credentials2, pgSchema2, relations, schemaFiles, casing2) => {
      const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const db = await preparePostgresDB2(credentials2);
      const customDefaults = getCustomDefaults(pgSchema2, casing2);
      let dbUrl;
      if ("driver" in credentials2) {
        const { driver: driver2 } = credentials2;
        if (driver2 === "aws-data-api") {
          dbUrl = `aws-data-api://${credentials2.database}/${credentials2.secretArn}/${credentials2.resourceArn}`;
        } else if (driver2 === "pglite") {
          dbUrl = "client" in credentials2 ? credentials2.client.dataDir || "pglite://custom-client" : credentials2.url;
        } else {
          assertUnreachable(driver2);
        }
      } else if ("url" in credentials2) {
        dbUrl = credentials2.url;
      } else {
        dbUrl = `postgresql://${credentials2.user}:${credentials2.password}@${credentials2.host}:${credentials2.port}/${credentials2.database}`;
      }
      const dbHash = (0, import_crypto7.createHash)("sha256").update(dbUrl).digest("hex");
      return {
        dbHash,
        dialect: "postgresql",
        driver: "driver" in credentials2 ? credentials2.driver : void 0,
        packageName: db.packageName,
        proxy: db.proxy,
        transactionProxy: db.transactionProxy,
        customDefaults,
        schema: pgSchema2,
        relations,
        schemaFiles,
        casing: casing2
      };
    };
    drizzleForMySQL = async (credentials2, mysqlSchema3, relations, schemaFiles, casing2) => {
      const { connectToMySQL: connectToMySQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { proxy, transactionProxy, database, packageName } = await connectToMySQL2(credentials2);
      const customDefaults = getCustomDefaults(mysqlSchema3, casing2);
      let dbUrl;
      if ("url" in credentials2) {
        dbUrl = credentials2.url;
      } else {
        dbUrl = `mysql://${credentials2.user}:${credentials2.password}@${credentials2.host}:${credentials2.port}/${credentials2.database}`;
      }
      const dbHash = (0, import_crypto7.createHash)("sha256").update(dbUrl).digest("hex");
      return {
        dbHash,
        dialect: "mysql",
        packageName,
        databaseName: database,
        proxy,
        transactionProxy,
        customDefaults,
        schema: mysqlSchema3,
        relations,
        schemaFiles,
        casing: casing2
      };
    };
    drizzleForSQLite = async (credentials2, sqliteSchema2, relations, schemaFiles, casing2) => {
      const { connectToSQLite: connectToSQLite2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const sqliteDB = await connectToSQLite2(credentials2);
      const customDefaults = getCustomDefaults(sqliteSchema2, casing2);
      let dbUrl;
      if ("driver" in credentials2) {
        const { driver: driver2 } = credentials2;
        if (driver2 === "d1-http") {
          dbUrl = `d1-http://${credentials2.accountId}/${credentials2.databaseId}/${credentials2.token}`;
        } else {
          assertUnreachable(driver2);
        }
      } else {
        dbUrl = credentials2.url;
      }
      const dbHash = (0, import_crypto7.createHash)("sha256").update(dbUrl).digest("hex");
      return {
        dbHash,
        dialect: "sqlite",
        driver: "driver" in credentials2 ? credentials2.driver : void 0,
        packageName: sqliteDB.packageName,
        proxy: sqliteDB.proxy,
        transactionProxy: sqliteDB.transactionProxy,
        customDefaults,
        schema: sqliteSchema2,
        relations,
        schemaFiles,
        casing: casing2
      };
    };
    drizzleForLibSQL = async (credentials2, sqliteSchema2, relations, schemaFiles, casing2) => {
      const { connectToLibSQL: connectToLibSQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const sqliteDB = await connectToLibSQL2(credentials2);
      const customDefaults = getCustomDefaults(sqliteSchema2, casing2);
      let dbUrl = `turso://${credentials2.url}/${credentials2.authToken}`;
      const dbHash = (0, import_crypto7.createHash)("sha256").update(dbUrl).digest("hex");
      return {
        dbHash,
        dialect: "sqlite",
        driver: void 0,
        packageName: sqliteDB.packageName,
        proxy: sqliteDB.proxy,
        transactionProxy: sqliteDB.transactionProxy,
        customDefaults,
        schema: sqliteSchema2,
        relations,
        schemaFiles,
        casing: casing2
      };
    };
    drizzleForSingleStore = async (credentials2, singlestoreSchema2, relations, schemaFiles, casing2) => {
      const { connectToSingleStore: connectToSingleStore2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { proxy, transactionProxy, database, packageName } = await connectToSingleStore2(credentials2);
      const customDefaults = getCustomDefaults(singlestoreSchema2, casing2);
      let dbUrl;
      if ("url" in credentials2) {
        dbUrl = credentials2.url;
      } else {
        dbUrl = `singlestore://${credentials2.user}:${credentials2.password}@${credentials2.host}:${credentials2.port}/${credentials2.database}`;
      }
      const dbHash = (0, import_crypto7.createHash)("sha256").update(dbUrl).digest("hex");
      return {
        dbHash,
        dialect: "singlestore",
        databaseName: database,
        packageName,
        proxy,
        transactionProxy,
        customDefaults,
        schema: singlestoreSchema2,
        relations,
        schemaFiles,
        casing: casing2
      };
    };
    extractRelations = (tablesConfig, casing2) => {
      const relations = Object.values(tablesConfig.tables).map(
        (it) => Object.entries(it.relations).map(([name, relation]) => {
          try {
            const normalized = (0, import_relations2.normalizeRelation)(
              tablesConfig.tables,
              tablesConfig.tableNamesMap,
              relation
            );
            const rel = relation;
            const refTableName = rel.referencedTableName;
            const refTable = rel.referencedTable;
            const fields = normalized.fields.map((it2) => getColumnCasing(it2, casing2)).flat();
            const refColumns = normalized.references.map((it2) => getColumnCasing(it2, casing2)).flat();
            let refSchema;
            if ((0, import_drizzle_orm6.is)(refTable, import_pg_core3.PgTable)) {
              refSchema = (0, import_pg_core3.getTableConfig)(refTable).schema;
            } else if ((0, import_drizzle_orm6.is)(refTable, import_mysql_core2.MySqlTable)) {
              refSchema = (0, import_mysql_core2.getTableConfig)(refTable).schema;
            } else if ((0, import_drizzle_orm6.is)(refTable, import_sqlite_core2.SQLiteTable)) {
              refSchema = void 0;
            } else if ((0, import_drizzle_orm6.is)(refTable, import_singlestore_core2.SingleStoreTable)) {
              refSchema = (0, import_singlestore_core2.getTableConfig)(refTable).schema;
            } else {
              throw new Error("unsupported dialect");
            }
            let type;
            if ((0, import_drizzle_orm6.is)(rel, import_relations2.One)) {
              type = "one";
            } else if ((0, import_drizzle_orm6.is)(rel, import_relations2.Many)) {
              type = "many";
            } else {
              throw new Error("unsupported relation type");
            }
            return {
              name,
              type,
              table: it.dbName,
              schema: it.schema || "public",
              columns: fields,
              refTable: refTableName,
              refSchema: refSchema || "public",
              refColumns
            };
          } catch (error2) {
            throw new Error(
              `Invalid relation "${relation.fieldName}" for table "${it.schema ? `${it.schema}.${it.dbName}` : it.dbName}"`
            );
          }
        })
      ).flat();
      return relations;
    };
    init = external_exports.object({
      type: external_exports.literal("init")
    });
    proxySchema = external_exports.object({
      type: external_exports.literal("proxy"),
      data: external_exports.object({
        sql: external_exports.string(),
        params: external_exports.array(external_exports.any()).optional(),
        typings: external_exports.string().array().optional(),
        mode: external_exports.enum(["array", "object"]).default("object"),
        method: external_exports.union([
          external_exports.literal("values"),
          external_exports.literal("get"),
          external_exports.literal("all"),
          external_exports.literal("run"),
          external_exports.literal("execute")
        ])
      })
    });
    transactionProxySchema = external_exports.object({
      type: external_exports.literal("tproxy"),
      data: external_exports.object({
        sql: external_exports.string(),
        method: external_exports.union([
          external_exports.literal("values"),
          external_exports.literal("get"),
          external_exports.literal("all"),
          external_exports.literal("run"),
          external_exports.literal("execute")
        ]).optional()
      }).array()
    });
    defaultsSchema = external_exports.object({
      type: external_exports.literal("defaults"),
      data: external_exports.array(
        external_exports.object({
          schema: external_exports.string(),
          table: external_exports.string(),
          column: external_exports.string()
        })
      ).min(1)
    });
    schema5 = external_exports.union([
      init,
      proxySchema,
      transactionProxySchema,
      defaultsSchema
    ]);
    jsonStringify = (data) => {
      return JSON.stringify(data, (_key, value) => {
        if (value instanceof Error) {
          return {
            error: value.message
          };
        }
        if (typeof value === "bigint") {
          return value.toString();
        }
        if (value && typeof value === "object" && "type" in value && "data" in value && value.type === "Buffer" || value instanceof ArrayBuffer || value instanceof Buffer) {
          return Buffer.from(value).toString("base64");
        }
        return value;
      });
    };
    prepareServer = async ({
      dialect: dialect6,
      driver: driver2,
      packageName,
      databaseName,
      proxy,
      transactionProxy,
      customDefaults,
      schema: drizzleSchema,
      relations,
      dbHash,
      casing: casing2,
      schemaFiles
    }, app) => {
      app = app !== void 0 ? app : new Hono2();
      app.use(compress());
      app.use(async (ctx, next) => {
        await next();
        ctx.header("Access-Control-Allow-Private-Network", "true");
      });
      app.use(cors());
      app.onError((err2, ctx) => {
        console.error(err2);
        return ctx.json({
          status: "error",
          error: err2.message
        });
      });
      const relationalSchema = {
        ...Object.fromEntries(
          Object.entries(drizzleSchema).map(([schemaName, schema6]) => {
            const mappedTableEntries = Object.entries(schema6).map(
              ([tableName, table6]) => {
                return [`__${schemaName}__.${tableName}`, table6];
              }
            );
            return mappedTableEntries;
          }).flat()
        ),
        ...relations
      };
      const relationsConfig = (0, import_relations2.extractTablesRelationalConfig)(
        relationalSchema,
        import_relations2.createTableRelationsHelpers
      );
      app.post("/", zValidator("json", schema5), async (c5) => {
        const body = c5.req.valid("json");
        const { type } = body;
        if (type === "init") {
          const preparedDefaults = customDefaults.map((d5) => ({
            schema: d5.schema,
            table: d5.table,
            column: d5.column
          }));
          let relations2 = [];
          try {
            relations2 = extractRelations(relationsConfig, casing2);
          } catch (error2) {
            console.warn(
              "Failed to extract relations. This is likely due to ambiguous or misconfigured relations."
            );
            console.warn(
              "Please check your schema and ensure that all relations are correctly defined."
            );
            console.warn(
              "See: https://orm.drizzle.team/docs/relations#disambiguating-relations"
            );
            console.warn("Error message:", error2.message);
          }
          return c5.json({
            version: "6.2",
            dialect: dialect6,
            driver: driver2,
            packageName,
            schemaFiles,
            customDefaults: preparedDefaults,
            relations: relations2,
            dbHash,
            databaseName
          });
        }
        if (type === "proxy") {
          const result = await proxy({
            ...body.data,
            params: body.data.params || []
          });
          return c5.json(JSON.parse(jsonStringify(result)));
        }
        if (type === "tproxy") {
          const result = await transactionProxy(body.data);
          return c5.json(JSON.parse(jsonStringify(result)));
        }
        if (type === "defaults") {
          const columns = body.data;
          const result = columns.map((column6) => {
            const found = customDefaults.find((d5) => {
              return d5.schema === column6.schema && d5.table === column6.table && d5.column === column6.column;
            });
            if (!found) {
              throw new Error(
                `Custom default not found for ${column6.schema}.${column6.table}.${column6.column}`
              );
            }
            const value = found.func();
            return {
              ...column6,
              value
            };
          });
          return c5.json(JSON.parse(jsonStringify(result)));
        }
        throw new Error(`Unknown type: ${type}`);
      });
      return {
        start: (params) => {
          serve(
            {
              fetch: app.fetch,
              createServer: params.key ? import_node_https2.createServer : void 0,
              hostname: params.host,
              port: params.port,
              serverOptions: {
                key: params.key,
                cert: params.cert
              }
            },
            () => params.cb(null, `${params.host}:${params.port}`)
          );
        }
      };
    };
  }
});

// src/serializer/sqliteImports.ts
var sqliteImports_exports = {};
__export(sqliteImports_exports, {
  prepareFromExports: () => prepareFromExports2,
  prepareFromSqliteImports: () => prepareFromSqliteImports
});
var import_drizzle_orm7, import_sqlite_core3, prepareFromExports2, prepareFromSqliteImports;
var init_sqliteImports = __esm({
  "src/serializer/sqliteImports.ts"() {
    "use strict";
    import_drizzle_orm7 = require("drizzle-orm");
    import_sqlite_core3 = require("drizzle-orm/sqlite-core");
    init_utils3();
    prepareFromExports2 = (exports2) => {
      const tables = [];
      const views = [];
      const i0values = Object.values(exports2);
      i0values.forEach((t6) => {
        if ((0, import_drizzle_orm7.is)(t6, import_sqlite_core3.SQLiteTable)) {
          tables.push(t6);
        }
        if ((0, import_drizzle_orm7.is)(t6, import_sqlite_core3.SQLiteView)) {
          views.push(t6);
        }
      });
      return { tables, views };
    };
    prepareFromSqliteImports = async (imports) => {
      const tables = [];
      const views = [];
      const { unregister } = await safeRegister();
      for (let i6 = 0; i6 < imports.length; i6++) {
        const it = imports[i6];
        const i0 = require(`${it}`);
        const prepared = prepareFromExports2(i0);
        tables.push(...prepared.tables);
        views.push(...prepared.views);
      }
      unregister();
      return { tables: Array.from(new Set(tables)), views };
    };
  }
});

// src/serializer/mysqlImports.ts
var mysqlImports_exports = {};
__export(mysqlImports_exports, {
  prepareFromExports: () => prepareFromExports3,
  prepareFromMySqlImports: () => prepareFromMySqlImports
});
var import_drizzle_orm8, import_mysql_core3, prepareFromExports3, prepareFromMySqlImports;
var init_mysqlImports = __esm({
  "src/serializer/mysqlImports.ts"() {
    "use strict";
    import_drizzle_orm8 = require("drizzle-orm");
    import_mysql_core3 = require("drizzle-orm/mysql-core");
    init_utils3();
    prepareFromExports3 = (exports2) => {
      const tables = [];
      const views = [];
      const i0values = Object.values(exports2);
      i0values.forEach((t6) => {
        if ((0, import_drizzle_orm8.is)(t6, import_mysql_core3.MySqlTable)) {
          tables.push(t6);
        }
        if ((0, import_drizzle_orm8.is)(t6, import_mysql_core3.MySqlView)) {
          views.push(t6);
        }
      });
      return { tables, views };
    };
    prepareFromMySqlImports = async (imports) => {
      const tables = [];
      const views = [];
      const { unregister } = await safeRegister();
      for (let i6 = 0; i6 < imports.length; i6++) {
        const it = imports[i6];
        const i0 = require(`${it}`);
        const prepared = prepareFromExports3(i0);
        tables.push(...prepared.tables);
        views.push(...prepared.views);
      }
      unregister();
      return { tables: Array.from(new Set(tables)), views };
    };
  }
});

// src/cli/commands/mysqlPushUtils.ts
var mysqlPushUtils_exports = {};
__export(mysqlPushUtils_exports, {
  filterStatements: () => filterStatements,
  logSuggestionsAndReturn: () => logSuggestionsAndReturn2
});
var import_hanji8, filterStatements, logSuggestionsAndReturn2;
var init_mysqlPushUtils = __esm({
  "src/cli/commands/mysqlPushUtils.ts"() {
    "use strict";
    init_source();
    import_hanji8 = __toESM(require_hanji());
    init_mysqlSchema();
    init_selector_ui();
    init_outputs();
    filterStatements = (statements, currentSchema, prevSchema) => {
      return statements.filter((statement) => {
        if (statement.type === "alter_table_alter_column_set_type") {
          if (statement.oldDataType.startsWith("tinyint") && statement.newDataType.startsWith("boolean")) {
            return false;
          }
          if (statement.oldDataType.startsWith("bigint unsigned") && statement.newDataType.startsWith("serial")) {
            return false;
          }
          if (statement.oldDataType.startsWith("serial") && statement.newDataType.startsWith("bigint unsigned")) {
            return false;
          }
        } else if (statement.type === "alter_table_alter_column_set_default") {
          if (statement.newDefaultValue === false && statement.oldDefaultValue === 0 && statement.newDataType === "boolean") {
            return false;
          }
          if (statement.newDefaultValue === true && statement.oldDefaultValue === 1 && statement.newDataType === "boolean") {
            return false;
          }
        } else if (statement.type === "delete_unique_constraint") {
          const unsquashed = MySqlSquasher.unsquashUnique(statement.data);
          if (unsquashed.columns.length === 1 && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && prevSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].name === unsquashed.columns[0]) {
            return false;
          }
        } else if (statement.type === "alter_table_alter_column_drop_notnull") {
          const serialStatement = statements.find(
            (it) => it.type === "alter_table_alter_column_set_type"
          );
          if (serialStatement?.oldDataType.startsWith("bigint unsigned") && serialStatement?.newDataType.startsWith("serial") && serialStatement.columnName === statement.columnName && serialStatement.tableName === statement.tableName) {
            return false;
          }
          if (statement.newDataType === "serial" && !statement.columnNotNull) {
            return false;
          }
          if (statement.columnAutoIncrement) {
            return false;
          }
        }
        return true;
      });
    };
    logSuggestionsAndReturn2 = async (db, statements, json2) => {
      let shouldAskForApprove = false;
      const statementsToExecute = [];
      const infoToPrint = [];
      const tablesToRemove = [];
      const columnsToRemove = [];
      const schemasToRemove = [];
      const tablesToTruncate = [];
      for (const statement of statements) {
        if (statement.type === "drop_table") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.tableName
              )} table with ${count} items`
            );
            tablesToRemove.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_drop_column") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.columnName
              )} column in ${statement.tableName} table with ${count} items`
            );
            columnsToRemove.push(`${statement.tableName}_${statement.columnName}`);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "drop_schema") {
          const res = await db.query(
            `select count(*) as count from information_schema.tables where table_schema = \`${statement.name}\`;`
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.name
              )} schema with ${count} tables`
            );
            schemasToRemove.push(statement.name);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_alter_column_set_type") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to change ${source_default.underline(
                statement.columnName
              )} column type from ${source_default.underline(
                statement.oldDataType
              )} to ${source_default.underline(statement.newDataType)} with ${count} items`
            );
            statementsToExecute.push(`truncate table ${statement.tableName};`);
            tablesToTruncate.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_alter_column_drop_default") {
          if (statement.columnNotNull) {
            const res = await db.query(
              `select count(*) as count from \`${statement.tableName}\``
            );
            const count = Number(res[0].count);
            if (count > 0) {
              infoToPrint.push(
                `\xB7 You're about to remove default value from ${source_default.underline(
                  statement.columnName
                )} not-null column with ${count} items`
              );
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "alter_table_alter_column_set_notnull") {
          if (typeof statement.columnDefault === "undefined") {
            const res = await db.query(
              `select count(*) as count from \`${statement.tableName}\``
            );
            const count = Number(res[0].count);
            if (count > 0) {
              infoToPrint.push(
                `\xB7 You're about to set not-null constraint to ${source_default.underline(
                  statement.columnName
                )} column without default, which contains ${count} items`
              );
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "alter_table_alter_column_drop_pk") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          if (Object.values(json2.tables[statement.tableName].columns).filter(
            (column6) => column6.autoincrement
          ).length > 0) {
            console.log(
              `${withStyle.errorWarning(
                `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
              )}`
            );
            process.exit(1);
          }
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to change ${source_default.underline(
                statement.tableName
              )} primary key. This statements may fail and you table may left without primary key`
            );
            tablesToTruncate.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "delete_composite_pk") {
          if (Object.values(json2.tables[statement.tableName].columns).filter(
            (column6) => column6.autoincrement
          ).length > 0) {
            console.log(
              `${withStyle.errorWarning(
                `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
              )}`
            );
            process.exit(1);
          }
        } else if (statement.type === "alter_table_add_column") {
          if (statement.column.notNull && typeof statement.column.default === "undefined") {
            const res = await db.query(
              `select count(*) as count from \`${statement.tableName}\``
            );
            const count = Number(res[0].count);
            if (count > 0) {
              infoToPrint.push(
                `\xB7 You're about to add not-null ${source_default.underline(
                  statement.column.name
                )} column without default value, which contains ${count} items`
              );
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "create_unique_constraint") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            const unsquashedUnique = MySqlSquasher.unsquashUnique(statement.data);
            console.log(
              `\xB7 You're about to add ${source_default.underline(
                unsquashedUnique.name
              )} unique constraint to the table, which contains ${count} items. If this statement fails, you will receive an error from the database. Do you want to truncate ${source_default.underline(
                statement.tableName
              )} table?
`
            );
            const { status, data } = await (0, import_hanji8.render)(
              new Select([
                "No, add the constraint without truncating the table",
                `Yes, truncate the table`
              ])
            );
            if (data?.index === 1) {
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        }
      }
      return {
        statementsToExecute,
        shouldAskForApprove,
        infoToPrint,
        columnsToRemove: [...new Set(columnsToRemove)],
        schemasToRemove: [...new Set(schemasToRemove)],
        tablesToTruncate: [...new Set(tablesToTruncate)],
        tablesToRemove: [...new Set(tablesToRemove)]
      };
    };
  }
});

// src/cli/commands/mysqlIntrospect.ts
var mysqlIntrospect_exports = {};
__export(mysqlIntrospect_exports, {
  mysqlPushIntrospect: () => mysqlPushIntrospect
});
var import_hanji9, mysqlPushIntrospect;
var init_mysqlIntrospect = __esm({
  "src/cli/commands/mysqlIntrospect.ts"() {
    "use strict";
    import_hanji9 = __toESM(require_hanji());
    init_mjs();
    init_global();
    init_mysqlSerializer();
    init_views();
    mysqlPushIntrospect = async (db, databaseName, filters) => {
      const matchers = filters.map((it) => {
        return new Minimatch(it);
      });
      const filter2 = (tableName) => {
        if (matchers.length === 0) return true;
        let flags = [];
        for (let matcher of matchers) {
          if (matcher.negate) {
            if (!matcher.match(tableName)) {
              flags.push(false);
            }
          }
          if (matcher.match(tableName)) {
            flags.push(true);
          }
        }
        if (flags.length > 0) {
          return flags.every(Boolean);
        }
        return false;
      };
      const progress = new ProgressView(
        "Pulling schema from database...",
        "Pulling schema from database..."
      );
      const res = await (0, import_hanji9.renderWithTask)(
        progress,
        fromDatabase3(db, databaseName, filter2)
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const { internal, ...schemaWithoutInternals } = schema6;
      return { schema: schemaWithoutInternals };
    };
  }
});

// src/serializer/singlestoreImports.ts
var singlestoreImports_exports = {};
__export(singlestoreImports_exports, {
  prepareFromExports: () => prepareFromExports4,
  prepareFromSingleStoreImports: () => prepareFromSingleStoreImports
});
var import_drizzle_orm9, import_singlestore_core3, prepareFromExports4, prepareFromSingleStoreImports;
var init_singlestoreImports = __esm({
  "src/serializer/singlestoreImports.ts"() {
    "use strict";
    import_drizzle_orm9 = require("drizzle-orm");
    import_singlestore_core3 = require("drizzle-orm/singlestore-core");
    init_utils3();
    prepareFromExports4 = (exports2) => {
      const tables = [];
      const i0values = Object.values(exports2);
      i0values.forEach((t6) => {
        if ((0, import_drizzle_orm9.is)(t6, import_singlestore_core3.SingleStoreTable)) {
          tables.push(t6);
        }
      });
      return {
        tables
        /* views  */
      };
    };
    prepareFromSingleStoreImports = async (imports) => {
      const tables = [];
      const { unregister } = await safeRegister();
      for (let i6 = 0; i6 < imports.length; i6++) {
        const it = imports[i6];
        const i0 = require(`${it}`);
        const prepared = prepareFromExports4(i0);
        tables.push(...prepared.tables);
      }
      unregister();
      return {
        tables: Array.from(new Set(tables))
        /* , views */
      };
    };
  }
});

// src/cli/commands/singlestorePushUtils.ts
var singlestorePushUtils_exports = {};
__export(singlestorePushUtils_exports, {
  filterStatements: () => filterStatements2,
  findColumnTypeAlternations: () => findColumnTypeAlternations,
  logSuggestionsAndReturn: () => logSuggestionsAndReturn3
});
function findColumnTypeAlternations(columns1, columns2) {
  const changes = [];
  for (const key in columns1) {
    if (columns1.hasOwnProperty(key) && columns2.hasOwnProperty(key)) {
      const col1 = columns1[key];
      const col2 = columns2[key];
      if (col1.type !== col2.type) {
        changes.push(col2.name);
      }
    }
  }
  return changes;
}
var import_hanji10, filterStatements2, logSuggestionsAndReturn3;
var init_singlestorePushUtils = __esm({
  "src/cli/commands/singlestorePushUtils.ts"() {
    "use strict";
    init_source();
    import_hanji10 = __toESM(require_hanji());
    init_sqlgenerator();
    init_singlestoreSchema();
    init_utils();
    init_selector_ui();
    init_outputs();
    filterStatements2 = (statements, currentSchema, prevSchema) => {
      return statements.filter((statement) => {
        if (statement.type === "alter_table_alter_column_set_type") {
          if (statement.oldDataType.startsWith("tinyint") && statement.newDataType.startsWith("boolean")) {
            return false;
          }
          if (statement.oldDataType.startsWith("bigint unsigned") && statement.newDataType.startsWith("serial")) {
            return false;
          }
          if (statement.oldDataType.startsWith("serial") && statement.newDataType.startsWith("bigint unsigned")) {
            return false;
          }
        } else if (statement.type === "alter_table_alter_column_set_default") {
          if (statement.newDefaultValue === false && statement.oldDefaultValue === 0 && statement.newDataType === "boolean") {
            return false;
          }
          if (statement.newDefaultValue === true && statement.oldDefaultValue === 1 && statement.newDataType === "boolean") {
            return false;
          }
        } else if (statement.type === "delete_unique_constraint") {
          const unsquashed = SingleStoreSquasher.unsquashUnique(statement.data);
          if (unsquashed.columns.length === 1 && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && prevSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].name === unsquashed.columns[0]) {
            return false;
          }
        } else if (statement.type === "alter_table_alter_column_drop_notnull") {
          const serialStatement = statements.find(
            (it) => it.type === "alter_table_alter_column_set_type"
          );
          if (serialStatement?.oldDataType.startsWith("bigint unsigned") && serialStatement?.newDataType.startsWith("serial") && serialStatement.columnName === statement.columnName && serialStatement.tableName === statement.tableName) {
            return false;
          }
          if (statement.newDataType === "serial" && !statement.columnNotNull) {
            return false;
          }
          if (statement.columnAutoIncrement) {
            return false;
          }
        }
        return true;
      });
    };
    logSuggestionsAndReturn3 = async (db, statements, json2, json1) => {
      let shouldAskForApprove = false;
      const statementsToExecute = [];
      const infoToPrint = [];
      const tablesToRemove = [];
      const columnsToRemove = [];
      const schemasToRemove = [];
      const tablesToTruncate = [];
      for (const statement of statements) {
        if (statement.type === "drop_table") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.tableName
              )} table with ${count} items`
            );
            tablesToRemove.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_drop_column") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.columnName
              )} column in ${statement.tableName} table with ${count} items`
            );
            columnsToRemove.push(`${statement.tableName}_${statement.columnName}`);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "drop_schema") {
          const res = await db.query(
            `select count(*) as count from information_schema.tables where table_schema = \`${statement.name}\`;`
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.name
              )} schema with ${count} tables`
            );
            schemasToRemove.push(statement.name);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_alter_column_set_type") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to change ${source_default.underline(
                statement.columnName
              )} column type from ${source_default.underline(
                statement.oldDataType
              )} to ${source_default.underline(statement.newDataType)} with ${count} items`
            );
            statementsToExecute.push(`truncate table ${statement.tableName};`);
            tablesToTruncate.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_alter_column_drop_default") {
          if (statement.columnNotNull) {
            const res = await db.query(
              `select count(*) as count from \`${statement.tableName}\``
            );
            const count = Number(res[0].count);
            if (count > 0) {
              infoToPrint.push(
                `\xB7 You're about to remove default value from ${source_default.underline(
                  statement.columnName
                )} not-null column with ${count} items`
              );
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "alter_table_alter_column_set_notnull") {
          if (typeof statement.columnDefault === "undefined") {
            const res = await db.query(
              `select count(*) as count from \`${statement.tableName}\``
            );
            const count = Number(res[0].count);
            if (count > 0) {
              infoToPrint.push(
                `\xB7 You're about to set not-null constraint to ${source_default.underline(
                  statement.columnName
                )} column without default, which contains ${count} items`
              );
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "alter_table_alter_column_drop_pk") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          if (Object.values(json2.tables[statement.tableName].columns).filter(
            (column6) => column6.autoincrement
          ).length > 0) {
            console.log(
              `${withStyle.errorWarning(
                `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
              )}`
            );
            process.exit(1);
          }
          const count = Number(res[0].count);
          if (count > 0) {
            infoToPrint.push(
              `\xB7 You're about to change ${source_default.underline(
                statement.tableName
              )} primary key. This statements may fail and you table may left without primary key`
            );
            tablesToTruncate.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "delete_composite_pk") {
          if (Object.values(json2.tables[statement.tableName].columns).filter(
            (column6) => column6.autoincrement
          ).length > 0) {
            console.log(
              `${withStyle.errorWarning(
                `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
              )}`
            );
            process.exit(1);
          }
        } else if (statement.type === "alter_table_add_column") {
          if (statement.column.notNull && typeof statement.column.default === "undefined") {
            const res = await db.query(
              `select count(*) as count from \`${statement.tableName}\``
            );
            const count = Number(res[0].count);
            if (count > 0) {
              infoToPrint.push(
                `\xB7 You're about to add not-null ${source_default.underline(
                  statement.column.name
                )} column without default value, which contains ${count} items`
              );
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "create_unique_constraint") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count = Number(res[0].count);
          if (count > 0) {
            const unsquashedUnique = SingleStoreSquasher.unsquashUnique(statement.data);
            console.log(
              `\xB7 You're about to add ${source_default.underline(
                unsquashedUnique.name
              )} unique constraint to the table, which contains ${count} items. If this statement fails, you will receive an error from the database. Do you want to truncate ${source_default.underline(
                statement.tableName
              )} table?
`
            );
            const { status, data } = await (0, import_hanji10.render)(
              new Select([
                "No, add the constraint without truncating the table",
                `Yes, truncate the table`
              ])
            );
            if (data?.index === 1) {
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "singlestore_recreate_table") {
          const tableName = statement.tableName;
          const prevColumns = json1.tables[tableName].columns;
          const currentColumns = json2.tables[tableName].columns;
          const { removedColumns, addedColumns } = findAddedAndRemoved(
            Object.keys(prevColumns),
            Object.keys(currentColumns)
          );
          if (removedColumns.length) {
            for (const removedColumn of removedColumns) {
              const res = await db.query(
                `select count(\`${tableName}\`.\`${removedColumn}\`) as count from \`${tableName}\``
              );
              const count = Number(res[0].count);
              if (count > 0) {
                infoToPrint.push(
                  `\xB7 You're about to delete ${source_default.underline(
                    removedColumn
                  )} column in ${tableName} table with ${count} items`
                );
                columnsToRemove.push(removedColumn);
                shouldAskForApprove = true;
              }
            }
          }
          if (addedColumns.length) {
            for (const addedColumn of addedColumns) {
              const [res] = await db.query(
                `select count(*) as count from \`${tableName}\``
              );
              const columnConf = json2.tables[tableName].columns[addedColumn];
              const count = Number(res.count);
              if (count > 0 && columnConf.notNull && !columnConf.default) {
                infoToPrint.push(
                  `\xB7 You're about to add not-null ${source_default.underline(
                    addedColumn
                  )} column without default value to table, which contains ${count} items`
                );
                shouldAskForApprove = true;
                tablesToTruncate.push(tableName);
                statementsToExecute.push(`TRUNCATE TABLE \`${tableName}\`;`);
              }
            }
          }
          const columnWithChangedType = findColumnTypeAlternations(prevColumns, currentColumns);
          for (const column6 of columnWithChangedType) {
            const [res] = await db.query(
              `select count(*) as count from \`${tableName}\` WHERE \`${tableName}\`.\`${column6}\` IS NOT NULL;`
            );
            const count = Number(res.count);
            if (count > 0) {
              infoToPrint.push(
                `\xB7 You're about recreate ${source_default.underline(tableName)} table with data type changing for ${source_default.underline(
                  column6
                )} column, which contains ${count} items`
              );
              shouldAskForApprove = true;
              tablesToTruncate.push(tableName);
              statementsToExecute.push(`TRUNCATE TABLE \`${tableName}\`;`);
            }
          }
        }
        const stmnt = fromJson([statement], "singlestore", "push");
        if (typeof stmnt !== "undefined") {
          statementsToExecute.push(...stmnt);
        }
      }
      return {
        statementsToExecute,
        shouldAskForApprove,
        infoToPrint,
        columnsToRemove: [...new Set(columnsToRemove)],
        schemasToRemove: [...new Set(schemasToRemove)],
        tablesToTruncate: [...new Set(tablesToTruncate)],
        tablesToRemove: [...new Set(tablesToRemove)]
      };
    };
  }
});

// src/cli/commands/singlestoreIntrospect.ts
var singlestoreIntrospect_exports = {};
__export(singlestoreIntrospect_exports, {
  singlestorePushIntrospect: () => singlestorePushIntrospect
});
var import_hanji11, singlestorePushIntrospect;
var init_singlestoreIntrospect = __esm({
  "src/cli/commands/singlestoreIntrospect.ts"() {
    "use strict";
    import_hanji11 = __toESM(require_hanji());
    init_mjs();
    init_global();
    init_singlestoreSerializer();
    init_views();
    singlestorePushIntrospect = async (db, databaseName, filters) => {
      const matchers = filters.map((it) => {
        return new Minimatch(it);
      });
      const filter2 = (tableName) => {
        if (matchers.length === 0) return true;
        let flags = [];
        for (let matcher of matchers) {
          if (matcher.negate) {
            if (!matcher.match(tableName)) {
              flags.push(false);
            }
          }
          if (matcher.match(tableName)) {
            flags.push(true);
          }
        }
        if (flags.length > 0) {
          return flags.every(Boolean);
        }
        return false;
      };
      const progress = new ProgressView(
        "Pulling schema from database...",
        "Pulling schema from database..."
      );
      const res = await (0, import_hanji11.renderWithTask)(
        progress,
        fromDatabase4(db, databaseName, filter2)
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const { internal, ...schemaWithoutInternals } = schema6;
      return { schema: schemaWithoutInternals };
    };
  }
});

// src/api.ts
var api_exports = {};
__export(api_exports, {
  generateDrizzleJson: () => generateDrizzleJson,
  generateMigration: () => generateMigration,
  generateMySQLDrizzleJson: () => generateMySQLDrizzleJson,
  generateMySQLMigration: () => generateMySQLMigration,
  generateSQLiteDrizzleJson: () => generateSQLiteDrizzleJson,
  generateSQLiteMigration: () => generateSQLiteMigration,
  generateSingleStoreDrizzleJson: () => generateSingleStoreDrizzleJson,
  generateSingleStoreMigration: () => generateSingleStoreMigration,
  pushMySQLSchema: () => pushMySQLSchema,
  pushSQLiteSchema: () => pushSQLiteSchema,
  pushSchema: () => pushSchema,
  pushSingleStoreSchema: () => pushSingleStoreSchema,
  startStudioMySQLServer: () => startStudioMySQLServer,
  startStudioPostgresServer: () => startStudioPostgresServer,
  startStudioSQLiteServer: () => startStudioSQLiteServer,
  startStudioSingleStoreServer: () => startStudioSingleStoreServer,
  upPgSnapshot: () => upPgSnapshot
});
module.exports = __toCommonJS(api_exports);
var import_crypto8 = require("crypto");
var import_drizzle_orm10 = require("drizzle-orm");
var import_mysql_core4 = require("drizzle-orm/mysql-core");
var import_pg_core4 = require("drizzle-orm/pg-core");
var import_relations3 = require("drizzle-orm/relations");
var import_singlestore_core4 = require("drizzle-orm/singlestore-core");
var import_sqlite_core4 = require("drizzle-orm/sqlite-core");
init_migrate();

// src/cli/commands/pgIntrospect.ts
var import_hanji3 = __toESM(require_hanji());
init_mjs();
init_global();
init_pgSerializer();
init_views();
var pgPushIntrospect = async (db, filters, schemaFilters, entities, tsSchema) => {
  const matchers = filters.map((it) => {
    return new Minimatch(it);
  });
  const filter2 = (tableName) => {
    if (matchers.length === 0) return true;
    let flags = [];
    for (let matcher of matchers) {
      if (matcher.negate) {
        if (!matcher.match(tableName)) {
          flags.push(false);
        }
      }
      if (matcher.match(tableName)) {
        flags.push(true);
      }
    }
    if (flags.length > 0) {
      return flags.every(Boolean);
    }
    return false;
  };
  const progress = new ProgressView(
    "Pulling schema from database...",
    "Pulling schema from database..."
  );
  const res = await (0, import_hanji3.renderWithTask)(
    progress,
    fromDatabase(db, filter2, schemaFilters, entities, void 0, tsSchema)
  );
  const schema6 = { id: originUUID, prevId: "", ...res };
  const { internal, ...schemaWithoutInternals } = schema6;
  return { schema: schemaWithoutInternals };
};

// src/cli/commands/pgPushUtils.ts
init_source();
var import_hanji5 = __toESM(require_hanji());
init_pgSchema();
init_sqlgenerator();
init_selector_ui();
function concatSchemaAndTableName(schema6, table6) {
  return schema6 ? `"${schema6}"."${table6}"` : `"${table6}"`;
}
function tableNameWithSchemaFrom(schema6, tableName, renamedSchemas, renamedTables) {
  const newSchemaName = schema6 ? renamedSchemas[schema6] ? renamedSchemas[schema6] : schema6 : void 0;
  const newTableName = renamedTables[concatSchemaAndTableName(newSchemaName, tableName)] ? renamedTables[concatSchemaAndTableName(newSchemaName, tableName)] : tableName;
  return concatSchemaAndTableName(newSchemaName, newTableName);
}
var pgSuggestions = async (db, statements) => {
  let shouldAskForApprove = false;
  const statementsToExecute = [];
  const infoToPrint = [];
  const tablesToRemove = [];
  const columnsToRemove = [];
  const schemasToRemove = [];
  const tablesToTruncate = [];
  const matViewsToRemove = [];
  let renamedSchemas = {};
  let renamedTables = {};
  for (const statement of statements) {
    if (statement.type === "rename_schema") {
      renamedSchemas[statement.to] = statement.from;
    } else if (statement.type === "rename_table") {
      renamedTables[concatSchemaAndTableName(statement.toSchema, statement.tableNameTo)] = statement.tableNameFrom;
    } else if (statement.type === "drop_table") {
      const res = await db.query(
        `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
      );
      const count = Number(res[0].count);
      if (count > 0) {
        infoToPrint.push(`\xB7 You're about to delete ${source_default.underline(statement.tableName)} table with ${count} items`);
        tablesToRemove.push(statement.tableName);
        shouldAskForApprove = true;
      }
    } else if (statement.type === "drop_view" && statement.materialized) {
      const res = await db.query(`select count(*) as count from "${statement.schema ?? "public"}"."${statement.name}"`);
      const count = Number(res[0].count);
      if (count > 0) {
        infoToPrint.push(
          `\xB7 You're about to delete "${source_default.underline(statement.name)}" materialized view with ${count} items`
        );
        matViewsToRemove.push(statement.name);
        shouldAskForApprove = true;
      }
    } else if (statement.type === "alter_table_drop_column") {
      const res = await db.query(
        `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
      );
      const count = Number(res[0].count);
      if (count > 0) {
        infoToPrint.push(
          `\xB7 You're about to delete ${source_default.underline(statement.columnName)} column in ${statement.tableName} table with ${count} items`
        );
        columnsToRemove.push(`${statement.tableName}_${statement.columnName}`);
        shouldAskForApprove = true;
      }
    } else if (statement.type === "drop_schema") {
      const res = await db.query(
        `select count(*) as count from information_schema.tables where table_schema = '${statement.name}';`
      );
      const count = Number(res[0].count);
      if (count > 0) {
        infoToPrint.push(`\xB7 You're about to delete ${source_default.underline(statement.name)} schema with ${count} tables`);
        schemasToRemove.push(statement.name);
        shouldAskForApprove = true;
      }
    } else if (statement.type === "alter_table_alter_column_set_type") {
      const res = await db.query(
        `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
      );
      const count = Number(res[0].count);
      if (count > 0) {
        infoToPrint.push(
          `\xB7 You're about to change ${source_default.underline(statement.columnName)} column type from ${source_default.underline(statement.oldDataType)} to ${source_default.underline(
            statement.newDataType
          )} with ${count} items`
        );
        statementsToExecute.push(
          `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
        );
        tablesToTruncate.push(statement.tableName);
        shouldAskForApprove = true;
      }
    } else if (statement.type === "alter_table_alter_column_drop_pk") {
      const res = await db.query(
        `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
      );
      const count = Number(res[0].count);
      if (count > 0) {
        infoToPrint.push(
          `\xB7 You're about to change ${source_default.underline(statement.tableName)} primary key. This statements may fail and you table may left without primary key`
        );
        tablesToTruncate.push(statement.tableName);
        shouldAskForApprove = true;
      }
      const tableNameWithSchema = tableNameWithSchemaFrom(
        statement.schema,
        statement.tableName,
        renamedSchemas,
        renamedTables
      );
      const pkNameResponse = await db.query(
        `SELECT constraint_name FROM information_schema.table_constraints
        WHERE table_schema = '${typeof statement.schema === "undefined" || statement.schema === "" ? "public" : statement.schema}'
            AND table_name = '${statement.tableName}'
            AND constraint_type = 'PRIMARY KEY';`
      );
      statementsToExecute.push(
        `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${pkNameResponse[0].constraint_name}"`
      );
      continue;
    } else if (statement.type === "alter_table_add_column") {
      if (statement.column.notNull && typeof statement.column.default === "undefined") {
        const res = await db.query(
          `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
        );
        const count = Number(res[0].count);
        if (count > 0) {
          infoToPrint.push(
            `\xB7 You're about to add not-null ${source_default.underline(statement.column.name)} column without default value, which contains ${count} items`
          );
          tablesToTruncate.push(statement.tableName);
          statementsToExecute.push(
            `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
          );
          shouldAskForApprove = true;
        }
      }
    } else if (statement.type === "create_unique_constraint") {
      const res = await db.query(
        `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
      );
      const count = Number(res[0].count);
      if (count > 0) {
        const unsquashedUnique = PgSquasher.unsquashUnique(statement.data);
        console.log(
          `\xB7 You're about to add ${source_default.underline(
            unsquashedUnique.name
          )} unique constraint to the table, which contains ${count} items. If this statement fails, you will receive an error from the database. Do you want to truncate ${source_default.underline(
            statement.tableName
          )} table?
`
        );
        const { status, data } = await (0, import_hanji5.render)(
          new Select(["No, add the constraint without truncating the table", `Yes, truncate the table`])
        );
        if (data?.index === 1) {
          tablesToTruncate.push(statement.tableName);
          statementsToExecute.push(
            `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
          );
          shouldAskForApprove = true;
        }
      }
    }
    const stmnt = fromJson([statement], "postgresql", "push");
    if (typeof stmnt !== "undefined") {
      statementsToExecute.push(...stmnt);
    }
  }
  return {
    statementsToExecute: [...new Set(statementsToExecute)],
    shouldAskForApprove,
    infoToPrint,
    matViewsToRemove: [...new Set(matViewsToRemove)],
    columnsToRemove: [...new Set(columnsToRemove)],
    schemasToRemove: [...new Set(schemasToRemove)],
    tablesToTruncate: [...new Set(tablesToTruncate)],
    tablesToRemove: [...new Set(tablesToRemove)]
  };
};

// src/cli/commands/pgUp.ts
init_pgSchema();
init_utils();
var updateUpToV6 = (json) => {
  const schema6 = pgSchemaV5.parse(json);
  const tables = Object.fromEntries(
    Object.entries(schema6.tables).map((it) => {
      const table6 = it[1];
      const schema7 = table6.schema || "public";
      return [`${schema7}.${table6.name}`, table6];
    })
  );
  const enums = Object.fromEntries(
    Object.entries(schema6.enums).map((it) => {
      const en = it[1];
      return [
        `public.${en.name}`,
        {
          name: en.name,
          schema: "public",
          values: Object.values(en.values)
        }
      ];
    })
  );
  return {
    ...schema6,
    version: "6",
    dialect: "postgresql",
    tables,
    enums
  };
};
var updateUpToV7 = (json) => {
  const schema6 = pgSchemaV6.parse(json);
  const tables = Object.fromEntries(
    Object.entries(schema6.tables).map((it) => {
      const table6 = it[1];
      const mappedIndexes = Object.fromEntries(
        Object.entries(table6.indexes).map((idx) => {
          const { columns, ...rest } = idx[1];
          const mappedColumns = columns.map((it2) => {
            return {
              expression: it2,
              isExpression: false,
              asc: true,
              nulls: "last",
              opClass: void 0
            };
          });
          return [idx[0], { columns: mappedColumns, with: {}, ...rest }];
        })
      );
      return [it[0], { ...table6, indexes: mappedIndexes, policies: {}, isRLSEnabled: false, checkConstraints: {} }];
    })
  );
  return {
    ...schema6,
    version: "7",
    dialect: "postgresql",
    sequences: {},
    tables,
    policies: {},
    views: {},
    roles: {}
  };
};

// src/cli/commands/sqliteIntrospect.ts
var import_hanji6 = __toESM(require_hanji());
init_mjs();
init_global();

// src/introspect-sqlite.ts
var import_casing2 = require("drizzle-orm/casing");

// ../node_modules/.pnpm/camelcase@7.0.1/node_modules/camelcase/index.js
var UPPERCASE = /[\p{Lu}]/u;
var LOWERCASE = /[\p{Ll}]/u;
var LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
var IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
var SEPARATORS = /[_.\- ]+/;
var LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source);
var SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu");
var NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu");
var preserveCamelCase = (string, toLowerCase, toUpperCase, preserveConsecutiveUppercase2) => {
  let isLastCharLower = false;
  let isLastCharUpper = false;
  let isLastLastCharUpper = false;
  let isLastLastCharPreserved = false;
  for (let index6 = 0; index6 < string.length; index6++) {
    const character = string[index6];
    isLastLastCharPreserved = index6 > 2 ? string[index6 - 3] === "-" : true;
    if (isLastCharLower && UPPERCASE.test(character)) {
      string = string.slice(0, index6) + "-" + string.slice(index6);
      isLastCharLower = false;
      isLastLastCharUpper = isLastCharUpper;
      isLastCharUpper = true;
      index6++;
    } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character) && (!isLastLastCharPreserved || preserveConsecutiveUppercase2)) {
      string = string.slice(0, index6 - 1) + "-" + string.slice(index6 - 1);
      isLastLastCharUpper = isLastCharUpper;
      isLastCharUpper = false;
      isLastCharLower = true;
    } else {
      isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;
      isLastLastCharUpper = isLastCharUpper;
      isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;
    }
  }
  return string;
};
var preserveConsecutiveUppercase = (input, toLowerCase) => {
  LEADING_CAPITAL.lastIndex = 0;
  return input.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1));
};
var postProcess = (input, toUpperCase) => {
  SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
  NUMBERS_AND_IDENTIFIER.lastIndex = 0;
  return input.replace(SEPARATORS_AND_IDENTIFIER, (_3, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m6) => toUpperCase(m6));
};
function camelCase(input, options) {
  if (!(typeof input === "string" || Array.isArray(input))) {
    throw new TypeError("Expected the input to be `string | string[]`");
  }
  options = {
    pascalCase: false,
    preserveConsecutiveUppercase: false,
    ...options
  };
  if (Array.isArray(input)) {
    input = input.map((x5) => x5.trim()).filter((x5) => x5.length).join("-");
  } else {
    input = input.trim();
  }
  if (input.length === 0) {
    return "";
  }
  const toLowerCase = options.locale === false ? (string) => string.toLowerCase() : (string) => string.toLocaleLowerCase(options.locale);
  const toUpperCase = options.locale === false ? (string) => string.toUpperCase() : (string) => string.toLocaleUpperCase(options.locale);
  if (input.length === 1) {
    if (SEPARATORS.test(input)) {
      return "";
    }
    return options.pascalCase ? toUpperCase(input) : toLowerCase(input);
  }
  const hasUpperCase = input !== toLowerCase(input);
  if (hasUpperCase) {
    input = preserveCamelCase(input, toLowerCase, toUpperCase, options.preserveConsecutiveUppercase);
  }
  input = input.replace(LEADING_SEPARATORS, "");
  input = options.preserveConsecutiveUppercase ? preserveConsecutiveUppercase(input, toLowerCase) : toLowerCase(input);
  if (options.pascalCase) {
    input = toUpperCase(input.charAt(0)) + input.slice(1);
  }
  return postProcess(input, toUpperCase);
}

// src/@types/utils.ts
String.prototype.trimChar = function(char) {
  let start = 0;
  let end = this.length;
  while (start < end && this[start] === char) ++start;
  while (end > start && this[end - 1] === char) --end;
  return start > 0 || end < this.length ? this.substring(start, end) : this.toString();
};
String.prototype.squashSpaces = function() {
  return this.replace(/  +/g, " ").trim();
};
String.prototype.camelCase = function() {
  return camelCase(String(this));
};
String.prototype.capitalise = function() {
  return this && this.length > 0 ? `${this[0].toUpperCase()}${this.slice(1)}` : String(this);
};
String.prototype.concatIf = function(it, condition) {
  return condition ? `${this}${it}` : String(this);
};
String.prototype.snake_case = function() {
  return this && this.length > 0 ? `${this.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)}` : String(this);
};
Array.prototype.random = function() {
  return this[~~(Math.random() * this.length)];
};

// src/introspect-sqlite.ts
init_global();

// src/cli/commands/sqliteIntrospect.ts
init_sqliteSerializer();
init_views();
var sqlitePushIntrospect = async (db, filters) => {
  const matchers = filters.map((it) => {
    return new Minimatch(it);
  });
  const filter2 = (tableName) => {
    if (matchers.length === 0) return true;
    let flags = [];
    for (let matcher of matchers) {
      if (matcher.negate) {
        if (!matcher.match(tableName)) {
          flags.push(false);
        }
      }
      if (matcher.match(tableName)) {
        flags.push(true);
      }
    }
    if (flags.length > 0) {
      return flags.every(Boolean);
    }
    return false;
  };
  const progress = new ProgressView(
    "Pulling schema from database...",
    "Pulling schema from database..."
  );
  const res = await (0, import_hanji6.renderWithTask)(progress, fromDatabase2(db, filter2));
  const schema6 = { id: originUUID, prevId: "", ...res };
  return { schema: schema6 };
};

// src/api.ts
init_sqlitePushUtils();
init_getTablesFilterByExtensions();
init_global();
init_mysqlSchema();
init_mysqlSerializer();
init_pgImports();
init_pgSchema();
init_pgSerializer();
init_singlestoreSchema();
init_singlestoreSerializer();
init_sqliteSchema();
init_sqliteSerializer();

// ../node_modules/.pnpm/env-paths@3.0.0/node_modules/env-paths/index.js
var import_node_path = __toESM(require("path"), 1);
var import_node_os2 = __toESM(require("os"), 1);
var import_node_process2 = __toESM(require("process"), 1);
var homedir = import_node_os2.default.homedir();
var tmpdir = import_node_os2.default.tmpdir();
var { env: env2 } = import_node_process2.default;
var macos = (name) => {
  const library = import_node_path.default.join(homedir, "Library");
  return {
    data: import_node_path.default.join(library, "Application Support", name),
    config: import_node_path.default.join(library, "Preferences", name),
    cache: import_node_path.default.join(library, "Caches", name),
    log: import_node_path.default.join(library, "Logs", name),
    temp: import_node_path.default.join(tmpdir, name)
  };
};
var windows = (name) => {
  const appData = env2.APPDATA || import_node_path.default.join(homedir, "AppData", "Roaming");
  const localAppData = env2.LOCALAPPDATA || import_node_path.default.join(homedir, "AppData", "Local");
  return {
    // Data/config/cache/log are invented by me as Windows isn't opinionated about this
    data: import_node_path.default.join(localAppData, name, "Data"),
    config: import_node_path.default.join(appData, name, "Config"),
    cache: import_node_path.default.join(localAppData, name, "Cache"),
    log: import_node_path.default.join(localAppData, name, "Log"),
    temp: import_node_path.default.join(tmpdir, name)
  };
};
var linux = (name) => {
  const username = import_node_path.default.basename(homedir);
  return {
    data: import_node_path.default.join(env2.XDG_DATA_HOME || import_node_path.default.join(homedir, ".local", "share"), name),
    config: import_node_path.default.join(env2.XDG_CONFIG_HOME || import_node_path.default.join(homedir, ".config"), name),
    cache: import_node_path.default.join(env2.XDG_CACHE_HOME || import_node_path.default.join(homedir, ".cache"), name),
    // https://wiki.debian.org/XDGBaseDirectorySpecification#state
    log: import_node_path.default.join(env2.XDG_STATE_HOME || import_node_path.default.join(homedir, ".local", "state"), name),
    temp: import_node_path.default.join(tmpdir, username, name)
  };
};
function envPaths(name, { suffix = "nodejs" } = {}) {
  if (typeof name !== "string") {
    throw new TypeError(`Expected a string, got ${typeof name}`);
  }
  if (suffix) {
    name += `-${suffix}`;
  }
  if (import_node_process2.default.platform === "darwin") {
    return macos(name);
  }
  if (import_node_process2.default.platform === "win32") {
    return windows(name);
  }
  return linux(name);
}

// src/utils/certs.ts
var import_fs2 = require("fs");
var import_promises = require("fs/promises");
var import_node_child_process = require("child_process");
var import_path2 = require("path");
function runCommand(command, options = {}) {
  return new Promise((resolve) => {
    (0, import_node_child_process.exec)(command, options, (error2) => {
      return resolve({ exitCode: error2?.code ?? 0 });
    });
  });
}
var certs = async () => {
  const res = await runCommand("mkcert --help");
  if (res.exitCode === 0) {
    const p5 = envPaths("drizzle-studio", {
      suffix: ""
    });
    (0, import_fs2.mkdirSync)(p5.data, { recursive: true });
    const keyPath = (0, import_path2.join)(p5.data, "localhost-key.pem");
    const certPath = (0, import_path2.join)(p5.data, "localhost.pem");
    try {
      await Promise.all([(0, import_promises.access)(keyPath), (0, import_promises.access)(certPath)]);
    } catch (e6) {
      await runCommand(`mkcert localhost`, { cwd: p5.data });
    }
    const [key, cert] = await Promise.all([
      (0, import_promises.readFile)(keyPath, { encoding: "utf-8" }),
      (0, import_promises.readFile)(certPath, { encoding: "utf-8" })
    ]);
    return key && cert ? { key, cert } : null;
  }
  return null;
};

// src/api.ts
var generateDrizzleJson = (imports, prevId, schemaFilters, casing2) => {
  const prepared = prepareFromExports(imports);
  const id = (0, import_crypto8.randomUUID)();
  const snapshot = generatePgSnapshot(
    prepared.tables,
    prepared.enums,
    prepared.schemas,
    prepared.sequences,
    prepared.roles,
    prepared.policies,
    prepared.views,
    prepared.matViews,
    casing2,
    schemaFilters
  );
  return {
    ...snapshot,
    id,
    prevId: prevId ?? originUUID
  };
};
var generateMigration = async (prev, cur) => {
  const { applyPgSnapshotsDiff: applyPgSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const validatedPrev = pgSchema.parse(prev);
  const validatedCur = pgSchema.parse(cur);
  const squashedPrev = squashPgScheme(validatedPrev);
  const squashedCur = squashPgScheme(validatedCur);
  const { sqlStatements, _meta } = await applyPgSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    schemasResolver,
    enumsResolver,
    sequencesResolver,
    policyResolver,
    indPolicyResolver,
    roleResolver,
    tablesResolver,
    columnsResolver,
    viewsResolver,
    validatedPrev,
    validatedCur
  );
  return sqlStatements;
};
var pushSchema = async (imports, drizzleInstance, schemaFilters, tablesFilter, extensionsFilters) => {
  const { applyPgSnapshotsDiff: applyPgSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const { sql } = require("drizzle-orm");
  const filters = (tablesFilter ?? []).concat(
    getTablesFilterByExtensions({ extensionsFilters, dialect: "postgresql" })
  );
  const db = {
    query: async (query, params) => {
      const res = await drizzleInstance.execute(sql.raw(query));
      return res.rows;
    }
  };
  const cur = generateDrizzleJson(imports);
  const { schema: prev } = await pgPushIntrospect(
    db,
    filters,
    schemaFilters ?? ["public"],
    void 0
  );
  const validatedPrev = pgSchema.parse(prev);
  const validatedCur = pgSchema.parse(cur);
  const squashedPrev = squashPgScheme(validatedPrev, "push");
  const squashedCur = squashPgScheme(validatedCur, "push");
  const { statements } = await applyPgSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    schemasResolver,
    enumsResolver,
    sequencesResolver,
    policyResolver,
    indPolicyResolver,
    roleResolver,
    tablesResolver,
    columnsResolver,
    viewsResolver,
    validatedPrev,
    validatedCur,
    "push"
  );
  const { shouldAskForApprove, statementsToExecute, infoToPrint } = await pgSuggestions(db, statements);
  return {
    hasDataLoss: shouldAskForApprove,
    warnings: infoToPrint,
    statementsToExecute,
    apply: async () => {
      for (const dStmnt of statementsToExecute) {
        await db.query(dStmnt);
      }
    }
  };
};
var startStudioPostgresServer = async (imports, credentials2, options) => {
  const { drizzleForPostgres: drizzleForPostgres2 } = await Promise.resolve().then(() => (init_studio2(), studio_exports));
  const pgSchema2 = {};
  const relations = {};
  Object.entries(imports).forEach(([k5, t6]) => {
    if ((0, import_drizzle_orm10.is)(t6, import_pg_core4.PgTable)) {
      const schema6 = (0, import_pg_core4.getTableConfig)(t6).schema || "public";
      pgSchema2[schema6] = pgSchema2[schema6] || {};
      pgSchema2[schema6][k5] = t6;
    }
    if ((0, import_drizzle_orm10.is)(t6, import_relations3.Relations)) {
      relations[k5] = t6;
    }
  });
  const setup = await drizzleForPostgres2(credentials2, pgSchema2, relations, [], options?.casing);
  await startServerFromSetup(setup, options);
};
var generateSQLiteDrizzleJson = async (imports, prevId, casing2) => {
  const { prepareFromExports: prepareFromExports5 } = await Promise.resolve().then(() => (init_sqliteImports(), sqliteImports_exports));
  const prepared = prepareFromExports5(imports);
  const id = (0, import_crypto8.randomUUID)();
  const snapshot = generateSqliteSnapshot(prepared.tables, prepared.views, casing2);
  return {
    ...snapshot,
    id,
    prevId: prevId ?? originUUID
  };
};
var generateSQLiteMigration = async (prev, cur) => {
  const { applySqliteSnapshotsDiff: applySqliteSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const validatedPrev = sqliteSchema.parse(prev);
  const validatedCur = sqliteSchema.parse(cur);
  const squashedPrev = squashSqliteScheme(validatedPrev);
  const squashedCur = squashSqliteScheme(validatedCur);
  const { sqlStatements } = await applySqliteSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    tablesResolver,
    columnsResolver,
    sqliteViewsResolver,
    validatedPrev,
    validatedCur
  );
  return sqlStatements;
};
var pushSQLiteSchema = async (imports, drizzleInstance) => {
  const { applySqliteSnapshotsDiff: applySqliteSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const { sql } = require("drizzle-orm");
  const db = {
    query: async (query, params) => {
      const res = drizzleInstance.all(sql.raw(query));
      return res;
    },
    run: async (query) => {
      return Promise.resolve(drizzleInstance.run(sql.raw(query))).then(
        () => {
        }
      );
    }
  };
  const cur = await generateSQLiteDrizzleJson(imports);
  const { schema: prev } = await sqlitePushIntrospect(db, []);
  const validatedPrev = sqliteSchema.parse(prev);
  const validatedCur = sqliteSchema.parse(cur);
  const squashedPrev = squashSqliteScheme(validatedPrev, "push");
  const squashedCur = squashSqliteScheme(validatedCur, "push");
  const { statements, _meta } = await applySqliteSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    tablesResolver,
    columnsResolver,
    sqliteViewsResolver,
    validatedPrev,
    validatedCur,
    "push"
  );
  const { shouldAskForApprove, statementsToExecute, infoToPrint } = await logSuggestionsAndReturn(
    db,
    statements,
    squashedPrev,
    squashedCur,
    _meta
  );
  return {
    hasDataLoss: shouldAskForApprove,
    warnings: infoToPrint,
    statementsToExecute,
    apply: async () => {
      for (const dStmnt of statementsToExecute) {
        await db.query(dStmnt);
      }
    }
  };
};
var startStudioSQLiteServer = async (imports, credentials2, options) => {
  const { drizzleForSQLite: drizzleForSQLite2 } = await Promise.resolve().then(() => (init_studio2(), studio_exports));
  const sqliteSchema2 = {};
  const relations = {};
  Object.entries(imports).forEach(([k5, t6]) => {
    if ((0, import_drizzle_orm10.is)(t6, import_sqlite_core4.SQLiteTable)) {
      const schema6 = "public";
      sqliteSchema2[schema6] = sqliteSchema2[schema6] || {};
      sqliteSchema2[schema6][k5] = t6;
    }
    if ((0, import_drizzle_orm10.is)(t6, import_relations3.Relations)) {
      relations[k5] = t6;
    }
  });
  const setup = await drizzleForSQLite2(credentials2, sqliteSchema2, relations, [], options?.casing);
  await startServerFromSetup(setup, options);
};
var generateMySQLDrizzleJson = async (imports, prevId, casing2) => {
  const { prepareFromExports: prepareFromExports5 } = await Promise.resolve().then(() => (init_mysqlImports(), mysqlImports_exports));
  const prepared = prepareFromExports5(imports);
  const id = (0, import_crypto8.randomUUID)();
  const snapshot = generateMySqlSnapshot(prepared.tables, prepared.views, casing2);
  return {
    ...snapshot,
    id,
    prevId: prevId ?? originUUID
  };
};
var generateMySQLMigration = async (prev, cur) => {
  const { applyMysqlSnapshotsDiff: applyMysqlSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const validatedPrev = mysqlSchema.parse(prev);
  const validatedCur = mysqlSchema.parse(cur);
  const squashedPrev = squashMysqlScheme(validatedPrev);
  const squashedCur = squashMysqlScheme(validatedCur);
  const { sqlStatements } = await applyMysqlSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    tablesResolver,
    columnsResolver,
    mySqlViewsResolver,
    validatedPrev,
    validatedCur
  );
  return sqlStatements;
};
var pushMySQLSchema = async (imports, drizzleInstance, databaseName) => {
  const { applyMysqlSnapshotsDiff: applyMysqlSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const { logSuggestionsAndReturn: logSuggestionsAndReturn4 } = await Promise.resolve().then(() => (init_mysqlPushUtils(), mysqlPushUtils_exports));
  const { mysqlPushIntrospect: mysqlPushIntrospect2 } = await Promise.resolve().then(() => (init_mysqlIntrospect(), mysqlIntrospect_exports));
  const { sql } = require("drizzle-orm");
  const db = {
    query: async (query, params) => {
      const res = await drizzleInstance.execute(sql.raw(query));
      return res[0];
    }
  };
  const cur = await generateMySQLDrizzleJson(imports);
  const { schema: prev } = await mysqlPushIntrospect2(db, databaseName, []);
  const validatedPrev = mysqlSchema.parse(prev);
  const validatedCur = mysqlSchema.parse(cur);
  const squashedPrev = squashMysqlScheme(validatedPrev);
  const squashedCur = squashMysqlScheme(validatedCur);
  const { statements } = await applyMysqlSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    tablesResolver,
    columnsResolver,
    mySqlViewsResolver,
    validatedPrev,
    validatedCur,
    "push"
  );
  const { shouldAskForApprove, statementsToExecute, infoToPrint } = await logSuggestionsAndReturn4(
    db,
    statements,
    validatedCur
  );
  return {
    hasDataLoss: shouldAskForApprove,
    warnings: infoToPrint,
    statementsToExecute,
    apply: async () => {
      for (const dStmnt of statementsToExecute) {
        await db.query(dStmnt);
      }
    }
  };
};
var startStudioMySQLServer = async (imports, credentials2, options) => {
  const { drizzleForMySQL: drizzleForMySQL2 } = await Promise.resolve().then(() => (init_studio2(), studio_exports));
  const mysqlSchema3 = {};
  const relations = {};
  Object.entries(imports).forEach(([k5, t6]) => {
    if ((0, import_drizzle_orm10.is)(t6, import_mysql_core4.MySqlTable)) {
      const schema6 = (0, import_mysql_core4.getTableConfig)(t6).schema || "public";
      mysqlSchema3[schema6] = mysqlSchema3[schema6] || {};
      mysqlSchema3[schema6][k5] = t6;
    }
    if ((0, import_drizzle_orm10.is)(t6, import_relations3.Relations)) {
      relations[k5] = t6;
    }
  });
  const setup = await drizzleForMySQL2(credentials2, mysqlSchema3, relations, [], options?.casing);
  await startServerFromSetup(setup, options);
};
var generateSingleStoreDrizzleJson = async (imports, prevId, casing2) => {
  const { prepareFromExports: prepareFromExports5 } = await Promise.resolve().then(() => (init_singlestoreImports(), singlestoreImports_exports));
  const prepared = prepareFromExports5(imports);
  const id = (0, import_crypto8.randomUUID)();
  const snapshot = generateSingleStoreSnapshot(
    prepared.tables,
    /* prepared.views, */
    casing2
  );
  return {
    ...snapshot,
    id,
    prevId: prevId ?? originUUID
  };
};
var generateSingleStoreMigration = async (prev, cur) => {
  const { applySingleStoreSnapshotsDiff: applySingleStoreSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const validatedPrev = singlestoreSchema.parse(prev);
  const validatedCur = singlestoreSchema.parse(cur);
  const squashedPrev = squashSingleStoreScheme(validatedPrev);
  const squashedCur = squashSingleStoreScheme(validatedCur);
  const { sqlStatements } = await applySingleStoreSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    tablesResolver,
    columnsResolver,
    /* singleStoreViewsResolver, */
    validatedPrev,
    validatedCur,
    "push"
  );
  return sqlStatements;
};
var pushSingleStoreSchema = async (imports, drizzleInstance, databaseName) => {
  const { applySingleStoreSnapshotsDiff: applySingleStoreSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const { logSuggestionsAndReturn: logSuggestionsAndReturn4 } = await Promise.resolve().then(() => (init_singlestorePushUtils(), singlestorePushUtils_exports));
  const { singlestorePushIntrospect: singlestorePushIntrospect2 } = await Promise.resolve().then(() => (init_singlestoreIntrospect(), singlestoreIntrospect_exports));
  const { sql } = require("drizzle-orm");
  const db = {
    query: async (query) => {
      const res = await drizzleInstance.execute(sql.raw(query));
      return res[0];
    }
  };
  const cur = await generateSingleStoreDrizzleJson(imports);
  const { schema: prev } = await singlestorePushIntrospect2(db, databaseName, []);
  const validatedPrev = singlestoreSchema.parse(prev);
  const validatedCur = singlestoreSchema.parse(cur);
  const squashedPrev = squashSingleStoreScheme(validatedPrev);
  const squashedCur = squashSingleStoreScheme(validatedCur);
  const { statements } = await applySingleStoreSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    tablesResolver,
    columnsResolver,
    /* singleStoreViewsResolver, */
    validatedPrev,
    validatedCur,
    "push"
  );
  const { shouldAskForApprove, statementsToExecute, infoToPrint } = await logSuggestionsAndReturn4(
    db,
    statements,
    validatedCur,
    validatedPrev
  );
  return {
    hasDataLoss: shouldAskForApprove,
    warnings: infoToPrint,
    statementsToExecute,
    apply: async () => {
      for (const dStmnt of statementsToExecute) {
        await db.query(dStmnt);
      }
    }
  };
};
var startStudioSingleStoreServer = async (imports, credentials2, options) => {
  const { drizzleForSingleStore: drizzleForSingleStore2 } = await Promise.resolve().then(() => (init_studio2(), studio_exports));
  const singleStoreSchema = {};
  const relations = {};
  Object.entries(imports).forEach(([k5, t6]) => {
    if ((0, import_drizzle_orm10.is)(t6, import_singlestore_core4.SingleStoreTable)) {
      const schema6 = (0, import_singlestore_core4.getTableConfig)(t6).schema || "public";
      singleStoreSchema[schema6] = singleStoreSchema[schema6] || {};
      singleStoreSchema[schema6][k5] = t6;
    }
    if ((0, import_drizzle_orm10.is)(t6, import_relations3.Relations)) {
      relations[k5] = t6;
    }
  });
  const setup = await drizzleForSingleStore2(credentials2, singleStoreSchema, relations, [], options?.casing);
  await startServerFromSetup(setup, options);
};
var startServerFromSetup = async (setup, options) => {
  const { prepareServer: prepareServer2 } = await Promise.resolve().then(() => (init_studio2(), studio_exports));
  const server = await prepareServer2(setup);
  const host = options?.host || "127.0.0.1";
  const port = options?.port || 4983;
  const { key, cert } = await certs() || {};
  server.start({
    host,
    port,
    key,
    cert,
    cb: (err2) => {
      if (err2) {
        console.error(err2);
      } else {
        console.log(`Studio is running at ${key ? "https" : "http"}://${host}:${port}`);
      }
    }
  });
};
var upPgSnapshot = (snapshot) => {
  if (snapshot.version === "5") {
    return updateUpToV7(updateUpToV6(snapshot));
  }
  if (snapshot.version === "6") {
    return updateUpToV7(snapshot);
  }
  return snapshot;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  generateDrizzleJson,
  generateMigration,
  generateMySQLDrizzleJson,
  generateMySQLMigration,
  generateSQLiteDrizzleJson,
  generateSQLiteMigration,
  generateSingleStoreDrizzleJson,
  generateSingleStoreMigration,
  pushMySQLSchema,
  pushSQLiteSchema,
  pushSchema,
  pushSingleStoreSchema,
  startStudioMySQLServer,
  startStudioPostgresServer,
  startStudioSQLiteServer,
  startStudioSingleStoreServer,
  upPgSnapshot
});
/*! Bundled license information:

web-streams-polyfill/dist/ponyfill.es2018.js:
  (**
   * @license
   * web-streams-polyfill v3.3.3
   * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors.
   * This code is released under the MIT license.
   * SPDX-License-Identifier: MIT
   *)

fetch-blob/index.js:
  (*! fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)

formdata-polyfill/esm.min.js:
  (*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)

node-domexception/index.js:
  (*! node-domexception. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)

gel/dist/primitives/chars.js:
gel/dist/primitives/buffer.js:
gel/dist/errors/index.js:
gel/dist/primitives/lru.js:
gel/dist/codecs/consts.js:
gel/dist/codecs/ifaces.js:
gel/dist/codecs/boolean.js:
gel/dist/codecs/numbers.js:
gel/dist/codecs/numerics.js:
gel/dist/codecs/text.js:
gel/dist/codecs/uuid.js:
gel/dist/codecs/bytes.js:
gel/dist/codecs/json.js:
gel/dist/datatypes/datetime.js:
gel/dist/codecs/datetime.js:
gel/dist/datatypes/memory.js:
gel/dist/codecs/memory.js:
gel/dist/codecs/pgvector.js:
gel/dist/codecs/codecs.js:
gel/dist/codecs/tuple.js:
gel/dist/datatypes/range.js:
gel/dist/codecs/range.js:
gel/dist/codecs/namedtuple.js:
gel/dist/codecs/array.js:
gel/dist/codecs/enum.js:
gel/dist/codecs/object.js:
gel/dist/codecs/set.js:
gel/dist/codecs/record.js:
gel/dist/codecs/sparseObject.js:
gel/dist/codecs/registry.js:
gel/dist/retry.js:
gel/dist/conUtils.js:
gel/dist/errors/map.js:
gel/dist/errors/resolve.js:
gel/dist/baseConn.js:
gel/dist/scram.js:
gel/dist/rawConn.js:
gel/dist/index.shared.js:
gel/dist/index.node.js:
  (*!
   * This source file is part of the Gel open source project.
   *
   * Copyright 2019-present MagicStack Inc. and the Gel authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   *)

gel/dist/datatypes/dateutil.js:
  (*!
   * Portions Copyright (c) 2019 MagicStack Inc. and the Gel authors.
   * Portions Copyright (c) 2001-2019 Python Software Foundation.
   * All rights reserved.
   * Licence: PSFL https://docs.python.org/3/license.html
   *)

gel/dist/utils.js:
gel/dist/ifaces.js:
gel/dist/primitives/queues.js:
gel/dist/baseClient.js:
gel/dist/reflection/strictMap.js:
gel/dist/reflection/index.js:
  (*!
   * This source file is part of the Gel open source project.
   *
   * Copyright 2020-present MagicStack Inc. and the Gel authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   *)

gel/dist/primitives/event.js:
  (*!
   * This source file is part of the Gel open source project.
   *
   * Copyright 2021-present MagicStack Inc. and the Gel authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   *)

gel/dist/fetchConn.js:
  (*!
   * This source file is part of the Gel open source project.
   *
   * Copyright 2022-present MagicStack Inc. and the Gel authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   *)
*/
